query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a method to calculate the pixel weights of a given geometry. The pixel weights are defined as the proportion of the input geometry that falls within each pixel of a grid. The grid represents the total area of the input geometry, and the weights are relative to this total area.
You are ... | ```java
public List<PixelWeight> getPixelWeights(Geometry geometry) {
List<PixelWeight> pixelWeights = new ArrayList<>();
double totalArea = geometry.calculateArea();
int gridSize = geometry.getGridSize(); // Assuming this method exists to retrieve the grid size
for (int x = 0; x < gridSize; x++) {
... | magicoder | java |
You are tasked with implementing a browser history navigation system. The given code snippet provides a basic structure for managing the navigation functionality. The `GoBack` and `GoForward` methods are responsible for navigating backward and forward in the browser history, respectively. The `CanGoBack` and `CanGoForw... | ```python
class BrowserHistory:
def __init__(self, initial_url):
self.history = [initial_url]
self.current_index = 0
def visit(self, url):
# Add the new URL to the history and update the current index
self.history = self.history[:self.current_index + 1] # Remove URLs after the ... | magicoder | python |
You are given a matrix of integers representing a two-dimensional array. Your task is to write a function to calculate the average of each row and each column in the matrix and then determine if there exists a row whose average is greater than the average of any column. If such a row exists, return its index; otherwise... | ```python
from typing import List
def compare_averages(matrix: List[List[int]]) -> int:
row_sums = [sum(row) for row in matrix]
column_sums = [sum(column) for column in zip(*matrix)]
row_averages = [sum(row) / len(row) for row in matrix]
column_averages = [sum(column) / len(column) for column in zip(*m... | magicoder | python |
You are tasked with implementing a class that creates instances of metro windows with customizable parameters. The class should have a method to create a new metro window instance with the given parameters. The parameters include options to control the window's appearance and behavior, such as whether it should be show... | ```csharp
using System.Windows;
public class MetroWindowFactory
{
public MetroWindow CreateMetroWindow(bool showInTaskbar, bool showActivated, bool topmost, ResizeMode resizeMode, WindowStyle windowStyle, WindowStartupLocation windowStartupLocation, bool showTitleBar, bool showTitle, bool showMinButton, bool showM... | magicoder | csharp |
You are tasked with implementing a function to delete a bookmark for a server using a given API endpoint. The function should handle the case where the server is not bookmarked and should return a boolean value indicating whether the bookmark has been successfully deleted.
You are provided with a code snippet that con... | ```python
import logging
class YuleakClient:
@staticmethod
def delete_request(endpoint):
# Implementation of delete_request method
pass
class Server:
def __init__(self, dashboard_id, server_id, bookmarked):
self.dashboard_id = dashboard_id
self.server_id = server_id
... | magicoder | python |
You are tasked with creating a Python class that represents a leaderboard for a gaming application. The class should allow for the addition of player scores and provide functionality to retrieve the top N players based on their scores.
Create a Python class called `Leaderboard` with the following requirements:
- The c... | ```python
class Leaderboard:
def __init__(self):
self.player_scores = []
def add_score(self, player_name, score):
for i, (name, _) in enumerate(self.player_scores):
if name == player_name:
self.player_scores[i] = (player_name, score)
break
els... | magicoder | python |
You are tasked with implementing a program to evaluate the performance of a text summarization algorithm using the ROUGE (Recall-Oriented Understudy for Gisting Evaluation) metric. ROUGE is commonly used to determine the quality of automatic summaries by comparing them to reference summaries. The given code snippet is ... | ```python
from rouge import Rouge
def calculate_rouge_scores(predicted_summaries, reference_summaries):
rouge = Rouge()
scores = rouge.get_scores(predicted_summaries, reference_summaries, avg=True)
return scores
```
The solution defines the function `calculate_rouge_scores` that utilizes the `Rouge` libra... | magicoder | python |
You are given a class `TreeNode` representing a node in an n-ary tree. The class has an `__init__` method that takes in a value `val` and a list of children nodes `children`.
Your task is to implement a method `max_depth` for the `TreeNode` class, which calculates the maximum depth of the n-ary tree. The maximum depth... | ```python
class TreeNode(object):
def __init__(self, val, children):
self.val = val
self.children = children
def max_depth(self, root: 'TreeNode') -> int:
if not root:
return 0
if not root.children:
return 1
max_child_depth = 0
for child ... | magicoder | python |
You are tasked with implementing a simplified job scheduler in Rust. The job scheduler should support adding jobs, executing them in a specific order, and handling job cancellation.
You are provided with a partial implementation of the `JobScheduler` struct and its associated methods. The `JobScheduler` struct has the... | ```rust
struct Job {
// Define the fields of the Job struct
}
impl Job {
// Implement methods for the Job struct
}
struct JobScheduler {
jobs: Vec<Job>,
current_job_index: usize,
}
impl JobScheduler {
fn new() -> JobScheduler {
JobScheduler {
jobs: Vec::new(),
curr... | magicoder | rust |
You are tasked with creating a program that generates a calendar for a specific month and year. Your program should take input for the month and year, and then output the calendar for that month in a specific format.
Write a Python function `generate_monthly_calendar(month, year)` that takes two integer parameters: `m... | ```python
import calendar
def generate_monthly_calendar(month, year):
cal = calendar.TextCalendar(calendar.SUNDAY)
month_calendar = cal.formatmonth(year, month)
return month_calendar
```
The `generate_monthly_calendar` function uses the `calendar` module in Python to generate the calendar for the specifie... | magicoder | python |
You are tasked with implementing a geofence management system. Geofences are virtual perimeters for real-world geographic areas. Your task is to create a class that manages a collection of geofences and provides methods for adding, removing, and updating geofences.
You are given a partial code snippet for the `Geofenc... | ```java
private void ensureGeofenceIsMutable() {
if (geofenceBuilder_ != null) {
geofence_ = geofenceBuilder_.build(); // Assuming build() returns a mutable geofence collection
geofenceBuilder_ = null; // Set geofenceBuilder_ to null to indicate the geofence collection is now mutable
}
}
privat... | magicoder | java |
You are tasked with creating a script to automate the setup of a CouchDB cluster. The script should be able to handle both single-node and multi-node clusters. For a single-node cluster, the script should create the necessary system databases directly. For a multi-node cluster, the script should initiate the cluster se... | ```bash
#!/bin/bash
COUCHDB_USER="admin"
COUCHDB_PASSWORD="password"
DB_PORT="5984"
CLUSTER_NODES=3 # Example: Set the number of cluster nodes
if [ $CLUSTER_NODES -gt 1 ]; then
# multi-node cluster, initiate the cluster setup process
curl -H "Content-Type: application/json" -X POST http://$COUCHDB_USER:$COUCHDB_... | magicoder | shell |
You are tasked with implementing a function `upgrade()` that takes an array of integers as input and returns a new array where each element is the sum of itself and all previous elements in the input array. For example, given the input array `[1, 2, 3, 4]`, the output array should be `[1, 3, 6, 10]` because the first e... | ```python
from typing import List
def upgrade(arr: List[int]) -> List[int]:
result = []
total = 0
for num in arr:
total += num
result.append(total)
return result
``` | magicoder | python |
You are tasked with implementing a simplified task execution system. The system consists of a task queue, a result queue, and a worker that processes tasks. The worker executes tasks using different executors, such as TERRAFORM, and then places the results in the result queue. Your goal is to implement the `execute_tas... | ```python
class TaskWorker:
def __init__(self, task_queue, result_queue, conn, logger):
self.task_queue = task_queue
self.result_queue = result_queue
self.conn = conn
self.logger = logger
def execute_task(self):
while True:
taskval = self.task_queue.get() # ... | magicoder | python |
You are tasked with creating a function that simulates a simplified version of a real-time event polling system for a chat application. The function will receive a user object, an explicit room ID, and a pagination configuration. The pagination configuration includes a "from_token" and a "limit" for the number of event... | ```python
async def poll_for_events(user, explicit_room_id, pagination_config) -> List[Event]:
if pagination_config.get('from_token'):
from_token = pagination_config['from_token']
else:
from_token = self.event_sources.get_current_token()
limit = pagination_config['limit']
room_ids, is_... | magicoder | python |
You are given a code snippet that involves the manipulation of a variable `place_holder` based on certain conditions. Your task is to understand the logic behind the code and implement a function that replicates the behavior of the code snippet.
You need to write a function `calculate_placeholder` that takes the follo... | ```python
def calculate_placeholder(M, m, n, positive, min_inf):
if not min_inf:
place_holder = (M + (n - 1) * (M - m)) + positive
else:
place_holder = (m + (n - 1) * (m - M)) - positive
return place_holder
# Test cases
print(calculate_placeholder(5, 2, 3, True, False)) # Output: 13
print(... | magicoder | python |
You are tasked with implementing a function that calculates the area of a 2D polygon given its vertices. The vertices are represented as a list of 2D points in the form (x, y). The function should return the area of the polygon as a floating-point number. The vertices are listed in clockwise or counterclockwise order, ... | ```python
def calculate_polygon_area(vertices):
n = len(vertices)
area = 0.0
for i in range(n):
x1, y1 = vertices[i]
x2, y2 = vertices[(i + 1) % n] # Wrap around to the first vertex for the last edge
area += (x1 * y2 - x2 * y1)
return abs(area) / 2.0
```
The `calculate_polygon_a... | magicoder | python |
You are given a circular track with N segments, numbered from 0 to N-1. Each segment has a specific length associated with it. Additionally, there is a starting point S on the track, and a cyclist who starts at segment 0. The cyclist moves along the track in a circular manner, adding the length of the current segment t... | ```python
def count_matches(N, S, l):
c = 0
S -= 1 # Adjust S to 0-based index
ans = 0
for i in l:
ans += c == S
c = (c + i + N) % N # Update cyclist's position
ans += c == S
return ans
# Test the function
N = 5
S = 2
l = [3, 1, 4, 1, 5]
print(count_matches(N, S, l)) # Output... | magicoder | python |
You are working on a data processing project that involves reading and manipulating JSON files. Your task is to create a Python function that reads a directory containing multiple JSON files, processes the data from each file, and returns a summary of the processed data.
You are provided with the following code snippe... | ```python
import os
import json
def process_json_files(directory_path):
if not os.path.isdir(directory_path):
return "Directory not found"
file_summary = {}
for file_name in os.listdir(directory_path):
if file_name.endswith('.json'):
file_path = os.path.join(directory_path, fil... | magicoder | python |
You are working on a quantum computing simulation project and need to implement a function to calculate the combined effect of two quantum gates: Rz and Ry. The Rz and Ry gates are represented by matrix exponentials and are used to manipulate the state of a quantum system. The function takes three parameters: detuning,... | ```python
import numpy as np
def sigmaz():
return np.array([[1, 0], [0, -1]])
def sigmay():
return np.array([[0, -1j], [1j, 0]])
def combined_effect(detuning, signal_strength, dt):
Rz = np.linalg.expm(1j * detuning / 2 * sigmaz() / 2 * dt)
Ry = np.linalg.expm(1j * 2 * signal_strength * sigmay() / 2 *... | magicoder | python |
You are tasked with creating a Python function that processes a list of strings representing commands and their arguments. The function should execute the commands and return the final state of a system based on the commands executed.
You are given a list of strings, where each string represents a command in the follo... | ```python
from typing import List
def process_commands(commands: List[str]) -> List[str]:
system_state = []
for command in commands:
action, *args = command.split()
if action == "add":
system_state.append(args[0])
elif action == "remove":
if args[0] in system_sta... | magicoder | python |
You are tasked with implementing a data transformation pipeline in Python for integrating two datasets related to materials science. The code snippet provided is a part of the pipeline setup and involves the initialization of a data integration class. Your task is to complete the implementation of the data integration ... | ```python
class DataIntegration(BaseClass):
def __init__(self, oxidation_states, robocrys, query, projection, **kwargs):
self.robocrys.key = "material_id"
self.oxidation_states.key = "material_id"
super().__init__(
source=oxidation_states,
target=robocrys,
... | magicoder | python |
You are tasked with creating a Python script that processes a list of tasks using Celery, a distributed task queue. Your script should define a Celery task that takes a list of integers as input, squares each integer, and returns the sum of the squared values. Additionally, the script should configure Celery to use Red... | ```python
# Import the necessary modules and configure Celery to use Redis as the message broker and backend
from celery import Celery
app = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0')
# Define a Celery task called `sum_of_squares` that takes a list of integers as input, squ... | magicoder | python |
You are tasked with creating a function that processes a list of integers and returns the maximum product that can be obtained by multiplying any three integers from the list. If the list contains less than three integers, the function should return 0.
You need to implement the function `maxProductOfThree` that takes ... | ```swift
func maxProductOfThree(_ nums: [Int]) -> Int {
let sortedNums = nums.sorted()
let n = nums.count
return max(sortedNums[0] * sortedNums[1] * sortedNums[n-1], sortedNums[n-1] * sortedNums[n-2] * sortedNums[n-3])
}
```
The `maxProductOfThree` function first sorts the input array of integers. Then, it... | magicoder | swift |
You are tasked with implementing a custom widget class in Python that extends the functionality of an existing widget class. The custom widget, named `CustomWidget`, needs to inherit from the `TtkResizeWidget` class and have additional features related to managing a TV (Table View) component. The `CustomWidget` class s... | ```python
class TtkResizeWidget:
def __init__(self, *args, **kw):
pass
def configure(self, item, **kw):
pass
class CustomWidget(TtkResizeWidget):
def __init__(self, tv, *args, **kw):
super().__init__(*args, **kw)
self.tv = tv
def configure(self, item, **kw):
# ... | magicoder | python |
You are working on a software project that involves creating a parameter management system. The system has a class `Params` with virtual member functions for setting and retrieving parameter values. You need to implement a concrete subclass of `Params` called `ConcreteParams` that provides the functionality for setting... | ```cpp
#include <iostream>
#include <map>
#include <vector>
#include <memory>
// Define the MapAgentIdListFloat type
using MapAgentIdListFloat = std::map<int, std::vector<float>>;
// Define the Params class
class Params {
public:
virtual void SetMapAgentIdListFloat(const std::string& param_name,
... | magicoder | cpp |
You are tasked with creating a unit test for a method that updates a "terimaBarang" (received goods) object in a system. The code snippet provided is a part of the unit test for this method. The test uses a repository to update a fake "terimaBarang" object and then asserts that the updated object matches the fake objec... | ```php
public function testUpdateTerimaBarang()
{
// Create a fake terimaBarang object for testing
$fakeTerimaBarang = [
'attribute1' => 'value1',
'attribute2' => 'value2',
// Add other attributes as needed
];
// Update the terimaBarang using the repository's update method
$... | magicoder | php |
You are tasked with creating a program that processes a list of student scores and returns the top N students based on their scores. You are given a class `Student` with properties `Name` (string) and `Score` (int). You need to implement a method `GetTopStudents` that takes a list of `Student` objects and an integer N,... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
public class Student
{
public string Name { get; set; }
public int Score { get; set; }
}
public class Program
{
public List<Student> GetTopStudents(List<Student> students, int N)
{
return students.OrderByDescending(s ... | magicoder | csharp |
You are tasked with implementing a simplified peer-to-peer (P2P) server class in C++. The provided code snippet contains part of the implementation for the server, including the `connect_to_peer` and `stop_server` methods. Your task is to complete the implementation of the `p2p_server` class by adding the missing metho... | ```cpp
class CPeer {
public:
bool connected() {
// Implementation for checking if the peer is connected
return false;
}
bool connect_peer() {
// Implementation for connecting the peer
return true;
}
};
class p2p_server {
public:
bool connect_to_peer(CPeer* peer) {
... | magicoder | cpp |
You are working on a project related to astrophysics and need to calculate the wavelengths of spectral lines in the Lyman series. The Lyman series describes the wavelengths of electromagnetic radiation emitted by hydrogen atoms when an electron transitions from a higher energy level to the first energy level (n=1).
Yo... | ```python
import collections
# Constants
lya_center = 1215.67 # Wavelength of Lyman-alpha line in Angstroms
# Function to calculate the Rydberg ratio
def rydberg_ratio(m, n):
return abs(1. / (m * m) - 1. / (n * n))
# Function to calculate the ratio for the Lyman series
def ly_series_ratio(n):
return rydberg... | magicoder | python |
You are tasked with implementing a preprocessing tool for Chinese natural language processing (NLP). The tool should be able to perform several essential preprocessing tasks on Chinese text, including tokenization, part-of-speech (POS) tagging, and named entity recognition (NER).
Your task is to create a Python class... | ```python
# Import the necessary library
from jionlp import NER, PosTagging, WordSegmentation
class ChineseNLPProcessor:
def __init__(self):
# Initialize the necessary components from JioNLP library
self.ner = NER()
self.pos_tagging = PosTagging()
self.word_segmentation = WordSegmen... | magicoder | python |
You are tasked with creating a Python program that interacts with a SQLite database to perform various operations. The program should include functions to create a new database, create a table, insert data into the table, retrieve data from the table, and delete the database.
Your program should provide a command-line... | ```python
import sqlite3
import os
# Function to create a new SQLite database
def create_db(db_name):
if not os.path.exists(db_name):
conn = sqlite3.connect(db_name)
conn.close()
print(f"Database '{db_name}' created successfully.")
else:
print(f"Database '{db_name}' already exis... | magicoder | python |
You are given a snippet of code that is part of a function. Your task is to complete the function by implementing the missing part. The function takes in an array of integers and should return true if the array is sorted in non-decreasing order, and false otherwise. The given code snippet is as follows:
```java
public... | ```java
public boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
```
The solution iterates through the array and checks if each element is less than or equal to the next element. If at any point t... | magicoder | java |
You are tasked with implementing a class that represents a simple bank account. The class should have methods to deposit funds, withdraw funds, and check the current balance. Additionally, the class should keep track of the total number of transactions (deposits and withdrawals) made on the account.
You need to implem... | ```python
class BankAccount:
def __init__(self, initial_balance):
self._balance = initial_balance
self._transactions = 0
def deposit(self, amount):
self._balance += amount
self._transactions += 1
def withdraw(self, amount):
if self._balance >= amount:
se... | magicoder | python |
You are tasked with implementing a Python decorator that adds a set of features to a function. The code snippet provided is a simplified version of the decorator implementation. The `feature_list` is a list of feature names, and the `function` is the original function to which the features will be added.
Your task is ... | ```python
def add_features_to_function(feature_list, function):
def _AddFeatures(function):
for feature in feature_list:
AnnotatedFunctions._AddFunction('Feature:%s' % feature, function)
return AnnotatedFunctions._AddFunction('Feature', function)
return _AddFeatures
```
The `add_feat... | magicoder | python |
You are tasked with creating a program that analyzes HTML code to identify the number of sections and their respective classes. Your program should read the HTML code and output the count of sections and the classes associated with each section.
For example, given the following HTML code snippet:
```
<h1>Category Deta... | ```python
from bs4 import BeautifulSoup
def analyze_html(html_code):
soup = BeautifulSoup(html_code, 'html.parser')
sections = soup.find_all('section')
section_count = len(sections)
print(f"Number of sections: {section_count}")
for i, section in enumerate(sections, start=1):
secti... | magicoder | python |
You are given a Rust function `solve_part2` that takes a reference to a vector of `Move` objects and returns an `isize` value. The `Move` type is not explicitly defined in the code snippet, but it is assumed to be a custom type representing different moves in a game or puzzle.
Your task is to implement the `solve_part... | ```rust
// Define the Move type if not already defined
struct Move {
// Define the fields and methods of the Move type as per the game or puzzle requirements
// Example:
// action: String,
// steps: isize,
}
// Implement the solve_part2 function
fn solve_part2(moves: &Vec<Move>) -> isize {
// Imple... | magicoder | rust |
You are tasked with creating a Python class that interacts with a storage system to manage tables, schemas, and data. Your task is to implement the `StorageManager` class with the following methods:
1. `create_table(table_name, schema_file)`: This method should create a new table in the storage system using the provid... | ```python
class StorageManager:
def __init__(self, storage):
self.storage = storage
def create_table(self, table_name, schema_file):
# Assume that the storage object has a method to create a table using the provided schema file
self.storage.create_table(table_name, schema_file)
... | magicoder | python |
You are tasked with creating a simple login system for GoozOS, a fictional operating system. The system should prompt the user for a username and password, and grant access if the provided credentials match the predefined values. Your task is to complete the Python code snippet provided below to implement the login sys... | ```python
password = "secretpassword"
username = "user123"
login_flag = False
print("Welcome to GoozOS")
usr = input("Username: ")
pwd = input("Password: ")
if usr == username and pwd == password:
login_flag = True
print("Login successful")
else:
print("Login failed")
```
In the solution, the predefined ... | magicoder | python |
You are tasked with designing a role-based access control system for a web application. The application has a controller method that handles the deletion of records, and it is annotated with various security and logging annotations. Your goal is to create a role-based access control system to determine whether a user h... | ```java
public class RoleBasedAccessControlSystem {
public boolean hasPermission(String userRole, List<String> userPermissions, String requiredPermission) {
// Check if the user has the required permission
return userPermissions.contains(requiredPermission);
}
public void logAccess(String t... | magicoder | java |
You are tasked with creating a program to analyze and display the publishing activity of a blog over a given period. The program should take into account the month and year filters provided by the user and generate a report showing the number of published posts for each month within the specified year.
Your task is to... | ```php
function publishingActivity($filters) {
$query = Post::query(); // Assuming Post is the model representing the 'posts' table
if (isset($filters['month'])) {
$month = $filters['month'];
$monthNumber = date('m', strtotime($month . ' 1')); // Convert human-readable month to its numerical re... | magicoder | php |
You are tasked with creating a program that reads a series of integers from a file, performs a specific operation on each integer, and then writes the results back to the file. The program should also calculate and output the sum of all the modified integers.
You are given a code snippet that opens a file named "file.... | ```python
# Open the file in read mode to read the integers
with open("file.txt", "r") as file:
integers = list(map(int, file.read().split()))
# Calculate the squares of the integers and write them back to the file
with open("file.txt", "w") as file:
squared_integers = [str(num**2) for num in integers]
fil... | magicoder | python |
You are tasked with creating a Python function that processes a list of video objects and returns a dictionary containing the ownership permission policy for each video. The ownership permission policy is determined based on the video's ownership status and the user's role. The ownership status can be "owned", "shared"... | ```python
class Video:
def __init__(self, title, ownership_status):
self.title = title
self.ownership_status = ownership_status
def get_ownership_permission_policy(videos, user_role):
permission_policy = {}
for video in videos:
if user_role == "admin":
permission_policy[... | magicoder | python |
You are given a Python code snippet that processes a depth image represented as a 2D matrix. The code snippet contains operations to handle duplicate indices, update the depth values, and perform normalization. Your task is to understand the code and implement a function to perform a specific operation on the depth mat... | ```python
import numpy as np
from collections import Counter
def update_depth_matrix(matrixSize, velo_pts_im, depth, depth_scale):
m, n = matrixSize
inds = np.ravel_multi_index((velo_pts_im[:, 1], velo_pts_im[:, 0]), (m, n))
dupe_inds = [item for item, count in Counter(inds).items() if count > 1]
for d... | magicoder | python |
You are tasked with implementing a Python class that represents a file system path. The class should provide methods for navigating and manipulating the path, similar to the functionality provided by the `os.path` module in Python.
Your task is to create a class `FileSystemPath` with the following methods:
1. `__init... | ```python
import os
class FileSystemPath:
def __init__(self, path: str):
self.path = path
def get_path(self) -> str:
return self.path
def is_file(self) -> bool:
return os.path.isfile(self.path)
def is_dir(self) -> bool:
return os.path.isdir(self.path)
def join(se... | magicoder | python |
You are working on a programming language interpreter that supports lazy namespace creation and usage. The code snippet provided is a part of the interpreter implementation. The `root` object represents the root namespace, and the `create_lazy_namespace` method is used to create a new lazy namespace within the root nam... | ```rust
use std::collections::HashMap;
// Define the Value and Scope types
enum Value {
Bool(bool),
// Add other value types as needed
}
struct Scope {
// Define the scope structure
name: String,
values: HashMap<String, Value>,
}
impl Scope {
fn new(name: &str) -> Scope {
Scope {
... | magicoder | rust |
You are tasked with implementing a simulated annealing optimizer for a given optimization problem. Simulated annealing is a probabilistic optimization algorithm that is used to find the global optimum in a large search space. The algorithm starts with an initial solution and iteratively explores the search space by acc... | ```cpp
#include <rr_common/planning/annealing_optimizer.h>
#include <rr_common/planning/planning_utils.h>
#include <parameter_assertions/assertions.h>
#include <cmath>
#include <random>
class SimulatedAnnealingOptimizer : public Optimizer {
public:
Solution optimize(const Solution& initial_solution) {
Solu... | magicoder | cpp |
You are tasked with implementing a custom error type for handling encoding errors in a text processing application. The error type, `EncodingError`, should provide specific error variants for different types of encoding issues. The provided code snippet shows the implementation of the `Display` trait for the `EncodingE... | ```rust
use std::fmt;
// Custom error type for encoding errors
#[derive(Debug)]
enum EncodingError {
InvalidAppSegment(u8),
InvalidCharacter(char),
InvalidFormat(String),
}
impl fmt::Display for EncodingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
... | magicoder | rust |
You are tasked with creating a Rust library for controlling General Purpose Input/Output (GPIO) pins on a microcontroller. The library should provide an interface for interacting with the GPIO pins, allowing users to set pin modes, read and write pin values, and configure interrupts.
Your task is to implement the `gpi... | ```rust
// Define the GpioPin trait
pub trait GpioPin {
fn set_mode(&self, mode: PinMode);
fn read_value(&self) -> PinValue;
fn write_value(&self, value: PinValue);
fn configure_interrupt(&self, interrupt: InterruptType);
}
// Define the PinMode enum
pub enum PinMode {
Input,
Output,
// Add... | magicoder | rust |
You are tasked with implementing a custom view in Swift that includes a gradient view and a background view container. The gradient view should be a subview of the custom view and should have a gradient layer applied to it. The background view container should also be a subview of the custom view and should have a top ... | ```swift
private func setupView() {
backgroundColor = .clear
// Add gradientView as a subview and configure its gradient layer
addSubview(gradientView)
gradientView.frame = bounds
gradientView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
gradientView.setGradient(colors: [UIColor.red... | magicoder | swift |
You are tasked with implementing a custom string type in Rust that allows for efficient manipulation and conversion of strings with different lifetimes. The custom string type, `Kstr`, is designed to represent a borrowed string slice with a specific lifetime. Additionally, you need to implement a method to convert the ... | ```rust
/// Represents a borrowed string slice with a specific lifetime.
struct Kstr<'a> {
inner: &'a str,
}
impl<'a> Kstr<'a> {
/// Creates a new `Kstr` instance from a borrowed string slice.
fn borrowed(inner: &'a str) -> Self {
Kstr { inner }
}
/// Converts the borrowed string slice int... | magicoder | rust |
You are tasked with implementing a command-line processor for a fictional application. The `CCommandLineProcessor` class needs to be extended to support the processing of command-line parameters. The `Process` method should parse the input parameters and perform the necessary actions based on the provided commands. The... | ```cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
class CCommandLineProcessor {
public:
bool Process(const wchar_t* szParams) {
std::wstring params(szParams);
std::transform(params.begin(), params.end(), params.begin(), ::tolower); // Convert to lowercase for case-... | magicoder | cpp |
You are tasked with implementing a function to calculate the gradient magnitude of a given matrix. The gradient magnitude is a measure of the change in intensity or color in an image, and it is commonly used in image processing and computer vision applications.
You are provided with a Python code snippet that calls a ... | ```python
import numpy as np
def gradient_magnitude(d_x):
# Calculate the gradient magnitude using Sobel operator
d_x = np.array(d_x, dtype=np.float32) # Convert input to float32 for gradient calculation
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) # Sobel operator for x-direction
sobel_y... | magicoder | python |
You are tasked with creating a program that analyzes a given software license text to extract specific information. The license text follows a standard format, with the permissions and conditions specified in a block of text. Your program should extract and display the following information:
1. List of permissions gran... | ```python
import re
def analyze_license_text(license_text):
permissions = re.findall(r'\b\w+\b', license_text.split('subject to the following conditions:')[0])
conditions = re.search(r'subject to the following conditions:(.*)THE SOFTWARE IS PROVIDED', license_text, re.DOTALL).group(1).strip()
warranty_disc... | magicoder | python |
You are tasked with implementing a custom `Answer` class in Java that represents an answer to a question in a quiz application. The `Answer` class should have the following properties and behaviors:
Properties:
- `aid` (answer ID): an integer representing the unique identifier for the answer.
- `qid` (question ID): an... | ```java
public class Answer {
private Integer aid;
private Integer qid;
private String answerText;
private boolean isCorrect;
public Answer(Integer aid, Integer qid, String answerText, boolean isCorrect) {
this.aid = aid;
this.qid = qid;
this.answerText = answerText;
... | magicoder | java |
You are tasked with implementing a class that simulates a simple queue data structure using a stack. The class should support the following operations:
1. `Enqueue(int value)`: Add an element to the end of the queue.
2. `Dequeue()`: Remove the element at the front of the queue and return its value.
3. `IsEmpty()`: Retu... | ```csharp
public void Enqueue(int value)
{
stack.Push(value);
}
public int Dequeue()
{
if (stack.Count == 0)
{
throw new InvalidOperationException("Queue is empty");
}
// Transfer elements to a temporary stack
Stack<int> tempStack = new Stack<int>();
while (stack.Count > 1)
{
... | magicoder | csharp |
You are tasked with implementing a deck-building algorithm for a collectible card game. The algorithm should load settings from a file, perform a search to find the best deck, and then display the best deck along with its probability of winning. Additionally, it should provide an option to dump additional information i... | ```python
class DeckBuilder:
def __init__(self):
self.settings = None
self.best_deck = None
self.best_prob = 0.0
def load_settings(self, file_name):
# Implement loading settings from the specified file
# Example: self.settings = load_settings_from_file(file_name)
... | magicoder | python |
You are tasked with implementing a JSON schema validator that can resolve and validate JSON references. JSON references are defined using the "$ref" keyword, which allows a JSON object to reference another part of the document. The referenced part is identified by a JSON Pointer, which is a string containing a sequence... | ```javascript
function validateJSONWithSchema(json, schema) {
const resolveReference = (ref, obj) => {
const tokens = ref.split('/').slice(1);
let current = obj;
for (const token of tokens) {
current = current[token];
}
return current;
};
const validate = (data, schema) => {
if (sch... | magicoder | javascript |
You are tasked with implementing a trait for a custom type in Rust. The trait, `MemoryInputStreamExt`, extends the functionality of the `MemoryInputStream` type, which is a part of the `gio` library in Rust. Your goal is to implement a method for this trait that reads data from the input stream.
Your task is to comple... | ```rust
impl<O: IsA<MemoryInputStream>> MemoryInputStreamExt for O {
fn read_data(&self, size: usize) -> Result<Vec<u8>, glib::Error> {
let mut buffer = vec![0; size];
match self.read(&mut buffer) {
Ok(bytes_read) => {
buffer.resize(bytes_read, 0);
Ok(buff... | magicoder | rust |
You are tasked with implementing a simplified version of a class-based object creation system in Python. Your goal is to create a class that can parse a JSON dictionary and instantiate objects based on the data provided in the dictionary.
You are given the following code snippet as a starting point:
```python
for obj... | ```python
class ObjectCreator:
def new(self, cls_name, attr_dict):
try:
cls = globals()[cls_name] # Get the class object from the global namespace
obj = cls(**attr_dict) # Instantiate the class with the provided attributes
return obj
except KeyError:
... | magicoder | python |
You are tasked with creating a program that processes command-line arguments to extract the name of the exported source file. The program should handle both default and explicitly provided output file names.
Your program should accept the following command-line arguments:
1. `-o <output_file>`: Specifies the name of t... | ```python
import argparse
import os
def get_exported_source_file_name(args):
parser = argparse.ArgumentParser(description='Process command-line arguments')
parser.add_argument('-o', dest='output_file', help='Name of the exported source file')
parsed_args = parser.parse_args(args)
if parsed_args.output... | magicoder | python |
You are tasked with writing a function to convert a given positive integer into its binary representation. The function should take an integer `num` as input and return a string representing the binary equivalent of the input number.
For example, if the input `num` is 13, the function should return the string '1101', ... | ```python
def decimal_to_binary(num):
if num == 0:
return '0' # Special case for 0
result = ''
while num > 0:
result = str(num % 2) + result # Append the remainder to the result
num = num // 2 # Update num by integer division
return result
```
The `decimal_to_binary` function... | magicoder | python |
You are tasked with creating a Python class that generates SQL queries for altering table columns with default values. Your class should have a method to generate and execute the SQL query for setting a default value using a sequence. The provided code snippet is part of the class method that executes the generated SQL... | ```python
class TableAlterer:
def __init__(self, table_name, column_name, sequence_name):
self._rname = table_name
self._id = self.Column(column_name)
self._sequence_name = sequence_name
def generate_default_query(self):
query = "ALTER TABLE %s ALTER COLUMN %s SET DEFAULT NEXTVA... | magicoder | python |
You are tasked with implementing a custom hook in a React application that optimizes the rendering performance by caching the result of a computationally expensive operation. The provided code snippet exports a custom hook called `useCachedNode` from a file named `useCachedNode.js`. Your task is to create the implement... | ```javascript
// useCachedNode.js
import { useMemo } from 'react';
// Custom hook for caching the result of a computationally expensive operation
export function useCachedNode() {
const cache = useMemo(() => new Map(), []);
return (key, computeNode) => {
if (cache.has(key)) {
return cache.get(key);
... | magicoder | javascript |
You are tasked with implementing a function that checks the correctness of the scope of delimiters in a multi-line string. The delimiters to be checked are the dollar sign ($) and the at symbol (@). The function should return True if the delimiters are correctly scoped and False if they are not.
The delimiters are cor... | ```python
def is_scope_correct_if_delimiter_not_at_bol(input_string: str) -> bool:
stack = []
for char in input_string:
if char == '$':
stack.append('$')
elif char == '@':
if stack and stack[-1] == '$':
stack.pop()
else:
return ... | magicoder | python |
You are tasked with creating a program that simulates a simple inventory management system for a retail store. The system should allow users to add, remove, and update products in the inventory. Additionally, it should be able to display the current inventory and calculate the total value of the inventory based on the ... | ```php
class Product
{
public $name;
public $price;
public $quantity;
public function __construct($name, $price, $quantity)
{
$this->name = $name;
$this->price = $price;
$this->quantity = $quantity;
}
}
class Inventory
{
private $products = [];
public function ... | magicoder | php |
You are tasked with implementing a function that will handle directory monitoring and file listing. The function should be able to handle exceptions and raise custom exceptions when necessary. You are given a code snippet that demonstrates part of the functionality required for this task.
Your task is to implement the... | ```python
import os
import errno
class NoSuchDir(Exception):
pass
def handle_directory(base, is_dir):
if is_dir:
try:
files = os.listdir(base)
except OSError as e:
if e.errno in (errno.ENOTDIR, errno.ENOENT):
raise NoSuchDir('The dir {0} does not exist'.... | magicoder | python |
You are tasked with creating a Python class that interacts with a web service to fetch and process data. The class should have a method `fetch_moves` that takes two `datetime` objects as input and retrieves information from a web page. The method should handle the login process, make an HTTP request, and extract releva... | ```python
import datetime
import requests
class WebDataFetcher:
class Urls:
OVERVIEW = 'https://example.com/overview'
def __init__(self, username, password):
self.username = username
self.password = password
self.session = requests.Session()
def _login(self):
login... | magicoder | python |
You are tasked with creating a custom text view component for a mobile application using React Native. The custom text view should have the ability to display text with a specified font, size, color, and alignment. Additionally, it should support the functionality to handle user interactions such as tapping and long-pr... | ```objc
// Created by Juan J LF on 8/30/21.
//
import Foundation
import UIKit
@objc(TextView)
class TextView: RCTViewManager {
override func view() -> UIView! {
let textView = UITextView()
textView.isEditable = false
textView.isSelectable = false
textView.dataDetectorTypes = .all
... | magicoder | objc |
You are working on a decentralized finance (DeFi) project called Badger, which involves deploying and setting up logic for various components. One of the tasks involves deploying a logic contract called "CurveTokenWrapper" and setting it as the CurveTokenWrapper for a bridge adapter. The code snippet provided demonstra... | ```python
def deploy_and_setup_logic(badger, CurveTokenWrapper) -> None:
badger.deploy_logic(CurveTokenWrapper, CurveTokenWrapper)
logic = badger.logic[CurveTokenWrapper]
bridge.adapter.setCurveTokenWrapper(logic, {"from": badger.devMultisig})
``` | magicoder | python |
You are tasked with creating a Python decorator that measures the execution time and memory usage of a given function. Your decorator should take the name of the function as an argument and print the time taken for execution and the memory used by the function. You can use the `time` and `resource` modules to accomplis... | ```python
import time
import resource
import functools
def timer_memory(name):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
start_memory = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
result = func(*args... | magicoder | python |
You are tasked with creating a Python function that manipulates files and directories using the `pathlib` module. Your function should take in a directory path and a list of filenames, and then create new files within the specified directory. Additionally, the function should create migration files for a database, foll... | ```python
from pathlib import Path
def create_files_and_migrations(directory_path, file_names, database, environment):
# Create files within the specified directory
for file_name in file_names:
file_path = Path(directory_path, file_name)
file_path.touch()
# Create migration files for the s... | magicoder | python |
You are tasked with implementing a PHP interface for a meeting management system. The interface, named `CampaignAwareInterface`, is intended to be used by classes that need to be associated with a campaign. The interface contains a method signature for retrieving the associated campaign.
Your task is to complete the `... | ```php
namespace amillot\MeetingBundle\Model\Traits;
use amillot\MeetingBundle\Model\CampaignInterface;
interface CampaignAwareInterface
{
/**
* @return CampaignInterface|null
*/
public function getCampaign(): ?CampaignInterface;
}
```
```php
namespace amillot\MeetingBundle\Model;
use amillot\Meet... | magicoder | php |
You are tasked with creating a password validation function that checks whether a given password meets certain criteria. The function should take a password as input and return True if the password meets the criteria, and False otherwise.
The password criteria are as follows:
1. The password must be at least 8 charact... | ```python
def validate_password(password, username):
if len(password) < 8:
return False
if not any(char.isupper() for char in password):
return False
if not any(char.islower() for char in password):
return False
if not any(char.isdigit() for char in password):
return Fals... | magicoder | python |
You are tasked with implementing a function to calculate the aligned size based on the input size, with a specific alignment requirement. The alignment requirement depends on whether the application is running on a 32-bit system or a 64-bit system. The alignment calculation should consider the architecture and adjust t... | ```cpp
#include <iostream>
bool IsRunningOnWow64() {
// Assume implementation of IsRunningOnWow64() function
return dwCachedWow64; // Placeholder for the actual implementation
}
inline size_t ALIGNUP(size_t nSize) {
if (IsRunningOnWow64()) {
// If running on a 64-bit system, use 64-bit alignment
... | magicoder | cpp |
You are tasked with creating a script to automate the process of joining worker nodes to a Kubernetes cluster. The script should generate the necessary join command for the worker nodes to connect to the cluster's master node. The join command should be modified to use a custom command `cks cluster join --master` inste... | ```bash
#!/bin/sh
# Generate the join command for the worker nodes
join_command=$(kubeadm token create --print-join-command --ttl 0)
# Modify the join command to use custom command and replace ca-cert-hash
modified_join_command=$(echo $join_command | sed 's/kubeadm join/cks cluster join --master/g' | sed 's/discovery-... | magicoder | shell |
You are working on a Python web application project and need to manage its dependencies and entry points. The project structure includes a `setup.py` file, which is used to define the project's metadata and dependencies. The `setup` function is used to configure the project's details, including its name, dependencies, ... | ```python
import re
def extract_entry_points(entry_points: str) -> dict:
entry_points_dict = {}
current_section = None
for line in entry_points.splitlines():
line = line.strip()
if line.startswith('[') and line.endswith(']'):
current_section = line[1:-1]
entry_points... | magicoder | python |
You are tasked with creating a Python class method that interacts with a database using SQLAlchemy. Your task is to complete the implementation of the method `get_database_version` in the given Python class. The method should connect to the database using the provided `db_url` and retrieve the database version. If the ... | ```python
from sqlalchemy import create_engine
class DatabaseManager:
gxy_db_url = "example_db_url"
def __init__(self, gxy_db_url):
self.gxy_db_url = gxy_db_url
def _get_gxy_alembic_db_version(self, engine):
# Placeholder implementation
return "alembic_version"
def _get_gxy_s... | magicoder | python |
You are tasked with implementing a function to convert a given string to uppercase using C++. The function should modify the input string in place and return a reference to the modified string. You are not allowed to use any built-in functions or libraries for case conversion.
You need to implement the `toupper` funct... | ```cpp
ccstd::string &StringUtil::toupper(ccstd::string &str) {
for (char &c : str) {
if (c >= 'a' && c <= 'z') {
c = c - 'a' + 'A'; // Convert lowercase letter to uppercase
}
}
return str;
}
```
The `toupper` function iterates through each character in the input string and che... | magicoder | cpp |
You are working on a 3D mesh processing application and need to calculate the vertex normal vectors for a given mesh. The mesh is represented by a set of vertices and triangular elements. Each vertex has an associated index, and each triangular element is defined by three vertex indices. The goal is to calculate the no... | ```python
import numpy as np
def calculate_vertex_normals(tri_elements, tri_normal_vec, surf_vindex):
vtx_normal_vec = np.zeros((surf_vindex.size, 3))
for i, iv in enumerate(surf_vindex):
iv_tri_index = np.argwhere(tri_elements == iv)[:, 0]
iv_tri_nv = tri_normal_vec[iv_tri_index]
vtx_n... | magicoder | python |
You are tasked with implementing a function that simulates a simple asynchronous task scheduler. The scheduler should be able to execute a series of tasks in a non-blocking manner, where each task takes a certain amount of time to complete. Your goal is to design a scheduler that can efficiently manage the execution of... | ```python
import asyncio
async def task_execution(task_id, duration):
await asyncio.sleep(duration)
print(f"Task {task_id} completed")
async def schedule_tasks(tasks):
await asyncio.gather(*(task_execution(task_id, duration) for task_id, duration in tasks))
tasks = [(1, 3), (2, 2), (3, 4)]
asyncio.run(sc... | magicoder | python |
You are tasked with creating a program to visualize data using a graphing library. The program should take a set of data points and plot them on a graph to provide a visual representation of the data. The graphing library used in this problem is called "pChart," which provides a simple and efficient way to create vario... | ```php
require_once "pChart/class/pData.class.php";
require_once "pChart/class/pDraw.class.php";
require_once "pChart/class/pImage.class.php";
function generateAndDisplayGraph($dataPoints) {
// Create a new pData object
$pData = new pData();
// Add data to the pData object
foreach ($dataPoints as $poi... | magicoder | php |
You are working on a Django web application that includes a model for machine learning models. The application uses Django's migration system to manage changes to the database schema. The code snippet provided is a part of a migration file that adds a new field to the `mainsite` app's `mlmodel` model.
Your task is to ... | ```python
from django.db import migrations, models
import pickle
def populate_default_values(apps, schema_editor):
MLModel = apps.get_model('mainsite', 'MLModel')
for model_instance in MLModel.objects.all():
# Replace 'default_value' with the actual default value you want to set
model_instance... | magicoder | python |
You are tasked with creating a Python function that optimizes a web page by conditionally adding a script tag to the HTML content based on the presence of a specific cookie. The function should read the content of a file, check for the existence of a cookie, and modify the content accordingly before returning it along ... | ```python
def optimize_page(filename, request_cookies):
arq = open(filename, 'r')
content = arq.read()
arq.close()
if "io.prismic.preview" in request_cookies:
content = content.replace(
"{{prismicjs}}",
"<script type=\"text/javascript\" src=\"//static.cdn.prismic.io/pris... | magicoder | python |
You are tasked with implementing a simplified version of a Byzantine Fault Tolerant (BFT) consensus algorithm using the BLS (Boneh-Lynn-Shacham) multi-signature scheme. The provided code snippet includes a class `BlsBftReplica` with a constant `PPR_BLS_MULTISIG_WRONG` defined as 1. Your task is to create a function tha... | ```python
from collections import defaultdict
class BlsBftReplica:
def __init__(self):
self.prepares_count = defaultdict(int)
self.commits_count = defaultdict(int)
def handle_message(self, message_type, message):
if message_type == 'PrePrepare':
if self.verify_bls_multisig(... | magicoder | python |
You are tasked with implementing a function that encodes integers into bytes according to a specific encoding scheme. The function should take an integer as input and return the corresponding byte representation based on the following rules:
- If the input integer `i` is less than 253 (0xfd in hexadecimal), the functi... | ```python
def encode_integer_to_bytes(i: int) -> bytes:
if i < 0xfd:
return i.to_bytes(1, 'little') # Return single byte representation for integers less than 253
order = 1
while i >= 2**(8*order):
order += 1
if order > 3:
raise ValueError("integer too large: {}".format(... | magicoder | python |
You are tasked with implementing a parser for a simple expression language. The language supports literals, parentheses, symbol invocations, member access, and array access. Your goal is to implement the `group` function, which parses an input expression enclosed in parentheses.
The provided code snippet is a part of ... | ```rust
// Import necessary libraries and modules
use nom::{IResult, sequence::between};
// Define the Expression and Input types
type Expression = String;
type Input = String;
// Implement the group function to parse an expression enclosed in parentheses
pub fn group(i: Input) -> Result<Expression, nom::error::Error... | magicoder | rust |
You are tasked with implementing a class for a sparse linear solver in C++. The class should handle the setup and deletion of a matrix and provide a method for setting up the solver. The provided code snippet is a part of the class implementation and shows the initialization and deletion of a matrix.
Your task is to c... | ```cpp
#include <iostream>
class SparseLinearSolver {
private:
double* Amat_; // Pointer to the matrix
// Other member variables as needed
public:
SparseLinearSolver() : Amat_(nullptr) {}
// Method to set up the solver using a specific algorithm (e.g., Conjugate Gradient)
void setUpSolver() {
... | magicoder | cpp |
You are tasked with implementing a Python class that represents a section of a data file containing reference system definitions. The provided code snippet is part of a larger program and includes a function and variable assignments related to this task. Your goal is to create a class that adheres to the requirements i... | ```python
class ReferenceSystemSection:
def __init__(self, values):
self.values = values
def validate_section(self):
if self.values['NREF'] == len(self.values['DATA']):
return True
else:
return 'Number of reference systems differs from NREF'
# Create an instance... | magicoder | python |
You are tasked with implementing a function that performs a safe conversion between two different types of pointers in Rust. The function should take two arguments: a mutable reference to a slice of integers and a mutable reference to a slice of floats. The goal is to convert the integer slice into a float slice withou... | ```rust
fn convert_slices(int_slice: &mut [i32], float_slice: &mut [f32]) {
assert_eq!(int_slice.len(), float_slice.len(), "Slice lengths must be equal");
let int_ptr = int_slice.as_mut_ptr();
let float_ptr = float_slice.as_mut_ptr();
let int_len = int_slice.len();
let float_len = float_slice.len(... | magicoder | rust |
You are tasked with implementing a Python class that manages data processing for a scientific experiment. The class, named `DataProcessor`, is responsible for handling various configurations and customizations for data processing.
The class should have the following attributes and methods:
Attributes:
- `skims`: A li... | ```python
class DataProcessor:
def __init__(self):
self.skims = ['EcalPhiSymByRun']
self.eras = 'Run3'
self.recoSeq = ':bunchSpacingProducer+ecalMultiFitUncalibRecHitTask+ecalCalibratedRecHitTask'
self.promptCustoms = ['Calibration/EcalCalibAlgos/EcalPhiSymRecoSequence_cff.customise'... | magicoder | python |
You are tasked with implementing a Python function that calculates the summary of a financial transaction. The function should take three parameters: `valor` (the transaction amount), `largura` (the width of the summary output), and `altura` (the height of the summary output). The function should then generate a visual... | ```python
def moeda_resumo(valor, largura, altura):
# Calculate the number of currency units to be displayed
currency_units = int(valor)
# Create the visual summary grid
summary_grid = ""
for _ in range(altura):
row = ""
for _ in range(largura):
if currency_units > 0:
... | magicoder | python |
You are tasked with creating a script to automate the setup of a Minecraft server. Your script should download the latest version of the Minecraft server software and set up the necessary configuration files.
Your script should perform the following steps:
1. Use the `curl` command to fetch the version manifest JSON f... | ```bash
#!/bin/bash
# Set the Minecraft server version
VANILLA_VERSION="1.17.1"
# Fetch the version manifest JSON and extract the version manifest URL
versionManifestUrl=$(curl -fsSL 'https://launchermeta.mojang.com/mc/game/version_manifest.json' | jq --arg VANILLA_VERSION "$VANILLA_VERSION" --raw-output '[.versions[... | magicoder | shell |
You are tasked with implementing a custom `AnimatedRecyclerView` class in Android that extends the `RecyclerView` widget. The `AnimatedRecyclerView` should support various animation and layout configurations to provide a visually appealing user experience. Your task is to complete the implementation of the `AnimatedRec... | ```java
import android.content.Context;
import android.support.annotation.AnimRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.animation.LayoutAnimationController;
import com.nankung.common.R;
public class AnimatedRecyclerView extends Recycl... | magicoder | java |
You are tasked with implementing a function that joins individual pieces of a URL together to form a complete URL. The function should handle various cases, including handling of slashes, ensuring proper formatting, and handling of special characters.
You are given the following code snippet as a starting point:
```p... | ```python
import re
from urllib.parse import quote
def urljoin(*pieces):
"""Join a URL
Joins the pieces together to form a complete URL.
"""
url_parts = [piece.strip('/') for piece in pieces] # Remove leading and trailing slashes
joined_url = '/'.join(url_parts) # Join the URL pieces with slashe... | magicoder | python |
You are tasked with implementing a class for creating fields in a data model. The class should have the ability to generate mock values based on the field type. Your task is to implement the `make_field` function and the corresponding `Field` class to fulfill the requirements.
The `make_field` function should take two... | ```python
class Field:
def __init__(self, name, type):
self.name = name
self.type = type
@property
def mock_value(self):
if self.type == 'TYPE_BYTES':
return bytes(f"{self.name}_blob", 'utf-8')
@property
def mock_value_original_type(self):
if self.type =... | magicoder | python |
You are tasked with creating a Python script to analyze sequencing runs and identify missing parts of the analysis. The script should take input arguments specifying the sequencing runs to be analyzed and then perform the necessary checks to identify any missing components.
Your task is to implement a function `analyz... | ```python
import argparse
def analyze_sequencing_runs(runs):
components = ["alignment", "quality_check", "variant_calling"]
missing_components = {}
for run in runs:
missing = [comp for comp in components if comp not in get_existing_components(run)]
if missing:
missing_component... | magicoder | python |
You are given a code snippet from a file that defines a data structure using a specific syntax. Your task is to write a program that can parse and extract the subtype and super-entity information from the given code snippet.
Write a function or method that takes the code snippet as input and returns the subtype and su... | ```python
import re
def extract_subtype_super_entity(code_snippet):
subtype_pattern = r'SUBTYPE\s+OF\s+\(\s*(\w+)\s*\)'
super_entity_pattern = r'SUPER-ENTITY\s*\(\s*(\w+)\s*\)'
subtype_match = re.search(subtype_pattern, code_snippet)
super_entity_match = re.search(super_entity_pattern, code_snippet)
... | magicoder | python |
You are tasked with implementing a Python class that simulates a modified string object. The class, named `CustomString`, should have the following functionalities:
1. The `__repr__` method should return a representation of the string with the first character removed.
2. The `__str__` method should return the string wi... | ```python
import ast
class CustomString(str):
def __repr__(self):
s = super().__repr__()
return s[1:]
def __str__(self):
s = super().__str__()
if s.startswith("b'") and s.endswith("'"):
s = s[2:-1]
elif s.startswith("b'") and s.endswith("'\n"):
s... | magicoder | python |
You are tasked with implementing a custom type trait in C++ that determines whether a given type is a pointer type or not. You should create a type trait called `IsPointer` that evaluates to `true` if the provided type is a pointer, and `false` otherwise.
Your task is to complete the implementation of the `IsPointer` ... | ```cpp
#include <iostream>
namespace Tristeon
{
template <typename T>
struct IsPointer : std::false_type {};
template <typename T>
struct IsPointer<T*> : std::true_type {};
}
int main() {
std::cout << "Is int* a pointer type? " << Tristeon::IsPointer<int*>::value << std::endl; // Outputs "Is int*... | magicoder | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.