query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a class that manages configuration settings for different programming languages. The class has methods to add include paths, defines, and undefines for specific languages. The class has the following methods:
```python
class LanguageConfig:
def __init__(self):
self.include_... | ```python
from typing import Union, Iterable, List, Dict, Collection
class Language:
# Define the Language class if not already defined
class LanguageConfig:
def __init__(self):
self.include_paths = {}
self.defines = {}
self.undefines = {}
def _clean_paths(self, paths: Union[str, ... | magicoder | python |
You are tasked with implementing a simple music note parser in Rust. The parser should be able to extract the pitch and accidental of a musical note from a given input string.
The pitch of a note is represented by the letters A-G (case-insensitive), and the accidental is represented by optional symbols like b, ♭, ♯, #... | ```rust
use crate::note::errors::NoteError;
use lazy_static::lazy_static;
use regex::{Match, Regex};
use std::fmt;
use std::str::FromStr;
use strum_macros::EnumIter;
use std::collections::HashMap;
lazy_static! {
static ref REGEX_PITCH: Regex = Regex::new("^[ABCDEFGabcdefg][b♭♯#s𝄪x]*").unwrap();
}
#[derive(Debug,... | magicoder | rust |
You are tasked with creating a function that can efficiently determine the longest substring of a given string that contains at most two distinct characters. For example, given the input string "abaccc", the function should return "abacc" as the longest substring containing at most two distinct characters.
Your task i... | ```swift
func longestSubstringWithTwoDistinct(_ s: String) -> String {
var charMap = [Character: Int]()
var start = 0
var end = 0
var maxLength = 0
var maxStart = 0
for (i, char) in s.enumerated() {
charMap[char] = i
if charMap.count > 2 {
let minIndex = charMap.... | magicoder | swift |
You are tasked with creating a Python function to simulate drawing a random playing card from a standard 52-card deck. The function should return the drawn card's face value and suit.
You are provided with a code snippet that initializes the faces and suits of the playing cards. Your task is to complete the `carddraw`... | ```python
import random
def carddraw():
faces = ["6", "7", "8", "9", "10", "J", "D", "K", "A"]
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
drawn_face = random.choice(faces)
drawn_suit = random.choice(suits)
return (drawn_face, drawn_suit)
```
The `carddraw` function uses the `random.choice` ... | magicoder | python |
You are tasked with creating a script to automate the build and packaging process for a Swift project using Docker. The provided code snippet demonstrates a part of the script that builds and packages a Swift project using a Docker container named "swift-lambda-builder."
Your task is to write a Bash script that encomp... | ```bash
#!/bin/bash
# Define the project name and Docker container name
project="your_project_name"
docker_container="swift-lambda-builder"
# Build the Swift project in release mode using the specified Docker container
echo "Building $project..."
docker run --rm --volume "$(pwd)/:/src" --workdir "/src/" $docker_conta... | magicoder | shell |
You are tasked with implementing a function to generate a unique email verification code for a user registration system. The code snippet provided is a part of a user registration process in a web application. The `mt_rand` function is used to generate a random number within a specified range, and this number is concat... | ```php
function generateEmailVerificationCode() {
$minRange = 12123234;
$maxRange = 234345456;
// Generate a random number within the specified range
$randomNumber = mt_rand($minRange, $maxRange);
// Get the current timestamp in the format "YmdHis"
$currentTimestamp = date("YmdHis");
... | magicoder | php |
You are tasked with creating a C# program to manage a fleet of ships. Each ship has various attributes, including its size. To facilitate the storage and retrieval of ship size information, the program uses XML serialization and deserialization. The provided code snippet shows the usage of the `XmlAttribute` attribute ... | ```csharp
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class Ship
{
[XmlAttribute(AttributeName = "ShipSize")]
public int ShipSize { get; set; }
public string ShipName { get; set; }
public void SerializeToXml(Ship ship, string filePath)
{
XmlSeria... | magicoder | csharp |
You are tasked with creating a program that parses and processes SVG (Scalable Vector Graphics) data. SVG is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. Your program needs to extract specific information from the SVG data and perform a transformation on it... | ```javascript
function parseSVG(svgData) {
let totalPaths = 0;
let totalLength = 0;
const pathRegex = /<path d="([^"]+)"/g;
let match;
while ((match = pathRegex.exec(svgData)) !== null) {
totalPaths++;
const pathData = match[1];
const pathLength = calculatePathLength(pathDat... | magicoder | javascript |
You are tasked with implementing a program that can efficiently determine the longest common subsequence (LCS) of two given strings. The longest common subsequence is the longest sequence of characters that appear in the same order in both strings. For example, given the strings "ABCDGH" and "AEDFHR", the LCS is "ADH" ... | ```python
def longestCommonSubsequence(str1, str2):
m, n = len(str1), len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i - 1] == str2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
... | magicoder | python |
You are given an array of integers `vals` of length `n`. Your task is to write a function that finds the minimum non-negative integer in the array and assigns it to the variable `finalmn`. If there are no non-negative integers in the array, `finalmn` should be assigned the value -1.
The function signature is:
```pytho... | ```python
from typing import List
def find_min_non_negative(vals: List[int]) -> None:
finalmn = -1 # Initialize finalmn to -1
for val in vals:
if val >= 0 and (finalmn == -1 or val < finalmn):
finalmn = val # Update finalmn if val is non-negative and smaller than the current finalmn
```
... | magicoder | python |
You are working on a travel booking application that manages reservations for flights, car rentals, and hotel rooms. The code snippet provided is a part of the backend implementation for managing package reservations. The `hasMany` method is used to define a one-to-many relationship between the `Paquete_ReservaVuelo` m... | ```php
function calculateTotalPrice($reserva_auto_id, $reserva_habitacion_id, $precio, $descuento, $tipo_paquete, $disponibilidad) {
$discountPercentage = 0;
$surchargePercentage = 0;
// Apply discount based on package type
switch ($tipo_paquete) {
case "standard":
$discountPercenta... | magicoder | php |
You are tasked with creating a Java class that represents ownership information for a company's assets. The class should implement the `Parcelable` interface and be annotated for JSON serialization using the Gson library.
Your task is to complete the `Ownership` class by adding the necessary fields, methods, and annot... | ```java
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import javax.annotation.Generated;
@Generated("org.jsonschema2pojo")
public class Ownership implements Parcelable {
@SerializedName("ownerName")
@Expos... | magicoder | java |
You are tasked with implementing a class that represents a simple task with a due date. The class should have the following properties and methods:
Properties:
- `title`: a string representing the title of the task.
- `dueDate`: a Date object representing the due date of the task.
- `updatedAt`: a Date object represen... | ```typescript
class Task {
title: string;
dueDate: Date;
updatedAt: Date;
constructor(title: string, dueDate: Date) {
this.title = title;
this.dueDate = dueDate;
this.updatedAt = new Date();
}
updateTitle(newTitle: string): void {
this.title = newTitle;
this.updatedAt = new Date();
}... | magicoder | typescript |
You are tasked with implementing a message queuing system using AWS Simple Queue Service (SQS) and Python. Your goal is to send a message to a queue named 'TEST', listen to the queue, and print the first message received.
Your task is to complete the Python function `run()` by using the AWS SDK for Python (Boto3) to a... | ```python
import boto3
def run():
# Set up AWS credentials and create an SQS client
aws_access_key_id = 'YOUR_ACCESS_KEY_ID'
aws_secret_access_key = 'YOUR_SECRET_ACCESS_KEY'
aws_session_token = 'YOUR_SESSION_TOKEN' # Optional for IAM roles
region_name = 'YOUR_REGION'
sqs = boto3.client('s... | magicoder | python |
You are tasked with implementing a Python function that calculates the angle in degrees between the hour and minute hands of an analog clock. The function should take two integers, `hour` and `minute`, as input, representing the time on the clock in 24-hour format. The function should return the smallest angle formed b... | ```python
from math import atan, pi
def calculate_clock_angle(hour, minute):
# Calculate the angles made by the hour and minute hands with respect to 12 o'clock
hour_angle = (hour % 12 + minute / 60) * 30 # 30 degrees per hour, 0.5 degrees per minute
minute_angle = minute * 6 # 6 degrees per minute
... | magicoder | python |
You are tasked with implementing a file linking utility that links files in a source directory to corresponding files in a target directory. The utility should be able to handle symbolic links and hard links. Your task is to write a Python function that accomplishes this.
You are given a class `FileLinker` with a meth... | ```python
import os
class FileLinker:
def cmd_link(self, source_dir, target_dir):
"""Link files in source_dir to corresponding files in target_dir."""
for root, _, files in os.walk(source_dir):
for file in files:
source_path = os.path.join(root, file)
tar... | magicoder | python |
You are tasked with creating a Python program that retrieves and processes data from a public GitHub API. The program should fetch information about the top repositories based on the number of stars and perform specific operations on the retrieved data.
Your program should perform the following steps:
1. Fetch the top... | ```python
import os
import sys
import datetime
import urllib2
from rdflib import Namespace, Graph
import AddProvenance
def fetch_top_repositories(stars_range):
try:
# Fetch the top repositories based on the number of stars within the specified range
# Use appropriate API endpoint and handle potenti... | magicoder | python |
You are tasked with implementing a Python program to convert a given DNA sequence into its corresponding amino acid sequence using the provided codon table. The codon table maps each codon (a sequence of three DNA nucleotides) to its corresponding amino acid. Your program should take a DNA sequence as input and output ... | ```python
#!/usr/bin/env python3
"""Codon/Amino Acid table conversion"""
codon_table = {
'ATT': 'Isoleucine', 'ATC': 'Isoleucine', 'ATA': 'Isoleucine',
'CTT': 'Leucine', 'CTC': 'Leucine', 'CTA': 'Leucine', 'CTG': 'Leucine', 'TTA': 'Leucine', 'TTG': 'Leucine',
'GTT': 'Valine', 'GTC': 'Valine', 'GTA': 'Valin... | magicoder | python |
You are tasked with creating a program that simulates a simple file management system. The system should be able to execute commands to manipulate files and directories. Your task is to implement the "ls" command, which lists the contents of a directory. The command should take into account the specified options and ar... | ```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LsCommandExecutor {
public static void main(String[] args) {
try {
Process lsProcess = Runtime.getRuntime().exec("ls paper-*.jar");
BufferedReader reader = new BufferedR... | magicoder | java |
You are tasked with implementing a performance monitoring system for a software application. The system should be able to track and record various performance metrics such as timing, gauge, and counter. You are provided with a code snippet that outlines the structure of the performance monitoring system, including a me... | ```python
class PerformanceMonitoringSystem:
@staticmethod
def timer(stat_name, start_time, tags: dict = {}):
# Implementation for timing method
# Record the time taken for a specific operation
stats_client.timing(stat_name, start_time, tags={**tags, })
@staticmethod
def gauge(s... | magicoder | python |
You are tasked with implementing a class that interfaces with hardware components and performs sensor data processing. The class has several private members, including a serial driver, a complementary filter, time tracking variables, and vectors for joint commands, joint states, and sensor states. Your goal is to creat... | ```cpp
hardware_interface::return_type write() override {
// Perform the write operation to the hardware interface
if (serial_driver_) {
// Write data using the serial driver
if (serial_driver_->writeData()) {
// Data write successful
if (!initialized_filter_) {
// Initialize the complem... | magicoder | cpp |
You are tasked with implementing a function that updates the working label for each class using an info file. The info file contains information about a dataset, and the working label for each class needs to be updated based on this information. The function should take the info file and the dataset as input and update... | ```python
import ut
def update_audio_working_from_info(info, dali_dataset):
"""
Update the working label for each class using an info file.
Parameters:
info (str): File path of the info file in gzip format.
dali_dataset (Dataset): Dataset containing audio information.
Returns:
None
"... | magicoder | python |
You are tasked with implementing a conversion storage system that can store and retrieve conversion rates between different units of measurement. The system should support adding new conversion rates, retrieving conversion rates, and converting values from one unit to another.
You need to implement a class `Conversion... | ```cpp
#include <iostream>
#include <unordered_map>
#include <string>
struct Conversion
{
std::string from_unit;
std::string to_unit;
double conversion_rate;
Conversion(const std::string& from, const std::string& to, double rate) : from_unit(from), to_unit(to), conversion_rate(rate) {}
};
class Conve... | magicoder | cpp |
You are tasked with creating a Python class to represent an indicator used in a monitoring system. The indicator should have various attributes and methods to manage its properties. Use the provided code snippet as a basis for defining the class and its functionalities.
Your task is to implement the `Indicator` class ... | ```python
class Indicator:
def __init__(self, unit, delta_unit, description, parameters, icon, category, tags):
self.unit = unit
self.delta_unit = delta_unit
self.description = description
self.parameters = parameters
self.icon = icon
self.category = category
... | magicoder | python |
You are tasked with creating a script to automate the testing of a Docker container's configuration. The script will execute commands within the container and verify the output to ensure that specific configurations are in place. The script will use the `docker exec` command to run commands inside the container and the... | ```bash
#!/bin/bash
# Function to execute command inside Docker container and check for expected output
execute_and_verify() {
local container_name=$1
local command=$2
local expected_output=$3
# Execute command inside the container and capture the output
output=$(docker exec "${container_name}" /bin/su - ro... | magicoder | shell |
You are given a list of IP addresses and a target address. Your task is to write a function that finds the closest IP address to the target address based on the number of matching bits in the binary representation of the addresses.
You need to implement the following function:
```python
def closest_ip_address(ip_list... | ```python
def closest_ip_address(ip_list, target):
def count_matching_bits(ip1, ip2):
ip1_binary = ''.join(format(int(x), '08b') for x in ip1.split('.'))
ip2_binary = ''.join(format(int(x), '08b') for x in ip2.split('.'))
return sum(bit1 == bit2 for bit1, bit2 in zip(ip1_binary, ip2_binary))... | magicoder | python |
You are tasked with implementing a Python module for user management that interacts with a database. The module should provide basic CRUD (Create, Read, Update, Delete) operations for user entities. The provided code snippet imports a module named `crud_user`, which is expected to contain the necessary functions for us... | ```python
# crud_user.py
# Assume the presence of a database connection and necessary imports
def create_user(username: str, email: str) -> bool:
# Implementation of creating a user in the database
try:
# Database query to insert user details
# Example: cursor.execute("INSERT INTO users (usern... | magicoder | python |
You are tasked with implementing a custom input component in a web application using Vue.js. The provided code snippet is a part of the component's template and shows the usage of the `InputText` component along with some properties and event handling.
Your task is to create a Vue.js component called `CustomInput` tha... | ```javascript
// CustomInput.vue
<template>
<div class="custom-input">
<InputText
:readonly="readonly"
:disabled="disabled"
:placeholder="placeholder"
:label="label"
:value="internalValue"
@input="onInput"
ref="inputText"
>
<template v-if="$slots.prepend" slot="... | magicoder | javascript |
You are tasked with implementing a concurrent hash mining algorithm to find a specific hash value. The algorithm will utilize a specified number of threads to perform the mining process. The hash mining process involves repeatedly hashing a given input and checking if the resulting hash matches a predefined target hash... | ```rust
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
const TARGET_HASH: u64 = 0x1234567890; // Replace with the actual target hash value
fn hash_function(input: u64) -> u64 {
// Replace with the actual hash function implementation
// Example:... | magicoder | rust |
You are tasked with implementing a function to draw a textured polygon using the given code snippet as a reference. The function should take in the necessary parameters and use the provided vgui library to draw the polygon with the specified color and texture.
You are given the following information:
- The vgui librar... | ```cpp
void DrawTexturedPolygon(const Color& color, const Vector2D* vertices, int numVertices, const Vector2D& position, int width, const Vector2D& uv11, const Vector2D& uv21) {
vgui::surface()->DrawSetColor(color);
// Create an array of vgui vertices
Vertex_t* vguiVertices = new Vertex_t[numVertices];
... | magicoder | cpp |
You are tasked with implementing a function that calculates the total number of ways to reach the top of a staircase. You can climb the staircase by either taking 1 or 2 steps at a time. Write a Python function `count_ways_to_climb_stairs(n)` that takes an integer `n` as input and returns the total number of distinct w... | ```python
def count_ways_to_climb_stairs(n):
if n <= 1:
return 1
else:
# Initialize the number of ways to climb the stairs with 1 step or 2 steps
ways = [1, 2]
for i in range(2, n):
# Calculate the total ways to reach the current step by adding the ways to reach the p... | magicoder | python |
You are tasked with creating a function that parses a given Swift code snippet and extracts the names of the public extension methods defined within it. The code snippet will contain Swift code defining public extension methods for a hypothetical APIManager class.
Write a function called `extractExtensionMethodNames` ... | ```swift
func extractExtensionMethodNames(from codeSnippet: String) -> [String] {
var methodNames: [String] = []
// Split the code snippet by lines
let lines = codeSnippet.components(separatedBy: .newlines)
// Iterate through each line to find public extension methods
for line in lines {
... | magicoder | swift |
You are tasked with implementing a guarded action transition in a finite state machine (FSM) using the `skizzay::fsm` library. A guarded action transition is a transition in an FSM that is triggered by a specific event, subject to a guard condition, and performs a specific action upon transition.
Your goal is to creat... | ```cpp
#include <skizzay/fsm/guarded_action_transition.h>
#include <iostream>
using namespace skizzay::fsm;
// Define the guarded action transition class
template <typename EventType, typename GuardCondition, typename Action>
class MyGuardedActionTransition : public guarded_action_transition<EventType> {
public:
... | magicoder | cpp |
You are tasked with implementing a C++ class that represents a geo annotation source for an image processing application. The class should inherit from `ossimAnnotationSource` and implement the `ossimViewInterface`. The constructor of the class should take an `ossimImageSource` pointer, an `ossimImageGeometry` pointer,... | ```cpp
#include <ossim/imaging/ossimGeoAnnotationSource.h>
ossimGeoAnnotationSource::ossimGeoAnnotationSource(ossimImageSource* inputSource, ossimImageGeometry* geom, bool ownsProjectionFlag)
: ossimAnnotationSource(inputSource),
ossimViewInterface(),
m_geometry(geom)
{
// Initialize base classes a... | magicoder | cpp |
You are tasked with implementing a function that sorts a list of items based on their properties. Each item is represented as an object with the following properties: `rotation`, `price`, and `blueprint`. The `rotation` and `price` properties are numerical values, while the `blueprint` property may be undefined or cont... | ```javascript
function sortItems(items) {
function compareItems(a, b) {
if (a.rotation !== undefined && b.rotation !== undefined) {
if (a.rotation !== b.rotation) {
return a.rotation - b.rotation;
} else if (a.price !== b.price) {
return a.price - b.price;
} else {
return... | magicoder | javascript |
You are tasked with implementing a class that manages paginated data from an external API. The class should handle the retrieval of data, tracking of pagination markers, and provide a method to check if there are more pages to fetch.
You are given a code snippet from the existing class that sets two attributes, `is_Tr... | ```python
class PaginationManager:
def __init__(self, initial_response):
self.is_Truncated = initial_response['is_truncated']
self.marker = initial_response['next_marker']
def fetch_next_page(self, next_page_response):
self.is_Truncated = next_page_response['is_truncated']
self.... | magicoder | python |
You are tasked with implementing a Python function that processes skeletal animation data for a 3D asset. The function takes in parameters related to the asset and the skeletal animation, and it creates and configures the necessary animation attributes using the USD (Universal Scene Description) library. The provided c... | ```python
def process_skeletal_animation(asset, usdStage, skeletonIdx, verbose):
if not asset.hasSkeletalAnimation():
if verbose:
print('No skeletal animation')
return
animationName = asset.getAnimationsPath() + '/' + 'SkelAnimation'
if skeletonIdx > 0:
animationName += ... | magicoder | python |
You are tasked with implementing a custom UITableViewCell subclass for a mobile app. The cell should display a list of items, and when a user taps on a cell, it should toggle a selection state and update the UI accordingly. Your task is to complete the implementation of the `CustomTableViewCell` class by adding the nec... | ```swift
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
itemLabel.textColor = .blue // Change the text color to indicate selection
// Add any other UI changes to indicate selection
} else {
itemLabel.textCol... | magicoder | swift |
You are tasked with creating a program to analyze and visualize the distribution of file sizes within a directory. You will need to write a Python script that utilizes the `os` module to traverse a specified directory, retrieve the file sizes, and then generate a histogram to visualize the distribution of file sizes.
... | ```python
import os
import matplotlib.pyplot as plt
def analyze_directory(directory_path):
file_sizes = []
try:
for root, dirs, files in os.walk(directory_path):
for file in files:
file_path = os.path.join(root, file)
file_sizes.append(os.path.getsize(file_pa... | magicoder | python |
You are given a program that processes a series of instructions. The program uses a bitmask to modify memory addresses and store values in memory. The bitmask is applied to the memory address before writing a value to the memory location. The bitmask is a 36-bit string of 0s, 1s, and Xs. The 0s and 1s in the bitmask ov... | ```python
def apply_mask(mask, value):
result = ''
for m, v in zip(mask, format(value, '036b')):
result += v if m == 'X' else m
return int(result, 2)
def part1(instructions):
memory = {}
mask = ''
for instruction in instructions:
if instruction.startswith('mask'):
ma... | magicoder | python |
You are tasked with implementing a Python function that processes a given text and extracts all the comments present in the text. A comment is a piece of text that is meant for human readers and is typically ignored by the compiler or interpreter when the code is executed. In this problem, a comment is defined as any t... | ```python
from typing import List
def extract_comments(text: str) -> List[str]:
comments = []
in_comment = False
current_comment = ""
lines = text.split('\n')
for line in lines:
line = line.strip()
if line.startswith('"""') and not in_comment:
in_comment = True
... | magicoder | python |
You are tasked with creating a program that simulates a simple game of rock-paper-scissors. The program should prompt the user to input their choice (rock, paper, or scissors), and then generate a random choice for the computer. The program should then determine the winner based on the choices and display the result.
... | ```python
import random
def rock_paper_scissors(user_choice):
choices = ["rock", "paper", "scissors"]
computer_choice = random.choice(choices)
if user_choice not in choices:
return "Invalid input"
elif user_choice == computer_choice:
return "Tie!"
elif (user_choice == "rock" and co... | magicoder | python |
You are tasked with implementing a function that determines whether a given input "looks falsy" based on Python's truth value testing rules. In Python, certain values are considered "falsy" when used in a boolean context, meaning they evaluate to `False`. Your task is to create a function `looks_falsy` that returns `Tr... | ```python
def looks_falsy(value):
if isinstance(value, str):
return value.strip().lower() == 'false'
elif isinstance(value, int):
return value == 0
elif isinstance(value, list):
return all(looks_falsy(item) for item in value)
else:
return False # For other types, conside... | magicoder | python |
You are tasked with implementing an iterator for a custom data structure called `Channel`. The `Channel` struct represents a communication channel and has a method `users_iter` that returns an iterator over users. The iterator, `UsersIter`, is defined as a struct with two fields: `channel` of type `Option<usize>` and `... | ```rust
impl<'a> Iterator for UsersIter<'a> {
type Item = User; // Assuming User is the type of elements in the iteration
fn next(&mut self) -> Option<Self::Item> {
if let Some(c) = self.channel {
if let Some(user) = self.channels[c].next() {
return Some(user);
}... | magicoder | rust |
You are tasked with creating a Python function that processes a directory structure and returns specific information about the contents. The function should take a directory path as input and return a dictionary containing the count of subdirectories and the count of files within each subdirectory.
Write a function ca... | ```python
import os
def directory_info(dir_path):
result = {}
for entry in os.scandir(dir_path):
if entry.is_dir():
sub_dir_info = {'files': 0, 'subdirectories': 0}
for sub_entry in os.scandir(entry.path):
if sub_entry.is_file():
sub_dir_info[... | magicoder | python |
You are tasked with implementing a class to simulate a mobile phone. The class should have the ability to store contacts, add new contacts, modify existing contacts, remove contacts, and search for contacts. Additionally, the class should be able to simulate the process of making and receiving calls.
Your task is to i... | ```java
import java.util.ArrayList;
class Contact {
private String name;
private String phoneNumber;
public Contact(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public String getPho... | magicoder | java |
You are tasked with creating a Python function that manipulates images using the Python Imaging Library (PIL). The function should take three parameters: `user1`, `user2`, and `background`. The `user1` and `user2` parameters represent the usernames of two users, and the `background` parameter represents the background ... | ```python
from PIL import Image
from io import BytesIO
async def manipulate_images(user1: str, user2: str, background: str) -> bytes:
# Retrieve avatar images as bytes
avatar1_bytes = await getavatar(user1)
avatar2_bytes = await getavatar(user2)
# Open, convert to RGBA, and resize avatar images
... | magicoder | python |
You are tasked with implementing a method to filter and retrieve specific problems from a list based on a given patient ID. The `Problem` class represents a medical issue, and each problem has an associated patient ID. Your task is to write a method that takes a list of problems and a patient ID as input and returns a ... | ```java
import java.util.ArrayList;
class Problem {
private int patientId;
// Other attributes and methods not shown for brevity
}
public class ProblemManager {
public ArrayList<Problem> getProblemsByPatientId(ArrayList<Problem> allProblems, int patientId) {
ArrayList<Problem> patientProblems = n... | magicoder | java |
You are tasked with creating a function that processes user access data to generate a list of accessible menu items for a web application. The function should take user access data as input and return a formatted list of menu items that the user has permission to access.
The user access data is represented as an array... | ```php
/**
* Process user access data to generate a list of accessible menu items
* @param array $userAccessData
* @return array
*/
function generateAccessibleMenu($userAccessData) {
// Remove duplicate URLs and add an empty string
$uniqueUrls = array_unique(array_column(Tools::buildArrFromObj($userAccessDa... | magicoder | php |
You are tasked with implementing a function to handle the deserialization of a JSON response in a Rust application. The function should take the response body and an error builder as input, attempt to deserialize the JSON, and handle any potential errors that may arise during the deserialization process.
Your task is ... | ```rust
fn deser_structure_gateway_timeout_exceptionjson_err(
response_body: &str,
error_builder: crate::error::gateway_timeout_exception::Builder,
) -> Result<crate::error::gateway_timeout_exception::Builder, crate::error::DeleteInputSecurityGroupError> {
// Attempt to deserialize the JSON response
let... | magicoder | rust |
You are tasked with implementing a simple event handling system in Swift. The system should allow for the creation of a `Signal` class, which represents an event that can be subscribed to and triggered. Additionally, you need to create a `MainPresenter` class that utilizes the `Signal` class to handle a specific event.... | ```swift
// Signal class representing an event
class Signal<T> {
typealias Closure = (T) -> Void
var subscribers: [Closure] = []
func subscribe(_ closure: @escaping Closure) {
subscribers.append(closure)
}
func update(_ value: T) {
for subscriber in subscribers {
... | magicoder | swift |
You are tasked with implementing a function to send SMS verification codes using a third-party service. The given code snippet contains a partial implementation of the function, along with some TODO comments. Your task is to complete the implementation of the function and write a test code to verify its functionality.
... | ```python
from third_party_sms_client import ThirdPartySMSClient # Assume the existence of a third-party SMS client
def send_sms_verification_code(phone_number, verification_code):
# Create a client for the third-party SMS service
client = ThirdPartySMSClient()
# Construct the request to send the SMS usi... | magicoder | python |
You are given a grid representing a map with 'L' and 'W' characters. Each 'L' represents land, and each 'W' represents water. Your task is to determine the number of connected land regions in the grid. Two land cells are considered connected if they are adjacent horizontally, vertically, or diagonally.
Write a functio... | ```cpp
#include <vector>
using namespace std;
void dfs(vector<vector<char>>& grid, int i, int j) {
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] != 'L') {
return;
}
grid[i][j] = 'W'; // Mark the cell as visited
dfs(grid, i + 1, j); // Check cell below
dfs(gri... | magicoder | cpp |
You are tasked with creating a Django model and an admin interface for managing articles. Your task is to define a model for articles and set up an admin interface to manage these articles.
Define a Django model called `Article` with the following fields:
- `title` (CharField with max length of 100)
- `author` (CharFi... | ```python
# models.py
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
category = models.CharField(max_length=50)
keywords = models.TextField()
publication_date = models.DateField()
# admin.py
from django.co... | magicoder | python |
You are tasked with implementing a simple syntax checker for a custom programming language. The language uses curly braces for defining code blocks, and your task is to identify and report any missing or mismatched braces in the code.
You are given a snippet of code as a string. The code may contain any combination of... | ```python
from typing import List, Tuple
def check_braces(code: str) -> List[Tuple[int, str]]:
stack = []
errors = []
for i, char in enumerate(code):
if char == '{':
stack.append((i, '{'))
elif char == '}':
if not stack:
errors.append((i, "unexpected... | magicoder | python |
You are tasked with creating a Python function that processes a list of software dependencies and their associated patches. The function should extract and organize the information from the given input and return a structured representation of the dependencies and patches.
The input will consist of a list of strings, ... | ```python
import re
def process_dependencies(input_list):
dependencies = {}
patches = {}
for line in input_list:
if line.startswith('dependency'):
match = re.search(r"dependency\('(.+?)', when='(.+?)', sha256='(.+?)'\)", line)
if match:
name, version, sha256... | magicoder | python |
You are tasked with creating a Python function that calculates the shortest path between two locations in a road network using the given code snippet as a reference. The road network is represented as a graph, where nodes represent intersections and edges represent road segments. The graph is loaded from an OpenStreetM... | ```python
import networkx as nx
import osmgraph
import geog
def shortest_path_length(graph, source, target):
for n1, n2 in graph.edges_iter():
c1, c2 = osmgraph.tools.coordinates(graph, (n1, n2))
graph[n1][n2]['length'] = geog.distance(c1, c2)
try:
length = nx.shortest_path_length(grap... | magicoder | python |
You are given a string containing only lowercase English letters. Your task is to write a function that determines whether the string can be made a palindrome by removing at most one character.
Write a function `canMakePalindrome` that takes a string `s` as input and returns `true` if the string can be made a palindro... | ```java
public boolean canMakePalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
// Try removing either the character at the left index or the character at the right index
return isPalindrome(s, le... | magicoder | java |
You are tasked with implementing a generic sorting algorithm using the strategy design pattern. The provided code snippet initializes a QuickSort algorithm and a context to execute the sorting process. Your task is to complete the implementation of the QuickSort algorithm and the Context class to enable the sorting of ... | ```java
import java.util.Arrays;
// Strategy interface
interface SortAlgorithm {
void sort(int[] array);
}
// Concrete strategy - QuickSort algorithm
class QuickSort implements SortAlgorithm {
@Override
public void sort(int[] array) {
quickSort(array, 0, array.length - 1);
}
private void ... | magicoder | java |
You are tasked with implementing a simplified version of a message-passing interface (MPI) in C++. The provided code snippet is a part of a class that manages communication between processes in a parallel computing environment. Your goal is to complete the implementation of the `pMR::MPI::Connection` class by defining ... | ```cpp
class pMR::MPI::Connection {
private:
int mCommunicator;
int mTargetRank;
public:
pMR::MPI::Connection(int communicator, int targetRank) : mCommunicator(communicator), mTargetRank(targetRank) {}
int getCommunicator() const {
return mCommunicator;
}
int getTargetRank() const {
... | magicoder | cpp |
You are tasked with creating a program to analyze a given HTML file and count the occurrences of a specific HTML tag with certain attributes. The HTML file contains a series of lines, each potentially containing an HTML tag. Each tag is represented in the format `<tagname attribute1="value1" attribute2="value2" ...>`. ... | ```python
def countTagOccurrences(html, tagName, attribute, value):
count = 0
tag_start = "<" + tagName
tag_end = "</" + tagName + ">"
index = 0
while index < len(html):
start = html.find(tag_start, index)
if start == -1:
break
end = html.find(">", start)
... | magicoder | python |
You are tasked with implementing a dynamic time warping algorithm to compare two sequences of eye fixation points. Dynamic time warping is a method used to measure the similarity between two sequences that may vary in time or speed. In this problem, you will be given the coordinates of eye fixation points and the algor... | ```python
import numpy as np
def dynamic_time_warping(sequence1, sequence2):
n = len(sequence1)
m = len(sequence2)
# Create a cost matrix and initialize the first row and column
cost_matrix = np.zeros((n, m))
cost_matrix[0, 0] = distance(sequence1[0], sequence2[0])
for i in range(1, n... | magicoder | python |
You are tasked with implementing a file content decoding function in Python. The function should take a file path as input and decode the contents of the file using a custom decoding algorithm. The decoding algorithm is based on the file path and involves extracting specific parts of the path to derive the decoding key... | ```python
import os
def DecodeFileContents(contents, path):
# Extract the file name from the path
file_name = os.path.basename(path)
# Extract the directory name from the path
directory_name = os.path.dirname(path)
# Derive the decoding key based on the file name and directory name
de... | magicoder | python |
You are tasked with implementing a Maxibon allocation algorithm for a group of developers. Each developer has a name and a specific number of Maxibons they want to get. The goal is to ensure that each developer gets their desired number of Maxibons while also accounting for the fact that the company's supply of Maxibon... | ```swift
struct Developer {
let name: String
let numberOfMaxibonsToGet: Int
}
func allocateMaxibons(developers: [Developer], availableMaxibons: Int) -> [String: Int] {
var allocatedMaxibons: [String: Int] = [:]
let totalRequestedMaxibons = developers.reduce(0) { $0 + $1.numberOfMaxibonsToGet }
if ... | magicoder | swift |
You are tasked with creating a custom sampler for Apache JMeter, a popular open-source performance testing tool. Your custom sampler will need to collect specific data from a web application and perform custom logic on the collected data. To achieve this, you will need to extend the `AbstractSampler` class provided by ... | ```java
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jorphan.gui.JLabeledTextField;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult;
import ... | magicoder | java |
You are working on a web application that utilizes the Axios library for making HTTP requests. Your task is to implement a function that sends a POST request to a server using Axios and handles the response appropriately.
You are given the following code snippet as a starting point:
```javascript
axios.defaults.heade... | ```javascript
function sendPostRequest(url, data) {
return new Promise((resolve, reject) => {
axios.post(url, data)
.then(response => {
resolve(response.data);
})
.catch(error => {
if (error.response) {
// The request wa... | magicoder | javascript |
You are tasked with implementing a custom database query class in Java that retrieves and processes data from a database. The provided code snippet is a partial implementation of the `Query` class, which extends `AbstractDbQuery` and implements the `IStoredFileSha1Query` interface. Your task is to complete the implemen... | ```java
private static class Query extends AbstractDbQuery<IRow> implements IStoredFileSha1Query {
private final Parameters parameters = new Parameters();
@Override
public IRow createRow(IDbSqlSelect select, DbResultSet resultSet) {
return new Row(this, select, resultSet);
}
@Override
... | magicoder | java |
You are tasked with creating a program to analyze and visualize data using Python's seaborn library. Your task is to write a function that takes a list of data arrays and a color palette as input, and then generates a series of overlaid histograms for each array using the specified color palette.
Write a Python functi... | ```python
import seaborn as sns
import matplotlib.pyplot as plt
def generate_histograms(toPlot, pal):
for i in range(0, len(toPlot)):
clr = pal[i]
sns.distplot(toPlot[i], kde=False, bins=50, color=clr)
plt.show()
# Test the function
toPlot = [[1, 2, 3, 4, 5], [2, 3, 3, 4, 4, 5, 5, 5, 6, 6]]
pa... | magicoder | python |
You are tasked with creating a Python class that simulates a simple ping command. The class should be able to send ICMP echo requests to a specified host and measure the round-trip time for the response. You should also implement a method to calculate the average round-trip time based on a specified number of ping requ... | ```python
import subprocess
import re
import platform
class FCPing:
def __init__(self, host: str):
self.host = host
def ping(self) -> float:
if platform.system().lower() == 'windows':
command = ['ping', '-n', '1', self.host]
else:
command = ['ping', '-c', '1', s... | magicoder | python |
You are tasked with implementing a custom sequence space class in Python for handling sequences of data. The sequence space should consist of two sub-spaces: one for the data and one for the mask (a binary-valued matrix). Your task is to create a class `SequenceSpace` that inherits from `space.CompositeSpace` and repre... | ```python
from pylearn2.utils import is_iterable
from pylearn2.space import CompositeSpace, Space
class SequenceSpace(CompositeSpace):
"""
This space represents sequences. In order to create batches it
actually consists of two sub-spaces, representing the data and
the mask (a binary-valued matrix).
... | magicoder | python |
You are tasked with implementing a bridge design pattern for creating different types of cars. The bridge pattern decouples an abstraction from its implementation so that the two can vary independently. In this scenario, the abstraction is the type of car, and the implementation is the car's color.
You need to create ... | ```php
// Implementing the Bridge pattern for creating different types of cars with different colors
// Implementor interface for the color
interface Color
{
public function applyColor(): string;
}
// Concrete Implementor classes for different colors
class BlueCar implements Color
{
public function applyColor... | magicoder | php |
You are tasked with implementing a function that calculates the position and size of a dialog box based on the provided configuration and container frame. The dialog box can have two types: `preferSize` and `size`. For the `preferSize` type, the position and size are calculated based on the preferred content size of th... | ```swift
enum DialogType {
case preferSize
case size(CGSize)
}
func calculateDialogFrame(containerFrame: CGRect, config: DialogType, presentedSize: CGSize?) -> CGRect {
let width = containerFrame.width
let height = containerFrame.height
switch config {
case .preferSize:
guard let p... | magicoder | swift |
You are given a code snippet that calculates the nth Fibonacci number and prints the result. The `fibo` function takes an integer `n` as input and returns the nth Fibonacci number. The code snippet then prints the input `n` and the corresponding Fibonacci number.
Your task is to implement the `fibo` function to calcul... | ```swift
func fibo(_ n: Int) -> Int {
if n <= 1 {
return n
} else {
return fibo(n - 1) + fibo(n - 2)
}
}
let n = Int(CommandLine.arguments[1]) ?? 0
let fibonacciNumber = fibo(n)
print("\(n) -> \(fibonacciNumber)")
```
In the solution, the `fibo` function is implemented using recursion to ca... | magicoder | swift |
You are tasked with creating a Python class to manage chapters in a digital magazine application. The class should handle the display of content and user interaction. Your task is to implement the `Mag` class with specific methods and attributes.
The `Mag` class should have the following attributes:
- `title`: A strin... | ```python
class Mag:
def __init__(self, title):
self.title = title
self.chapters = []
def add_chapter(self, chapter):
if isinstance(chapter, Chapter):
self.chapters.append(chapter)
else:
raise ValueError("Invalid chapter instance provided")
def displ... | magicoder | python |
You are tasked with creating a script to automate the initialization of SSH connections to multiple remote servers. The script should read a list of servers with their corresponding IP addresses, passwords, and ports from a file, and then attempt to establish SSH connections to each server using the provided credential... | ```python
import paramiko
import os
# Function to initialize SSH connection and log the status
def initialize_ssh(server, ip, password, port, log_dir):
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
log_file = os.path.join(log_dir, f"{server}_ssh.log")
... | magicoder | python |
You are tasked with creating a Python script to automate the management of Docker containers. Your script should stop and remove a specified Docker container. You will need to utilize the `docker` Python library to interact with the Docker daemon and perform these operations.
Your script should take the name of the Do... | ```python
import docker
def manage_docker_container(container_name):
client = docker.from_env()
try:
container = client.containers.get(container_name)
print(f"Stopping container: {container_name}")
container.stop()
print(f"Removing container: {container_name}")
container... | magicoder | python |
You are tasked with implementing a custom error handling mechanism for a Rust program. The goal is to create a custom error type and associated error handling logic to handle invalid values encountered during the program's execution.
Your task is to define a custom error type called `CustomError` that can represent tw... | ```rust
use std::str::FromStr;
// Define a custom error type
#[derive(Debug, PartialEq)]
enum CustomError {
UnexpectedValue(f64),
UnexpectedString(String),
}
impl CustomError {
fn invalid_value(value: f64) -> CustomError {
CustomError::UnexpectedValue(value)
}
fn invalid_string(value: &st... | magicoder | rust |
You are tasked with creating a buffer overflow exploit to gain control of a vulnerable program. The given code snippet is part of an exploit script that sends a payload to the program in order to execute shellcode and gain a shell. Your goal is to craft a payload that will successfully exploit the program and execute t... | To solve this problem, you need to craft a payload that will successfully exploit the program and execute the shellcode. The payload should be constructed as follows:
1. Generate the appropriate shellcode for the target architecture and operating system using a tool such as msfvenom or by manually crafting the shellco... | magicoder | python |
You are tasked with implementing a message flashing system in a web application. In web development, a message flashing system is used to display temporary messages to the user, typically after a specific action has been performed, such as creating a new item or updating a record. The messages are usually displayed to ... | ```php
function flashAndRedirect($message, $messageType, $redirectUrl) {
// Store the message in the session with the specified type
session()->flash('message', $message);
session()->flash('messageType', $messageType);
// Redirect the user to the specified URL
return redirect($redirectUrl);
}
```
... | magicoder | php |
You are tasked with implementing a custom serialization and deserialization mechanism for a Rust struct using the `serde` library. The struct represents a generic type that can be serialized and deserialized using a custom format. Your goal is to create the necessary implementations to enable the serialization and dese... | ```rust
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde::de;
use serde::ser::SerializeMap;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
struct CustomSerializable<T> {
data: T,
// Other fields and methods may be present
}
impl<T> Serialize for CustomSerializable<T>
where
... | magicoder | rust |
You are tasked with implementing a user interface (UI) system for a mobile game. The provided code snippet contains three methods within a UIEventManager class, each responsible for handling button events to display different UI panels. The UIComponent class provides a static method GetUiView<T>() to retrieve the UI vi... | ```csharp
// Define the UI panel component types
public enum PanelComponentType
{
RulePanel,
FiveStarSetPanel,
ActivityAndAnnouncementPanel
}
// Define the UI panel component base class
public abstract class UIPanelComponent
{
public abstract void Show();
}
// Define the specific UI panel component cl... | magicoder | csharp |
You are tasked with creating a Python program that simulates a simple file management system. The program should be able to perform basic file operations such as creating, reading, updating, and deleting files. Additionally, the program should be able to execute user-defined commands on the files.
Your task is to impl... | ```python
import subprocess as sp
import sys
class FileManager:
def create_file(self, filename: str, content: str) -> None:
with open(filename, 'w') as file:
file.write(content)
def read_file(self, filename: str) -> str:
with open(filename, 'r') as file:
return file.rea... | magicoder | python |
You are tasked with creating a Django model for an alarm system. The model should represent an alarm with specific attributes and constraints. Your task is to implement the `Alarm` model with the following requirements:
- The `Alarm` model should inherit from `RulesModel`.
- It should have the following fields:
- `ti... | ```python
from django.db import models
from django.contrib.auth.models import User
from rules.models import RulesModel
class Sound(models.Model):
# Define the Sound model if not already defined
pass
class Alarm(RulesModel):
"""Model representing an alarm"""
title = models.CharField(max_length=200, def... | magicoder | python |
You are tasked with implementing a custom `SelectMany` operator in C#. The `SelectMany` operator is used to project each element of a sequence to an `IEnumerable` and flatten the resulting sequences into one sequence. Your task is to create a class that implements this operator and to write a method that applies the op... | To implement the `SelectMany` operator, you can create a class named `SelectManyOperator` that extends the `ILink<T, V>` interface. Within this class, you can implement the necessary logic to apply the `SelectMany` operator to a sequence.
Here's a possible implementation of the `SelectManyOperator` class:
```csharp
p... | magicoder | csharp |
You are tasked with implementing a higher-order function in TypeScript that takes in a variable number of functions as arguments and returns a new function. The returned function should take a single argument and apply each of the input functions to it in sequence, passing the result of each function as the argument to... | ```typescript
const compose = (...args: any[]) => (x: any) => args.reduce((res, cb) => cb(res), x);
```
The `compose` function takes a variable number of functions as arguments using the rest parameter syntax `...args`. It returns a new function that takes a single argument `x`. Inside the returned function, the `reduc... | magicoder | typescript |
You are tasked with creating a Python function that processes a list of column names and data types and generates the corresponding SQLAlchemy column creation code for a given table. The function should take in a list of tuples, where each tuple contains the column name as a string and the data type as a string. The ou... | ```python
import sqlalchemy as sa
from alembic import op
def generate_column_creation_code(table_name, columns):
code = ""
for column in columns:
column_name, data_type = column
code += f"op.add_column('{table_name}', sa.Column('{column_name}', sa.{data_type}(), autoincrement=False, nullable=Tr... | magicoder | python |
You are tasked with implementing a module resolution algorithm for a JavaScript-like language. The given code snippet represents a module system where different modules are being exported. Each module is represented by a file in a specific directory structure. The module resolution algorithm needs to determine the corr... | ```javascript
function resolveModulePath(importStatement, currentFilePath) {
const moduleTypes = ['immutable', 'mutable', 'causal', 'hashing', 'literals'];
const modulePath = importStatement.replace('import * from', '').trim();
const resolvedPath = currentFilePath.split('/').slice(0, -1).join('/') + modulePath + ... | magicoder | javascript |
You are tasked with creating a program that processes a given input file and generates an output file based on the content of the input. The input file will contain a series of commands, each on a separate line. Each command will be in the format of a shell command, and your program should process these commands accord... | ```python
import os
def process_commands(input_file, output_file):
with open(input_file, 'r') as f:
commands = f.readlines()
with open(output_file, 'w') as f:
for command in commands:
parts = command.split()
if parts[0] == 'echo':
f.write(' '.join(parts[... | magicoder | python |
You are tasked with implementing a function to update the physics of units in a star system simulation. The provided code snippet is a part of the existing codebase and contains a segment of the `UpdateUnitPhysics` function in the `StarSystem` class. The function is responsible for updating the physics of units within ... | ```cpp
void StarSystem::UpdateUnitPhysics(bool firstframe) {
Unit* unit = nullptr;
for (int queue = 0; queue < SIM_QUEUE_SIZE; ++queue) {
un_iter iter = this->physics_buffer[queue].createIterator();
while ((unit = *iter) && *iter != un) {
++iter;
}
if (unit == un) {
... | magicoder | cpp |
You are working on a computer vision project and need to implement a function that performs a specific operation on an input tensor. The function takes an input tensor `h` and processes it using the `score_fr` and `upscore32` methods. After processing, it returns a modified tensor.
The `score_fr` method is responsible... | ```python
import torch
def process_tensor(h, o_h, o_w):
# Perform initial processing using score_fr method
h = score_fr(h)
# Perform upsampling using upscore32 method
upscore32 = upscore32(h)
# Calculate the dimensions for extracting the region of interest
u_h, u_w = upscore32.size()[... | magicoder | python |
You are tasked with creating a generic data structure that represents a stack with a twist. In addition to the standard push and pop operations, this stack should also support a "getMinimum" operation that returns the minimum element currently in the stack. Your task is to implement this special stack using any program... | ```python
class SpecialStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, x):
self.stack.append(x)
if not self.min_stack or x <= self.min_stack[-1]:
self.min_stack.append(x)
def pop(self):
if self.stack:
popped = se... | magicoder | python |
You are tasked with implementing a task management application using the Model-View-ViewModel (MVVM) architecture. The application uses RxSwift for reactive programming and the Action library for handling asynchronous actions.
Your task is to complete the implementation of the `EditTaskViewModel` struct, which is resp... | ```swift
import Foundation
import RxSwift
import Action
struct EditTaskViewModel {
let taskName: Observable<String>
let errors: Observable<Error>
private let editTaskAction: Action<String, Void>
private let taskNameSubject: BehaviorSubject<String>
private let errorsSubject: PublishSubject<Erro... | magicoder | swift |
You are tasked with creating a program that calculates the age of a person based on their birth year and gender. The program should prompt the user to input their birth year and gender, and then calculate and display their age. The program should handle cases where the birth year is from the current century or the prev... | ```python
import datetime
def calculate_age():
atual = datetime.datetime.now().year
ano_Nasc = int(input("Digite o ano de nascimento: "))
if atual - ano_Nasc > 100: # caso o ano digitado seja do século anterior
ano_Nasc += 100
gen = str(input('Qual o seu gênero de nascimento? (M/F): ... | magicoder | python |
You are tasked with implementing a function that transforms a set of 3D points from a Cartesian coordinate system to a robot coordinate system. The function takes in the rotation angle `alpha`, the translation values `deltax`, `deltay`, and `deltaz`, and a set of 3D points `xyzc` in the Cartesian coordinate system. The... | ```python
import math
import numpy as np
def PointsToRobot(alpha, deltax, deltay, deltaz, xyzc):
sina = math.sin(alpha)
cosa = math.cos(alpha)
pointrs = []
for pointc in xyzc:
# METHOD 2: matrix calculation
pc = pointc.reshape(3, 1)
R = np.array([cosa, -sina, 0, sina, cosa, 0, ... | magicoder | python |
You are tasked with creating a program that simulates a simple text-based web page renderer. The program should parse a given HTML-like input and generate the corresponding rendered output.
Your task is to implement a function `renderHTML` that takes a string `html` as input and returns the rendered output as a string... | ```python
def renderHTML(html):
stack = []
result = ""
i = 0
while i < len(html):
if html[i] == '<':
j = i + 1
while j < len(html) and html[j] != '>':
j += 1
tag = html[i+1:j]
if tag[0] == '/':
stack.pop()
... | magicoder | python |
You are tasked with implementing a Python class that interacts with an API to retrieve growth activity data for a specific list. The provided code snippet is a partial implementation of the `ListGrowthHistory` class, which is intended to handle this functionality. Your task is to complete the implementation of the `Lis... | ```python
class ListGrowthHistory(BaseClass):
def __init__(self, *args, **kwargs):
super(ListGrowthHistory, self).__init__(*args, **kwargs)
self.endpoint = 'lists'
self.list_id = None
self.month = None
async def all(self, list_id, get_all=False, **queryparams):
"""
... | magicoder | python |
You are given a snippet of HTML code representing a portion of a web page. Your task is to write a function that parses this HTML snippet and extracts specific information from it.
The HTML snippet contains a structure representing a table row with three columns. Each column contains different types of data and elemen... | ```javascript
const parseHTMLSnippet = (html) => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const numericalValue = doc.querySelector('.ub-color_425A70').textContent.trim();
const hyperlinkText = doc.querySelector('a').textContent.trim();
const iconType = doc.quer... | magicoder | javascript |
You are tasked with creating a script to automate the validation of SwiftLint configuration files in a version-controlled repository. The script should compare the current SwiftLint configuration file with the latest version available in the "versions" directory and take appropriate action based on the comparison resul... | ```bash
#!/bin/bash
# Step 1: Determine the latest version number
last_version=$(ls versions | sed 's/\([0-9]\+\).*/\1/g' | sort -n | tail -1)
# Step 2: Compare the current "swiftlint.yml" file with the latest version
if cmp --silent "swiftlint.yml" "versions/$last_version/swiftlint.yml"; then
echo "SwiftLint con... | magicoder | shell |
You are tasked with implementing a file transcribing utility that processes either a single file or an entire directory of files. The utility should handle command-line arguments, validate input, and transcribe the content of the file(s) according to certain rules.
Your task is to complete the implementation of the `T... | ```python
import logging
from pathlib import Path
class Transcriber:
def __init__(self, args):
self.args = args
def process_dir(self, args):
for file_path in Path(args.input).iterdir():
if file_path.is_file():
self.transcribe_file(file_path)
def transcribe_file... | magicoder | python |
You are tasked with implementing a recommendation system for a social media platform. The system should allow users to postpone recommendations and reactivate previously postponed recommendations. You are given a class snippet from the recommendation system's codebase, which includes methods for postponing and reactiva... | ```csharp
using System;
public class RecommendationSystem
{
public void PostponeRecommendation(string recommendationId, DateTime postponeUntilDateTime)
{
// Append the recommendation ID and postpone date to the request URL
this.AppendSegmentToRequestUrl("microsoft.graph.postpone");
this... | magicoder | csharp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.