query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a function that joins foreign entities to a given result set based on certain conditions. The function takes an array of results as input and should return the modified result set after joining the foreign entities.
You are provided with a code snippet from a PHP class that includes a ... | ```php
protected function join_foreigns(array $result)
{
// Assuming $model is an instance of the model class
$prefix = $this->input->post_get('prefix');
$conds = []; // Initialize an array to store conditions for joining foreign entities
if ($prefix = trim($prefix)) {
// Assuming $model has a ... | magicoder | php |
You are given a C++ code snippet from a unit test using the Google Test framework. The code snippet shows a part of a test case for a Windows Registry manipulation function. The test case checks the behavior of the function when retrieving different types of registry values.
Your task is to implement a function that s... | ```cpp
#include <gtest/gtest.h>
#include <windows.h>
// Function to be implemented
std::string getRegistryValue(const std::string& keyName, const std::string& valueName) {
HKEY hKey;
std::string retrievedValue;
// Open the registry key
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName.c_str(), 0, KEY_READ,... | magicoder | cpp |
You are tasked with creating a Python function that takes a string as input and performs a specific transformation on it. The transformation involves converting all vowels in the input string to uppercase and all consonants to lowercase. The function should then return the modified string.
Create a function called `tr... | ```python
def transform_string(input_string):
vowels = "aeiou"
result = ""
for char in input_string:
if char.lower() in vowels:
result += char.upper()
else:
result += char.lower()
return result
# Test the function with the given example
input_str = "Hello hue"
ou... | magicoder | python |
You are tasked with creating a script to automate the deployment and management of a Dockerized application. Your script should perform the following actions in sequence:
1. Stop and remove the running Docker containers using `docker-compose down`.
2. Remove a specific Docker image named `csgo-match-forwarding_match-n... | ```bash
#!/bin/bash
# Step 1: Stop and remove running Docker containers
sudo docker-compose down
# Step 2: Remove the specific Docker image
sudo docker image rm csgo-match-forwarding_match-nonebot
# Step 3: Start Docker containers in detached mode
sudo docker-compose up -d
# Step 4: Continuously monitor the logs of... | magicoder | shell |
You are tasked with creating a command-line interface (CLI) tool to interact with Trello boards. Your goal is to implement a command that allows users to create a new board on Trello. The CLI tool uses the `click` library for command-line parsing and is expected to interact with Trello's API to create the board.
Your ... | ```python
import click
import requests
def get_tokens():
# Assume this function retrieves the necessary authentication tokens
# for interacting with Trello's API
pass
@click.command()
@click.argument('board_name')
def create_board(board_name):
""" To create a board in Trello with BOARD_NAME
B... | magicoder | python |
You are tasked with creating a Python class that reads and parses the contents of a Linux OS release file. The OS release file contains key-value pairs representing various attributes of the operating system. The class should provide a method to read the OS release file and return its contents as a dictionary.
You are... | ```python
class OSInfo:
OS_RELEASE = '/etc/os-release'
@classmethod
def read_os_release(clazz):
with open(clazz.OS_RELEASE, 'r') as fin:
return clazz.OS_RELEASE, fin.read()
@classmethod
def parse_os_release(clazz):
os_release_data = {}
with open(clazz.OS_RELEASE, 'r') as fin:
for lin... | magicoder | python |
You are tasked with creating a command-line utility that simulates a simple virtual machine called "Krill." The Krill virtual machine executes code written in a custom language, and your goal is to implement a specific feature of this virtual machine.
The Krill virtual machine takes a file containing Krill code as inp... | ```python
def executeKrillCode(code):
output = ""
data = [0] * 30000 # Initialize the data array with 30000 cells
pointer = 0
code_ptr = 0
while code_ptr < len(code):
command = code[code_ptr]
if command == '>':
pointer += 1
elif command == '<':
pointe... | magicoder | python |
You are tasked with implementing a Python function that processes an image using OpenCV library. The function should perform Gaussian blur on the input image and display the blurred image in a window. Additionally, the function should wait for the user to press the 'q' key to close the displayed image. If the 'q' key i... | ```python
import cv2
# GaussianBlur FUNCTION
def gaussianBlurImage(image):
image_blur = cv2.GaussianBlur(image, (7, 7), 0)
cv2.imshow("GaussianBlur Image", image_blur)
if cv2.waitKey(0) == ord('q'):
cv2.destroyAllWindows()
``` | magicoder | python |
You are tasked with implementing a simplified version of a client class for a web service. The client class has a method to set the authentication token for accessing the web service. Your goal is to create a method that generates a new authentication token and sets it in the client class.
You are given the following ... | ```python
def generate_and_set_auth_token(client, token_generator):
client.auth_token = token_generator()
```
The `generate_and_set_auth_token` function takes in the `client` object and a `token_generator` function. It sets the `auth_token` attribute of the `client` object to the value returned by the `token_gener... | magicoder | python |
You are tasked with implementing a class to parse and extract data from a BLE (Bluetooth Low Energy) Blood Pressure Service. The service exposes blood pressure and other related data from a blood pressure monitoring device. The data is transmitted in a specific format defined by the Bluetooth SIG (Special Interest Grou... | ```swift
import Foundation
struct BloodPressureData {
let systolic: UInt16
let diastolic: UInt16
let meanArterialPressure: UInt16
let timestamp: UInt16
}
class BloodPressureServiceParser {
func parseData(_ rawData: [UInt8]) -> BloodPressureData {
let flags = rawData[0]
let systolic... | magicoder | swift |
You are tasked with implementing a function to parse a given Fluent resource string and handle any parsing errors. Fluent is a localization system used for natural-sounding translations in software applications. The provided code snippet is a part of a FluentResource implementation in Rust, which attempts to create a n... | ```rust
use rentals::Rentals;
#[derive(Debug)]
struct FluentResource(rentals::Rentals<str>);
#[derive(Debug)]
enum ParserError {
// Define custom parsing errors here
MissingSemicolon,
// More error types can be added as needed
}
impl FluentResource {
pub fn try_new(source: String) -> Result<Self, (Se... | magicoder | rust |
You are tasked with implementing a placeholder system for a mobile application. The placeholder system should allow the creation of placeholders with customizable data and styles. Each placeholder will have associated data and a style, and the system should be able to render the placeholders with the specified data and... | ```swift
import Foundation
import UIKit
/// The NKPlaceholderData object, used to hold the data of the placeholder
public struct NKPlaceholderData {
var title: String
var description: String
// Add any other properties as needed
init(title: String, description: String) {
self.title = title... | magicoder | swift |
You are tasked with implementing a Python function to convert paired-end FASTQ files into a SAM file. The function should parse the input FASTQ files line by line and write the output SAM file. The input FASTQ files contain paired-end reads, and the output SAM file should follow the SAM format specifications.
The func... | ```python
def convert(_path2Reads1, _path2Reads2, _path2output):
with open(_path2Reads1, 'r') as reads1, open(_path2Reads2, 'r') as reads2, open(_path2output, 'w') as output_sam:
for line1, line2 in zip(reads1, reads2):
# Process the paired-end reads and generate SAM entries
# Exampl... | magicoder | python |
You are tasked with implementing a Python function that processes a list of time durations represented as strings and returns the total duration in seconds. Each time duration string is in the format "HH:MM:SS" (hours, minutes, seconds). However, some of the time durations may be invalid and need to be handled appropri... | ```python
from typing import List
def calculate_total_duration(durations: List[str]) -> int:
total_seconds = 0
for duration in durations:
try:
hours, minutes, seconds = map(int, duration.split(':'))
if hours >= 0 and minutes >= 0 and seconds >= 0:
total_seconds +... | magicoder | python |
You are tasked with implementing a Django model for a maze game. The model represents a character within the game and has several fields and methods associated with it. Your task is to complete the implementation of the `Character` model by adding the missing parts based on the provided code snippet and requirements.
... | ```python
from django.db import models
from django.urls import reverse
class Level(models.Model):
# Define the Level model if not already defined
class Pixel(models.Model):
# Define the Pixel model if not already defined
class Character(models.Model):
name = models.CharField(max_length=100)
direction... | magicoder | python |
You are working as a DevOps engineer for a company that uses Docker and Open vSwitch for network virtualization. Your task is to automate the process of building and packaging Open vSwitch for deployment on Raspberry Pi devices. The provided code snippet is a part of the automation script used for this purpose.
The sc... | ```python
def build_openvswitch_command():
return 'docker run --rm -ti --cap-add NET_ADMIN -v $(pwd)/builds:/builds hypriot/rpi-openvswitch-builder /bin/bash -c \'DEB_BUILD_OPTIONS="parallel=8 nocheck" fakeroot debian/rules binary && cp /src/*.deb /builds/ && chmod a+rw /builds/*\''
```
The `build_openvswitch_comma... | magicoder | python |
You are tasked with creating a simple HTTP server using Rust's async/await syntax. Your goal is to implement the missing parts of the `run` method in the given code snippet to create a functional HTTP server.
The `run` method is part of a struct that represents an HTTP server. It takes in a `SocketAddr` as a parameter... | ```rust
use std::net::SocketAddr;
use hyper::{Server, Request, Response, Body, Error, service::service_fn};
pub struct HttpServer {
log: Logger, // Assume the existence of a Logger type
}
impl HttpServer {
pub async fn run(&self, addr: SocketAddr) {
info!(self.log, "Listening on http://{}", addr);
... | magicoder | rust |
You are tasked with implementing a Python function that can encode and decode SAMLRequest strings using a combination of compression, base64 encoding, and URL encoding. The SAMLRequest string is first compressed using the zlib library, then the compressed string is base64 encoded and URL encoded. The function should al... | ```python
import zlib
import base64
import urllib.parse
def encode_saml_request(StringSAMLRequest):
zlibbed_str = zlib.compress(StringSAMLRequest.encode())
compressed_string = zlibbed_str[2:-4]
encoded_string = base64.b64encode(compressed_string)
return urllib.parse.quote_plus(encoded_string)
def deco... | magicoder | python |
You are tasked with implementing a simple navigation system for a user interface module in a desktop application. The provided code snippet is a simplified representation of the UIModule class, which is responsible for managing the UI navigation using the Prism library in a WPF application.
The UIModule class has a co... | ```csharp
public class UIModule
{
private readonly RegionManager _regionManager;
private readonly IUnityContainer _container;
public UIModule(RegionManager regionManager, IUnityContainer container)
{
_regionManager = regionManager;
_container = container;
}
public void Initiali... | magicoder | csharp |
You are tasked with implementing a function to determine the relationship between two commits in a version control system. The function `find_commit_relationship(a, b, repo)` takes two commit identifiers `a` and `b`, as well as a repository `repo`, and returns the relationship between the commits.
The function should ... | ```python
from enum import Enum
class CommitsRelationship(Enum):
same = 1
ancestor = 2
descendant = 3
unrelated = 4
def find_commit_relationship(a, b, repo):
"""Describes the relationship of a to b.
Returns a CommitsRelationship; e.g. CommitsRelationship.ancestor if a is
an ancestor of b.... | magicoder | python |
You are tasked with implementing a function that formats and displays summary logs for different metrics and species. The function takes in a dictionary `summary_logs` containing summary data for various metrics and species. Each metric contains a dictionary with species as keys and a list of lists as values. The inner... | ```python
def format_summary_logs(summary_logs: dict, SPACE: int) -> str:
formatted = []
for metric, species_data in summary_logs.items():
for species, rows in species_data.items():
for i, row in enumerate(rows):
formatted.append(''.join([j + (' ' * (SPACE - len(j))) for j in... | magicoder | python |
You are tasked with creating a Python function that simulates a simple text-based game. The game involves a player navigating through a series of rooms, each with its own set of challenges and rewards. The player must make choices at each step, and the outcome of their choices will determine their progress in the game.... | ```python
import click
def warn(message):
click.secho(f'\n==> {message}', fg='red')
def explore_game():
click.echo("Welcome to the Text Adventure Game!")
click.echo("You find yourself in a mysterious castle with three rooms to explore.")
# Room 1
click.echo("\nRoom 1: The Dark Hallway")
click... | magicoder | python |
You are given a Python function that processes an input file and returns a tuple of two values. The function takes the input file path as an argument and performs the following operations:
1. It initializes a variable `start` with a value from the input file.
2. It iterates through the input file, calculating the diffe... | ```python
def generate_input_file():
# The input file should be generated in such a way that it produces the maximum product of final[1] and final[3],
# and the maximum key in the results dictionary.
# To achieve this, the input file should be carefully crafted to produce the desired output when processed b... | magicoder | python |
You are tasked with creating a program to manage system settings using a command-line interface. The program should read a series of commands and execute them to modify the system settings accordingly. Each command consists of a description, a set of keys, and their corresponding values. The keys and values may vary in... | ```python
import subprocess
def execute_commands(commands):
for command in commands:
try:
subprocess.run(command, shell=True, check=True)
except subprocess.CalledProcessError as e:
print(f"Command '{command}' failed with error: {e}")
except Exception as e:
... | magicoder | python |
You are tasked with creating a Python program that processes a given input file and performs specific actions based on the content of the file. The program should read the input file line by line and apply different operations depending on the content of each line. The operations include pasting a script, pasting CSS, ... | ```python
def processInputFile(inputFileName, outputFileName, classId, cssId):
with open(inputFileName, 'r', encoding='utf-8') as inputFile, open(outputFileName, 'w', encoding='utf-8') as outputFile:
for line in inputFile:
if classId in line:
pasteScript(line, outputFile)
... | magicoder | python |
You are given a 2D numpy array `expected_sum_mat` representing a matrix of integers. The first row of the matrix represents the expected sum of each column, the second row represents the expected sum of the Y-axis, and the third row represents the expected sum of the X-axis. Your task is to write a function `find_missi... | ```python
import numpy
def find_missing_values(expected_sum_mat: numpy.ndarray) -> numpy.ndarray:
total_sum = expected_sum_mat[0]
y_sum = expected_sum_mat[1]
x_sum = expected_sum_mat[2]
# Create a matrix with the same shape as expected_sum_mat filled with -1
result_mat = numpy.full(expected_sum_ma... | magicoder | python |
You are tasked with creating a script to automate the training and testing process for a part-of-speech tagging model using the M3N algorithm. The training and testing are performed using the `run.sh` script, which takes various parameters and options. Your task is to write a shell script that orchestrates the training... | ```bash
#!/bin/bash
# Define input and output file paths
TRAINING_DATA="training_data.txt"
VALIDATION_DATA="validation_data.txt"
M3N_OUT="m3n_model"
M3N_LOG="m3n_training_log.txt"
LR_OUT="lr_model"
LR_VALIDATION="lr_validation_results.txt"
LR_TRAIN="lr_training_results.txt"
# Set training parameters
ITERATIONS=100
L2... | magicoder | shell |
You are given a list of integers representing the heights of a group of people standing in a line. Your task is to determine the number of people visible from the front of the line. A person is visible if there is no one taller standing in front of them. Write a function `visible_people_count` that takes in the list of... | ```python
from typing import List
def visible_people_count(h: List[int]) -> int:
n = len(h)
visible_count = 0
max_height = 0
for height in h:
if height > max_height:
visible_count += 1
max_height = height
return visible_count
``` | magicoder | python |
You are tasked with creating a script to automate the installation of the latest nightly version of PyTorch using the provided code snippet as a reference. Your script should fill the `PYTORCH_VERSION` variable with the latest conda nightly version and populate the `CONDA_CHANNEL_FLAGS` variable with appropriate flags ... | ```bash
#!/bin/bash
# Function to retrieve the latest conda nightly version of PyTorch
get_latest_pytorch_version() {
# Logic to retrieve the latest conda nightly version of PyTorch and store it in PYTORCH_VERSION
# Example:
PYTORCH_VERSION="1.9.0.dev20210607"
}
# Function to populate CONDA_CHANNEL_FLAGS ... | magicoder | shell |
You are tasked with implementing a simple command handling service for a chatbot application. The provided code snippet outlines an interface `ISlashCommandHandlingService` that defines a method `Handle` to process slash commands. Your goal is to create a class that implements this interface and handles incoming slash ... | ```csharp
using System.Threading.Tasks;
namespace XudonaxBot.Bot.Services
{
public class SimpleSlashCommandHandlingService : ISlashCommandHandlingService
{
public async Task Handle(SocketSlashCommand command)
{
// Perform a simple action based on the received command
// ... | magicoder | csharp |
You are working on a project to simulate the behavior of electromagnetic waves interacting with different types of objects. In this scenario, you need to implement a function that calculates the Green's function for a spherical and cylindrical scatterer. The Green's function is defined as follows:
For a spherical scat... | ```python
import numpy as np
def calculate_greens_function(freq, r, d_ij, M, c):
_delta = 2 * r * np.sin(np.pi * d_ij / M)
g_dn_sphere = np.sinc(2 * np.pi * freq[:, None, None] * _delta[None] / c)
g_dn_cylinder = np.i0(2 * np.pi * freq[:, None, None] * _delta[None] / c)
return g_dn_sphere, g_dn_cylinde... | magicoder | python |
You are tasked with implementing a class method that parses a URL and extracts the path and query parameters from it. The method should adhere to a specific regular expression pattern and handle any potential errors that may arise during the parsing process.
You are given the following code snippet as a starting point... | ```php
public function parseUrl($requestUri) {
try {
$baseUri = self::$base_uri;
$regExp = '/^' . preg_quote($baseUri, '/') . '[\/]?([^\?]*)(\?.*)?$/i';
$matches = [];
if (preg_match($regExp, $requestUri, $matches)) {
$path = $matches[1];
$query = iss... | magicoder | php |
You are tasked with creating a program to analyze the connectivity of a graph. The program should determine whether the graph is directed or undirected, calculate the proportion of connected edges, and print the number of nodes, edges, and self-loops in the graph. Additionally, it should output the percentage of node p... | ```python
import networkx as nx
class GraphAnalyzer:
def __init__(self, graph):
self.graph = graph
def analyze_graph(self):
number_of_nodes = len(self.graph.nodes)
number_of_edges = len(self.graph.edges)
number_of_selfloops = len(list(nx.selfloop_edges(self.graph)))
if... | magicoder | python |
You are tasked with implementing a function to find the seat details based on a given boarding pass string. The boarding pass string consists of 10 characters, where the first 7 characters are either 'F' or 'B', and the last 3 characters are either 'L' or 'R'. The first 7 characters represent the row number, and the la... | ```rust
fn find_seat_details(boarding_pass: &str) -> (u32, u32) {
let row_str = &boarding_pass[..7];
let col_str = &boarding_pass[7..];
let row = row_str.chars().fold(0, |acc, c| (acc << 1) + if c == 'B' { 1 } else { 0 });
let col = col_str.chars().fold(0, |acc, c| (acc << 1) + if c == 'R' { 1 } else {... | magicoder | rust |
You are tasked with creating a C++ module for a game-saving system. The provided code snippet is a part of the module implementation. The `SaveExtension.h` header file contains necessary declarations and definitions for the module. The `LogSaveExtension` is a logging category, and `FSaveExtension` is the module class b... | ```cpp
// SaveExtension.h
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"
class FSaveExtension : public IModuleInterface
{
public:
virtual void StartupModule() override;
virtual void ShutdownModule() override;
void SaveGameStateToFile(const FString& FilePath);
void LoadGameSta... | magicoder | cpp |
You are tasked with creating a Python program to simulate a simple DNS spoofing attack. In a DNS spoofing attack, the attacker provides false DNS information to a DNS resolver, redirecting traffic to malicious servers. Your program should spoof a DNS response for a given domain name and IP address.
Your program should... | ```python
from scapy.layers.dns import DNSRR, DNSQR
def spoof_dns_response(qname, spoof_ip, ttl):
# Construct a DNS response record with the provided inputs
dnsrr = DNSRR(rrname=qname, ttl=ttl, rdata=spoof_ip)
return dnsrr
```
The `spoof_dns_response` function takes the domain name (`qname`), the IP addre... | magicoder | python |
You are tasked with implementing a rating system for articles in a web application. The system should allow users to rate articles, and also display the average rating for each article. However, there are certain constraints and requirements that need to be enforced.
Your task is to design and implement a Python class... | ```python
class ArticleRatingSystem:
def __init__(self):
self.ratings = {} # Dictionary to store ratings for each article
def add_rating(self, article_id, user_id, rating):
if article_id not in self.ratings:
self.ratings[article_id] = {'total': rating, 'count': 1}
else:
... | magicoder | python |
You are tasked with implementing a Swift extension for working with 3D transformations. The extension should provide functionality to determine if a given `CATransform3D` can be represented exactly by an affine transform and to obtain the affine transform representation if possible.
Your task is to create the extensio... | ```swift
// Define the extension for CATransform3D
public extension CATransform3D {
/// Returns true if the receiver can be represented exactly by an affine transform.
@inlinable
var isAffine: Bool { CATransform3DIsAffine(self) }
/// Returns the affine transform represented by the receiver if possible;... | magicoder | swift |
You are tasked with implementing a function that processes a series of events and produces a list of results based on the event type. The events are represented as an enum called `EventType`, and the results are represented as an enum called `NodeWatchEvent`. The function should handle different event types and produce... | ```rust
use std::error::Error;
fn process_events(events: Vec<EventType>) -> Option<Result<Vec<NodeWatchEvent>, Box<dyn Error>>> {
let mut results = Vec::new();
for event in events {
match event {
EventType::Get => {
// No result for EventType::Get
}
... | magicoder | rust |
You are given a Python function that calculates the exponent of the highest power of 2 that divides a given positive integer. Your task is to implement a similar function in a different programming language, Java, and ensure that it produces the same output as the given Python function.
You should write a Java functio... | ```java
public class Main {
public static void main(String[] args) {
System.out.println(highestPowerOfTwo(256)); // Output: 8
System.out.println(highestPowerOfTwo(64)); // Output: 6
System.out.println(highestPowerOfTwo(128)); // Output: 7
}
public static int highestPowerOfTwo(int n... | magicoder | java |
You are tasked with implementing a function that processes a list of Miller indices and symmetry operations to find the corresponding transformed indices that lie inside a specified asymmetric unit.
You are given the following information:
- An asymmetric unit (asu) object with a method `is_inside` that takes a Miller... | ```python
def find_transformed_indices(hkl, asu, sg):
transformed_indices = []
symmetry_operations = []
for h in hkl:
found = False
for i_smx in range(sg.n_smx()):
rt_mx = sg(0, 0, i_smx) # Assuming i_inv is always 0
_hkl = [-h for h in hkl]
mhkl_ = ... | magicoder | python |
You are tasked with creating a notification system for an admin module in a corporation's web application. The notification system should be implemented within the `Corporation.Models.Admin.Notification` namespace. The system should support the following functionalities:
1. Sending notifications to individual users.
2.... | ```csharp
using System;
using System.Collections.Generic;
namespace Corporation.Models.Admin.Notification
{
// Interface for a notification
public interface INotification
{
string Message { get; }
DateTime Timestamp { get; }
bool IsRead { get; set; }
}
// Class representing... | magicoder | csharp |
You are working on a project to develop a machine learning algorithm for sparse coding using the SPAMS library in Python. As part of the algorithm, you need to implement a function that performs either Lasso regression or projected gradient descent based on the value of the `mode` variable. The code snippet provided is... | ```python
import numpy as np
import spams # Assuming spams library is already installed
def sparse_coding_algorithm(X, W, U0, lda2, Xnorm, mode, THREADS, use_chol, posU, U0_delta, maxItr):
if mode == 1:
U = spams.lasso(np.asfortranarray(X.T), D=np.asfortranarray(W.T),
lambda1=lda2*... | magicoder | python |
You are tasked with creating a Python function that performs relative import transformations on a given string based on a provided package. Relative imports are a way of importing modules in Python by specifying the relative location of the module with respect to the current module. The function should take a package n... | ```python
from typing import List, Tuple
def transform_relative_imports(package: str, string: str, transformations: List[Tuple[str, str]]) -> List[str]:
transformed_imports = []
for original, expected in transformations:
if original in string:
transformed_import = string.replace(original, e... | magicoder | python |
You are tasked with creating a function that takes a URL as input and returns a Boolean value indicating whether the URL is valid or not. A valid URL should start with "http://" or "https://", followed by a domain name (e.g., "www.example.com") and an optional path. The function should ignore case sensitivity and allow... | ```swift
func isValidURL(_ url: String) -> Bool {
let urlPattern = "^(http|https)://(www\\.)?[a-zA-Z0-9-]+(\\.[a-zA-Z]{2,})+(/\\S*)?$"
let regex = try! NSRegularExpression(pattern: urlPattern, options: .caseInsensitive)
let range = NSRange(location: 0, length: url.utf16.count)
return regex.firstMatch(in... | magicoder | swift |
You are tasked with creating a custom macro for optimizing image sizes in a web application. The macro should take in a set of image URLs and generate HTML image tags with optimized sizes based on the device's screen size. The macro should be implemented using the Rust programming language and the Perseus web framework... | ```rust
use quote::quote;
use syn::{parse_macro_input, ItemFn};
#[proc_macro_attribute]
pub fn perseus_size_opt(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input_fn = parse_macro_input!(item as ItemFn);
let fn_name = &input_fn.sig.ident;
let block = &input_fn.block;
let expanded = quot... | magicoder | rust |
You are tasked with creating a C# program that dynamically sets the assembly configuration based on the build mode. The assembly configuration should be set to "Debug" if the build mode is DEBUG, and "Release" if the build mode is RELEASE.
Your task is to write a C# program that achieves this behavior using conditiona... | ```csharp
using System;
public class AssemblyConfigurationSetter
{
public static void Main()
{
#if DEBUG
SetAssemblyConfiguration("Debug");
#else
SetAssemblyConfiguration("Release");
#endif
}
private static void SetAssemblyConfiguration(string configuration)
{
// Code to se... | magicoder | csharp |
You are tasked with implementing a Python class that represents an IP node in a network. The class should support adding child nodes, iterating through the nodes, and storing user data. Your task is to complete the implementation of the `IPNode` class by adding the necessary methods to fulfill the requirements.
The `I... | ```python
class IPNode:
def __init__(self, network):
self.network = network
self.children = {}
self.user_data_dict = {}
def add(self, node):
node.parent = self
self.children[node.network] = node
def __iter__(self):
return iter(self.children.values())
de... | magicoder | python |
You are tasked with creating a custom property wrapper in Swift that will enforce specific validation rules for a property. The property wrapper should be used to validate the `status` property of a class. The validation rules are as follows:
- The `status` property must be one of the following values: "active", "inact... | ```swift
// Define the StatusValidator property wrapper
@propertyWrapper
struct StatusValidator {
private var status: String
var wrappedValue: String {
get { status }
set { status = validate(newValue) ? newValue : status }
}
init(wrappedValue: String) {
self.status = va... | magicoder | swift |
You are tasked with implementing a function to update a specific value in a binary search tree (BST). The given code snippet is a part of the update function for a BST node. The function takes a value to be updated and a new value to replace the old one. The code snippet provided is the end of the update function, wher... | ```java
public boolean update(int value, int newValue) {
if (value == this.value) {
this.value = newValue; // update the value
return true; // update successful
} else if (value < this.value && left != null) {
return left.update(value, newValue); // recursively update in the left subtree... | magicoder | java |
You are working on a project that involves parsing and analyzing COBOL (Common Business-Oriented Language) code. Your task is to create a program that extracts and counts the occurrences of unique program unit names from a given COBOL source file. A program unit in COBOL can be a paragraph, section, or division.
Write... | ```python
import re
def count_program_units(cobol_code):
program_units = {}
pattern = r'(?<!-)\b[A-Z]+(?:-[A-Z]+)*(?:\s+DIVISION|\s+SECTION|\s+PARAGRAPH)\b'
matches = re.findall(pattern, cobol_code, re.IGNORECASE)
for match in matches:
program_unit = match.strip().upper()
program_units... | magicoder | python |
You are tasked with creating a Python function that simulates a simplified version of a machine learning training process. The function takes in a dictionary `info` containing relevant information and a boolean `training` flag. It then performs several operations including model prediction, loss computation, gradient c... | ```python
def train_model(self, info: dict, training: bool) -> dict:
pred = self(info, training=True) # Make a prediction using the model
loss = self.compiled_loss(info[self.resKey], pred) # Update the loss based on the prediction
usersCaracteristics, itemCaracteristics = self.computeEmb(info) # Compute ... | magicoder | python |
You are tasked with creating a script to manage a system for running and monitoring multiple data collection processes. The system should allow for starting, detaching, and managing these processes. To achieve this, you need to implement a Python script that interacts with the `screen` command to achieve the desired fu... | ```python
import subprocess
def start_screen_session(session_name, script_path):
subprocess.run(['screen', '-d', '-m', '-S', session_name, 'python', script_path])
def list_screen_sessions():
result = subprocess.run(['screen', '-ls'], capture_output=True, text=True)
print(result.stdout)
def terminate_scre... | magicoder | python |
You are tasked with creating a program that simulates the behavior of a database management system. The program should read a series of commands from an input file and execute them in the correct order. Each command is represented by a string and may be one of the following types:
1. "alter pluggable database all open"... | ```python
# Read input from input.txt
with open('input.txt', 'r') as input_file:
commands = input_file.readlines()
# Execute commands and write output to output.txt
with open('output.txt', 'w') as output_file:
for command in commands:
command = command.strip()
if command == "alter pluggable dat... | magicoder | python |
You are tasked with implementing a custom index function that mimics the behavior of Swift's standard library index function. The custom index function should take an integer i, an offset distance, and a limit, and return the resulting index after applying the offset by the given distance, considering the limit.
The f... | ```swift
public func index(_ i: Int, offsetBy distance: Int, limitedBy limit: Int) -> Int? {
let result = i + distance
return result <= limit ? result : nil
}
```
The solution defines the custom index function that takes an initial index `i`, an offset distance, and a limit. It calculates the resulting index by... | magicoder | swift |
You are tasked with implementing a secure login system for a web application. The provided code snippet is a simplified version of a login function in a Django web application. The function `login_user` is responsible for authenticating a user's credentials and logging them into the system if the credentials are valid.... | To enhance the security of the login process, you can modify the `login_user` function as follows:
```python
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.con... | magicoder | python |
You are given a quantum gate decomposition problem. Quantum gates are fundamental building blocks in quantum computing, and they are represented by unitary matrices. The task is to implement a function that decomposes an arbitrary one-qubit gate into a sequence of elementary gates. The elementary gates are defined as r... | ```python
import numpy as np
def decompose_gate(U):
# Extract the parameters of the unitary matrix U
alpha = np.angle(U[0, 0])
beta = -np.angle(U[1, 0])
gamma = np.angle(U[0, 1])
delta = np.angle(U[1, 1])
return alpha, beta, gamma, delta
```
The `decompose_gate` function first extracts the pa... | magicoder | python |
You are tasked with implementing a layout manager for a user interface that adapts to different size classes in an iOS application. The layout manager consists of a default rule set and a set of size class-specific rule sets. Each rule set contains layout options for a specific combination of horizontal and vertical si... | ```swift
public struct LayoutOption {
// Define layout options for a specific size class combination
// ...
}
public class SizeClassRuleSet<T> {
public let sizeClass: LayoutManager.SizeClass
public let layoutOptions: T
// Initialize the rule set with a specific size class combination and layout op... | magicoder | swift |
You are tasked with creating a program to manage different types of files in a content management system. The system should be able to handle model files and texture files, each with its own specific control for displaying and managing the file content.
You are given a code snippet from the existing system that uses a... | ```csharp
// Base class for file control
public abstract class File_Control
{
public abstract void DisplayFileContent();
public abstract void ManageFile();
}
// Class for managing model files
public class ModelFile_Control : File_Control
{
private ModelFile modelFile;
public ModelFile_Control(ModelFil... | magicoder | csharp |
You are given a string representing a decorative ASCII art of a Buddha figure. Your task is to write a function to count the number of non-space characters in the ASCII art.
Write a function `countNonSpaceChars` that takes a single parameter:
- `art` (1 <= |art| <= 1000): a string representing the ASCII art, where eac... | ```python
def countNonSpaceChars(art):
count = 0
for line in art.split('\n'):
count += len([char for char in line if char != ' '])
return count
``` | magicoder | python |
You are tasked with implementing a Python function that utilizes the turtle graphics library to draw a regular polygon. The function should take the number of sides of the polygon, the length of each side, and the angle between sides as input parameters. You need to define the function `draw_regular_polygon` to accompl... | ```python
import turtle
import math
def draw_regular_polygon(n, length, angle):
"""
Draw a regular polygon using turtle graphics.
Args:
n (int): Number of sides of the polygon.
length (int): Length of each side.
angle (int): Angle between sides.
Returns:
None
"""
bob = turtle.... | magicoder | python |
You are tasked with implementing a C++ class for interpolating data using the Delaunay triangulation method. The provided code snippet is a partial implementation of the `DelaunayStaticCPUInterpolator` class, which is a templated class for performing static CPU-based interpolation in N-dimensional space.
Your task is ... | ```cpp
#include "delaunay_static_cpu_interpolator.h"
template<typename index_t, int N_DIMS, int N_OPS>
DelaunayStaticCPUInterpolator<index_t, N_DIMS, N_OPS>::DelaunayStaticCPUInterpolator(
operator_set_evaluator_iface *supporting_point_evaluator,
const std::array<int, N_DIMS> &axes_points,
cons... | magicoder | cpp |
You are given a Python code snippet that defines a function `f(x)` and then uses this function to calculate and print the output for a range of input values. Your task is to understand the code and write the function `f(x)` in a different programming language, and then use it to produce the same output as the given Pyt... | ```cpp
#include <iostream>
using namespace std;
int f(int x) {
return 2 * x * x + 1;
}
int main() {
int n;
cout << "Ingrese número: ";
cin >> n;
for (int i = 0; i < n; i++) {
int y = f(i);
cout << i << " " << y << endl;
}
return 0;
}
```
The provided C++ solution defines... | magicoder | cpp |
You are tasked with implementing a function that recreates a transformation based on a given list of elementary transformations and a name. The elementary transformations are represented as a list of strings, where each string contains a single transformation. The transformations can be of two types: "rotate" or "mirro... | ```python
def recreate_transform(es, name):
transformation = ""
for e in es:
if e == "rotate":
transformation = rotate_90_degrees(transformation)
elif e == "mirror":
transformation = mirror_horizontally(transformation)
if name == "rotate":
transformation ... | magicoder | python |
You are given a code snippet that generates inputs and outputs for a time series data. Your task is to implement a function that calculates the mean squared error (MSE) between the inputs and outputs.
The code snippet provided uses the NumPy library to generate random binary inputs and then creates outputs by applying... | ```python
import numpy as np
def calculate_mse(inputs, outputs):
mse = np.mean((inputs - outputs) ** 2)
return mse
# Example usage
inputs = np.array([0, 1, 0, 1, 1])
outputs = np.array([0, 0, 0, 1, 0])
lag = 2
padded_outputs = np.array(lag * [0] + list(inputs))[:len(inputs)]
mse = calculate_mse(inputs, padded... | magicoder | python |
You are tasked with creating a Python class that simulates a simple game of darts. The game consists of players taking turns to throw darts at a dartboard and accumulating points based on where their darts land. The dartboard is divided into 20 sectors, each with a different point value. The game should keep track of e... | ```python
class DartsGame:
def __init__(self):
self.score = 501
def throw_dart(self, sector, multiplier):
if 1 <= sector <= 20 and multiplier in [1, 2, 3]:
points = sector * multiplier
if points <= self.score:
self.score -= points
def get_score(self)... | magicoder | python |
You are tasked with creating a script to automate the generation of multiple resized images from a given source image. The script should take the source image file path, a list of target sizes, and the destination directory as input, and then generate the resized images accordingly.
Write a function or script that tak... | ```python
import os
import subprocess
def resize_and_combine_images(source_image_path, target_sizes, destination_directory):
source_image_name = os.path.basename(source_image_path).split('.')[0]
# Resize the source image to each target size
resized_image_paths = []
for size in target_sizes:
... | magicoder | python |
You are tasked with creating a Python script that interacts with Google Drive using the PyDrive library. Your script should be able to download all files from a specified folder in Google Drive to a local directory. You will need to handle authentication using saved credentials and ensure that the downloaded files are ... | ```python
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
from oauth2client.client import OAuth2Credentials
import json
import sys
import os
FOLDER_NAME='TrialFolder'
PARENT_FOLDER='root'
DOWNLOAD_FOLDER='folderdownloads'
def load_saved_credentials():
with open('token.json','r') as cred_... | magicoder | python |
You are tasked with creating a Python function that processes a YAML configuration file to determine the absent roles and generate a report based on the provided data. The function should take the YAML data as input and return a dictionary containing the report.
The YAML data represents a list of roles that are absent... | ```python
import yaml
def process_yaml_data(yaml_data: dict) -> dict:
report = {'name': '',
'changes': {},
'result': True,
'comment': '',
'comments': []}
if 'roles' in yaml_data:
for role, values in yaml_data['roles'].items():
report[... | magicoder | python |
You are tasked with creating a program that simulates a simple contact management system. The system should allow users to add, remove, and search for contacts. Each contact will have a name, phone number, and email address. Your task is to implement the `ContactManager` class with the following functionalities:
1. `a... | ```swift
class ContactManager {
private var contacts: [String: (String, String)] = [:]
func addContact(name: String, phoneNumber: String, email: String) {
contacts[name] = (phoneNumber, email)
}
func removeContact(name: String) {
contacts.removeValue(forKey: name)
}
func searc... | magicoder | swift |
You are tasked with implementing a simple text-based game in Python. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player starts at position (0, 0) in a grid, and can move up, down, left, or right. The grid is represented by a 2D list where each cell... | ```python
from typing import List, Tuple
class GridGame:
def __init__(self, grid: List[List[str]]):
self.grid = grid
self.rows = len(grid)
self.cols = len(grid[0])
self.player_position = (0, 0)
self.treasures_collected = 0
self.total_treasures = sum(row.count('T') fo... | magicoder | python |
You are tasked with implementing a program to manage and store cultural names from various regions. The given code snippet is part of a larger program and is responsible for registering cultural names from a stream and storing them in appropriate data structures. The `registerRegex` function registers a regular express... | ```cpp
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <regex>
class CultureNames {
private:
std::vector<std::string> maleNames;
std::vector<std::string> surnames;
public:
CultureNames(std::istream& theStream) {
// Implement the constructor to initialize the cultura... | magicoder | cpp |
You are tasked with creating a Python class that models a web page visit tracker. The class should have the following attributes:
- `region`: a string representing the region from which the visit originated (optional, can be blank or null)
- `agent`: a string representing the user agent or browser information
- `page`:... | ```python
from django.db import models
from django.utils import timezone
class WebPageVisit(models.Model):
region = models.CharField(max_length=1000, blank=True, null=True)
agent = models.CharField(max_length=1000)
page = models.CharField(max_length=100)
referer = models.CharField(max_length=500, blank... | magicoder | python |
You are tasked with implementing a function to calculate the rotation angles of an object based on its transformation matrix. The transformation matrix is represented by a 4x4 matrix, and the rotation angles need to be calculated using the arcsine function. Your task is to write a function that takes the transformation... | ```java
import java.lang.Math;
class Matrix4f {
float m00, m01, m02, m03;
float m10, m11, m12, m13;
float m20, m21, m22, m23;
float m30, m31, m32, m33;
}
public class RotationCalculator {
public static float[] calculateRotationAngles(Matrix4f matrix) {
float rotX = (float) Math.asin(matrix... | magicoder | java |
You are tasked with implementing a custom attribute macro in Rust that validates the input of a struct field. The macro should check if the value of the field matches a specific constant and return a boolean value accordingly.
Your task is to create a macro called `validate_field` that takes two arguments: the field n... | ```rust
#[proc_macro_attribute]
pub fn validate_field(attr: TokenStream, item: TokenStream) -> TokenStream {
let field_name: Ident = parse_macro_input!(item as Field).ident;
let expected_value: LitStr = parse_macro_input!(attr as LitStr);
let gen = quote! {
impl MyStruct {
fn validate_#... | magicoder | rust |
You are tasked with implementing a Python decorator that ensures a function is executed in a separate thread using a thread pool executor. The decorator should handle the execution of the decorated function in a worker thread, ignoring the executor argument if called in a worker thread, and requiring the use of `await`... | ```python
import asyncio
import concurrent.futures
def executor(func):
def wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
if loop.is_running() and asyncio.current_task() is not None:
return func(*args, **kwargs)
else:
executor = kwargs.get('executor', None... | magicoder | python |
You are tasked with testing a Python script that involves the registration of multiple post-processing scripts. The script uses a custom framework for registering and executing these post-processing scripts. Your goal is to write unit tests to ensure that the registration of the post-processing scripts is functioning c... | ```python
import unittest
from unittest.mock import Mock, patch
def post_conf_load():
# Function to load post-processing configuration
pass
class TestPostProcessingRegistration(unittest.TestCase):
@patch('module_name.p_Script')
def test_post_conf_load_call_count(self, mock_p_script):
post_conf... | magicoder | python |
You are tasked with implementing a Python class that performs a specific mathematical operation. Your class should contain a method that takes an integer as input and returns the result of a mathematical function applied to that integer. The mathematical function is defined as follows:
\[ f(x) = 2x^2 + 3x - 5 \]
Your... | ```python
class MathOperation:
def f(self, x: int) -> int:
return 2*x**2 + 3*x - 5
```
The solution defines the `MathOperation` class with a method `f` that takes an integer `x` as input and returns the result of the mathematical function \( f(x) = 2x^2 + 3x - 5 \). The method correctly implements the math... | magicoder | python |
You are tasked with implementing a custom deformable convolution layer in PyTorch. Deformable convolutions are a type of convolutional layer that allows the network to learn the spatial sampling locations for each output feature map position, rather than using a regular grid. This can be useful for handling geometric t... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair, _single
import torchvision.ops as O
class DeformConv2d(nn.Module):
"""
A Custom Deformable Convolution layer that acts similarly to a regular Conv2d layer.
"""
def __init__(self, in_nc... | magicoder | python |
You are tasked with creating a C++ class hierarchy for a game loader system using the SFML library. The game loader system should support different platforms, and the provided code snippet shows the beginning of a WindowsGameLoader class derived from a DesktopGameLoader class.
Your task is to extend the class hierarch... | ```cpp
#include <iostream>
// Base class for game loader
class GameLoader {
public:
virtual void loadGame() = 0; // Pure virtual function
};
// GameLoader for Windows
class WindowsGameLoader : public GameLoader {
public:
void loadGame() override {
std::cout << "Loading game on Windows..." << std::end... | magicoder | cpp |
You are working on a software tool for parsing and manipulating mathematical optimization models. The tool uses an AMPLParser to process a given optimization problem and extract relevant information. The code snippet provided is a part of this tool and involves parsing meta entities and building sub-entities based on t... | ```python
from typing import List
class SubEntity:
def __init__(self, meta_entity_name: str, sub_entity_info: str):
self.meta_entity_name = meta_entity_name
self.sub_entity_info = sub_entity_info
def build_sub_entities(problem, meta_entity_names) -> List[SubEntity]:
ampl_parser = AMPLParser(pr... | magicoder | python |
You are tasked with implementing a method to calculate the area of a given polygon using the Shoelace formula. The Shoelace formula is a mathematical algorithm used to determine the area of a polygon given the coordinates of its vertices. The formula is based on the concept of calculating the area of a polygon by summi... | ```python
class Polygon:
"""
A polygon is a two-dimensional figure defined by a sequence of
a minimum of three ordered and non-coincident vertices
connected to form a closed polygonal chain.
"""
def calculate_area(self):
n = len(self.vertices)
area = 0
for i in range(n):... | magicoder | python |
You are working for a cloud computing company that provides database instances to its customers. Your task is to parse the information from a given string representing a database instance and extract relevant details for further processing.
The string representing a database instance has the following format:
```
# DB... | ```python
import re
def parse_db_instance_string(db_instance_str):
pattern = r'# DBINSTANCES (\d+) (\w+) (\S+) (\d+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\w+) (\S+) (\S+) (\w+)'
match = re.match(pattern, db_instance_str)
if match:
keys = ["Number of Instances", "Multi-AZ Deploymen... | magicoder | python |
You are tasked with simulating the behavior of a simple vending machine using object-oriented programming concepts. The vending machine has two states: "Locked" and "Unlocked". It can receive two types of inputs: "None" and "Coin". When in the "Locked" state, the vending machine can transition to the "Locked" state onl... | ```python
class VendingMachine:
def __init__(self):
self.state = "Locked"
def process_input(self, input_type):
if self.state == "Locked":
if input_type == "None":
self.state = "Locked"
elif input_type == "Coin":
self.state = "Unlocked"
... | magicoder | python |
You are tasked with implementing a Python decorator that adds revision information to a function. The decorator should take in revision details as arguments and update the function's metadata accordingly. The revision details include the revision number, branch labels, and dependencies.
Your task is to implement the `... | ```python
def add_revision(revision_number, branch_labels, depends_on):
def decorator_function(func):
func.revision_number = revision_number
func.branch_labels = branch_labels
func.depends_on = depends_on
return func
return decorator_function
@add_revision(revision_number=1, bra... | magicoder | python |
You are tasked with implementing a file manipulation utility in Rust. The utility should be able to perform operations on both single files and entire directories. The code snippet provided is a part of the utility's main functionality. The `run` function takes a `Config` struct as an argument and matches the `config.o... | ```rust
// Define the Operation enum
enum Operation {
SingleFile,
Directory,
}
// Define the Config struct
struct Config {
operation: Operation,
path: String,
}
// Implement the run function
fn run(config: Config) {
match config.operation {
Operation::SingleFile => split_file(config.path),... | magicoder | rust |
You are tasked with creating a social networking application that includes a feature for managing follow requests between users. The application has an `FollowRequestsInteractor` class responsible for handling follow requests. The class has dependencies on `listProcessor` and `socialService`, which are interfaces for p... | ```swift
class FollowRequestsInteractor {
private let listProcessor: UsersListProcessor
private let socialService: SocialService
var output: FollowRequestsInteractorOutput?
init(listProcessor: UsersListProcessor, socialService: SocialService) {
self.listProcessor = listProcessor
self.so... | magicoder | swift |
You are tasked with implementing a class that manages an entity storage system. The class should provide methods to erase entities based on their IDs and to flush the erase queue.
You need to implement a class called `EntityStorage` that has the following methods:
1. `void erase_equal_range(IdT entity)`: A virtual met... | ```cpp
#include <iostream>
#include <unordered_map>
#include <queue>
// Define the type for entity ID
using IdT = int;
// Define the EntityStorage class
class EntityStorage {
public:
virtual void erase_equal_range(IdT entity) = 0;
virtual void flush_erase_queue() = 0;
};
// Derived class implementing the Ent... | magicoder | cpp |
You are given a code snippet that contains file paths and numerical values related to image processing. Your task is to write a Python function that processes the given image files and extracts patches based on the provided stride value.
You need to implement a function `extract_patches` that takes in the following pa... | ```python
import os
import cv2
def extract_patches(img_folder, gt_folder, class_number, stride):
# Create class folders in the ground truth folder
for i in range(class_number):
class_folder = os.path.join(gt_folder, f'class_{i}')
os.makedirs(class_folder, exist_ok=True)
# Read image files ... | magicoder | python |
You are tasked with implementing a custom PHP class that extends a base model and interacts with a WeChat application. The class should be able to handle various operations related to the WeChat application, such as sending messages, retrieving user information, and managing access tokens. Your task is to complete the ... | The provided solution includes the implementation of the `BaseClient` class with the required methods to interact with the WeChat application. The class extends the `Model` class and has a protected property `$app` of type `Application` to hold the instance of the WeChat application. The constructor initializes the `$a... | magicoder | php |
You are working on a security project and need to crack a hashed password using the hashcat tool. The hashcat tool is a popular password recovery tool that utilizes the power of the GPU to crack passwords. The command-line snippet provided is an example of using hashcat to crack a hashed password.
The command-line sni... | ```python
import subprocess
def crack_password(hashed_password_file: str, wordlist_file: str, hash_type: int) -> str:
command = f"./hashcat -a 0 -m {hash_type} {hashed_password_file} {wordlist_file} -O -o key.txt --status"
subprocess.run(command, shell=True)
with open("key.txt", "r") as file:
... | magicoder | python |
You are tasked with creating a shell script that processes a given directory structure and performs specific operations on the files and subdirectories within it. Your script should accomplish the following tasks:
1. Create a new directory named "data" within the current working directory.
2. Traverse through the cont... | ```bash
#!/bin/bash
# Create a new directory named "data" within the current working directory
mkdir -p data
# Traverse through the contents of the current directory and process ".txt" files
for file in *.txt; do
# Extract unique words from each ".txt" file and store them in "words.txt" within the "data" director... | magicoder | shell |
You are tasked with creating a Python function to calculate the sum of even-valued terms in the Fibonacci sequence up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first few terms of the Fibonacc... | ```python
def fib_even_sum(limit):
sum_even = 0
a, b = 0, 1
while b <= limit:
if b % 2 == 0:
sum_even += b
a, b = b, a + b
return sum_even
```
The `fib_even_sum` function initializes `sum_even` to 0 and sets `a` and `b` to 0 and 1, respectively, representing the first two te... | magicoder | python |
You are tasked with implementing a method to convert a given input stream into an enumerable collection of byte arrays. The method should take the input stream and a block size as parameters and return an enumerable collection of byte arrays, each containing the specified block size of data from the input stream. If th... | ```csharp
using System;
using System.Collections.Generic;
using System.IO;
public static class StreamExtensions
{
public static IEnumerable<byte[]> ToEnumerable(this Stream stream, int blockSize)
{
if (stream == null)
{
yield break; // Return an empty enumerable collection if the in... | magicoder | csharp |
You are tasked with implementing a virtual machine (VM) that executes a sequence of instructions to match a regular expression pattern against a given input string. The provided code snippet gives a glimpse of the VM implementation in Rust, where the `run_vm` function is responsible for running the VM to match the regu... | ```rust
// Define the instruction set for the virtual machine
enum Inst {
// Define different types of instructions
// Example:
// Char(char), // Match a specific character
// Any, // Match any character
// Split(usize, usize),// Split the execution path
// Jump(usize), ... | magicoder | rust |
You are given a Python code snippet that generates a string of length 5000 consisting of random binary digits (0s and 1s). Your task is to write a function that takes this string as input and returns the count of the longest consecutive sequence of 1s in the string.
For example, if the input string is "001110111100011... | ```python
def longest_consecutive_ones(s: str) -> int:
max_count = 0
current_count = 0
for char in s:
if char == '1':
current_count += 1
max_count = max(max_count, current_count)
else:
current_count = 0
return max_count
```
The `longest_consecutive_... | magicoder | python |
You are tasked with creating a program that can detect and count the number of characters present in a given image. The program should utilize the OpenCV library for image processing and character detection. The image is captured from a video feed using a camera, and the character detection algorithm should be implemen... | To solve this problem, you can use the following approach:
```python
import cv2
# Function to detect and count characters in the image
def detect_and_count_characters(image):
# Implement character detection algorithm using OpenCV
# For example, you can use OCR (Optical Character Recognition) techniques or cus... | magicoder | python |
You are given a 3D array `in_out` representing a volume, and a 3D array `labels` representing the segmentation labels for the objects in the volume. The goal is to write a function that counts the number of voxels for each object in the segmentation, excluding the object with label `label_corner`. The function should r... | ```python
import numpy as np
def count_voxels_per_object(in_out, labels, label_corner):
voxel_counts = {}
unique_labels = np.unique(labels)
for obj_num in unique_labels:
if obj_num == label_corner:
continue
voxel_counts[obj_num] = np.sum(labels == obj_num)
return voxel_count... | magicoder | python |
You are tasked with creating a program that securely stores and retrieves a user's Rally password. The program should prompt the user to input their password and then store it securely. Additionally, the program should provide a way to retrieve the stored password when needed. To achieve this, you need to implement a c... | ```java
import java.util.Scanner;
public class PasswordManager {
private String storedPassword;
public void setPassword(String password) {
// Securely store the password (e.g., using encryption or other secure methods)
this.storedPassword = password;
}
public String getPassword() {
... | magicoder | java |
You are tasked with creating a program to manage a library system. The library contains books, each of which has a unique identifier, title, author, and availability status. The program should allow users to perform various operations such as adding new books, borrowing books, returning books, and displaying the availa... | ```python
class Book:
def __init__(self, book_id, title, author):
self.book_id = book_id
self.title = title
self.author = author
self.availability = True
class Library:
def __init__(self):
self.books = []
def add_book(self, book_id, title, author):
new_book ... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.