query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a feature detection algorithm for image processing. The algorithm takes an input image and identifies specific features within it. The detected features are then stored in a pandas DataFrame, and the algorithm also generates an output image with the detected features highlighted.
Your ... | ```python
import pandas as pd
import numpy as np
import cv2
def detect_features(input_image):
"""
Detects features in the input image and returns the detected features and the output image.
Args:
input_image (2D array): The input image for feature detection.
Returns:
features (pandas DataFram... | magicoder | python |
You are tasked with creating a simple routing system for a web application. The routing system should be able to match incoming URLs to specific handlers and execute the corresponding code. To achieve this, you need to implement a basic routing table and a function to match incoming URLs to the appropriate handler.
Yo... | ```rust
// routes_test.rs
use std::collections::HashMap;
type Handler = fn(&str);
struct Router {
routes: HashMap<String, Handler>,
}
impl Router {
fn new() -> Router {
Router {
routes: HashMap::new(),
}
}
fn register_route(&mut self, url_pattern: &str, handler_function:... | magicoder | rust |
You are tasked with creating a Python program that simulates a DNS server using the `scapy` and `dnslib` libraries. Your program should listen for DNS queries on port 53 and respond with a fixed IP address for any domain name. Additionally, the program should also include an HTTP server that can handle incoming HTTP re... | ```python
import json
from scapy.all import *
from scapy.layers.l2 import *
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
from dnslib.server import DNSLogger, DNSServer
from dnslib.fixedresolver import FixedResolver
class FixedDNSResolver(FixedResolver):
def resolve(self, reques... | magicoder | python |
You are tasked with implementing a state machine for a traffic light system. The traffic light can be in one of three states: INACTIVE, ACTIVE, or YELLOW. The traffic light transitions between these states based on certain conditions. Your goal is to implement the logic for transitioning between these states based on t... | ```java
public class TrafficLight {
private StatePhase _currentPhase;
public void start() {
// Assuming durations for state transitions are defined as constants
while (true) {
switch (_currentPhase) {
case INACTIVE:
// Transition to ACTIVE after s... | magicoder | java |
You are tasked with creating a function that calculates the padding required for a convolutional neural network (CNN) given the kernel size, strides, and dilation rate. The function should handle input for 1D, 2D, or 3D convolutions. The padding calculation is based on the formula:
\[ p = (k - s) \times d \]
where \( ... | ```python
import numpy as np
def get_same_padding(kernel_size, strides, dilation_rate, n_dims=2):
p = []
for i in range(n_dims):
if strides[i] > 1 and dilation_rate[i] > 1:
raise ValueError("Can't have the stride and dilation rate over 1")
padding = (kernel_size[i] - strides[i]) * d... | magicoder | python |
You are given an array of integers `a[]` of length `n`. Your task is to find the minimum absolute difference between any two elements in the array.
Write a function `minAbsDifference` that takes in the array `a[]` and its length `n` as input and returns the minimum absolute difference.
Function signature:
```java
pu... | ```java
public static int minAbsDifference(int[] a, int n) {
Arrays.sort(a); // Sort the array in non-decreasing order
int minDiff = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
int diff = Math.abs(a[i] - a[i - 1]);
if (diff < minDiff) {
minDiff = diff;
}
}
re... | magicoder | java |
You are tasked with implementing a Swift structure to manage asynchronous network requests. The structure should include a cancellation token, a dispatch queue, and a context object. Your goal is to create a `NetworkRequest` structure with the following properties:
- `cancellationToken`: A token used to make a best-ef... | ```swift
import Foundation
/// A token used to make a best-effort attempt at canceling a request.
public struct CancellationToken {
// Implementation details for CancellationToken
}
/// A context object to associate with the request.
public struct PipelineContext {
// Implementation details for PipelineContex... | magicoder | swift |
You are tasked with implementing a simple error handling mechanism for a service in a programming language that supports custom error types. The service has a function that can potentially produce errors, and you need to define the custom error type and handle the errors appropriately.
Your task is to create a custom ... | ```python
# Define the custom error type
class ServiceError(Exception):
pass
class ConnectionError(ServiceError):
pass
class DataError(ServiceError):
pass
# Implement the Service class with the fetchData method
class Service:
def fetchData(self):
# Simulate a connection error
# Uncomm... | magicoder | python |
You are tasked with implementing a simple iOS app feature that involves a `UIPickerView`. The `UIPickerView` is a standard iOS control that allows users to make selections from a list of options presented in a dropdown-like interface. The provided code snippet is a part of the implementation for this feature.
The `UIP... | ```swift
class HeroPickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let heroes = ["Superman", "Batman", "Wonder Woman", "Spider-Man", "Iron Man"]
// MARK: - UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
retur... | magicoder | swift |
You are tasked with implementing a custom authorization attribute in a C# ASP.NET Core application. The attribute should restrict access to a specific action method based on the presence of certain user scopes. Additionally, the action method should set a ViewData value based on a configuration setting.
Your task is t... | ```csharp
// Define a custom authorization attribute to restrict access based on user scopes
public class AuthorizeForScopesAttribute : TypeFilterAttribute
{
public AuthorizeForScopesAttribute(string[] scopes) : base(typeof(AuthorizeForScopesFilter))
{
Arguments = new object[] { scopes };
}
}
// Im... | magicoder | csharp |
You are tasked with creating a script to automate the deployment process for a Jekyll-based website. Jekyll is a popular static site generator that is often used for blogs and other content-heavy websites. The provided code snippet is a part of a deployment script that needs to be completed.
The script is intended to ... | ```bash
#!/bin/bash
# Set the dir variable to the absolute path of the current directory
dir=$(cd "${dir}" || exit 1; pwd)
# Set the HOME variable to the absolute path of the parent directory of dir
HOME=$(cd "${dir}/.." || exit 1; pwd)
# Change the working directory to HOME
cd "${HOME}" || exit 1
# If a directory ... | magicoder | shell |
You are tasked with creating a program that simulates a simple file management system. The program should allow users to perform basic file operations such as creating, deleting, and navigating through directories. Additionally, the program should provide a feature to run an executable file with elevated privileges.
Y... | ```csharp
using System;
using System.Diagnostics;
using System.IO;
public class FileManager
{
public void CreateDirectory(string directoryName)
{
string path = Path.Combine(Environment.CurrentDirectory, directoryName);
if (!Directory.Exists(path))
{
Directory.CreateDirectory... | magicoder | csharp |
You are tasked with implementing a set data structure using a linked list. The set should support the following operations:
1. `add(element)`: Add the specified element to the set if it is not already present.
2. `remove(element)`: Remove the specified element from the set if it is present.
3. `contains(element)`: Chec... | ```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Set:
def __init__(self):
self.head = None
def add(self, element):
if not self.contains(element):
new_node = Node(element)
new_node.next = self.head
se... | magicoder | python |
You are tasked with implementing a CPU emulator for a simplified 8-bit computer architecture. The CPU has a set of operations, each associated with a specific opcode and clock cycle count. Your goal is to implement the `add_bc_op` function, which adds a new operation to the CPU's instruction set.
The `add_bc_op` funct... | ```cpp
#include <iostream>
#include <map>
#include <functional>
// Define the CPU class
class Cpu {
public:
unsigned char m_a; // Example member variable
};
// Define the clock_t type
using clock_t = int;
// Define the add_bc_op function to add a new operation to the CPU's instruction set
void add_bc_op(unsigne... | magicoder | cpp |
You are tasked with creating a program to manage DHCP options for a network configuration tool. The program should handle the creation, update, and deletion of DHCP options based on user input. The user can specify whether to delete or purge DHCP options, and whether to create, update, or delete options. Additionally, ... | ```python
def manage_dhcp_options(delete_dhcp_options, purge_dhcp_options, state):
if delete_dhcp_options and purge_dhcp_options:
return "Error: delete_dhcp_options and purge_dhcp_options are mutually exclusive."
if state not in ['create', 'update', 'delete']:
return "Error: Invalid state. Stat... | magicoder | python |
You are tasked with implementing a TypeScript function that can parse a given file and extract the copyright information from it. The copyright information is typically located at the beginning of the file as a comment block and includes the copyright symbol, year, and license information.
Your task is to write a Type... | ```typescript
import * as fs from 'fs';
interface CopyrightInfo {
copyrightSymbol: string;
year: string;
license: string;
}
function extractCopyright(filePath: string): CopyrightInfo {
const fileContent = fs.readFileSync(filePath, 'utf8');
const regex = /Copyright \(c\) (\d{4}) .+?This software is released ... | magicoder | typescript |
You are given a string `s` and a pattern `p` that may contain the wildcard character '*'. The '*' can match any sequence of characters (including the empty sequence). Implement a function `isMatch` to determine if the pattern matches the entire string.
Function Signature:
```cpp
bool isMatch(string s, string p)
```
... | ```cpp
bool isMatch(string s, string p) {
int m = s.length(), n = p.length();
bool dp[m + 1][n + 1];
memset(dp, false, sizeof(dp));
dp[0][0] = true;
for (int j = 1; j <= n; j++) {
if (p[j - 1] == '*') {
dp[0][j] = dp[0][j - 1];
}
}
for (int i = 1; i <= m; i++) {... | magicoder | cpp |
You are tasked with implementing a context management system in Swift. The system should allow for the creation of a context, union of contexts, and retrieval of values from the context.
You are provided with the following code snippet as a starting point:
```swift
/// Creates a union between `self` and `val`, where ... | ```swift
// Define the JarContextValue protocol
protocol JarContextValue {}
// Implement the formUnion method for the Jar.Context type
extension Jar.Context {
mutating func formUnion(_ other: Jar.Context) {
for (key, value) in other.vals {
self.vals[key] = value
}
}
}
// Implement ... | magicoder | swift |
You are tasked with creating a Java class that utilizes the RestAssured library to perform HTTP requests and handle responses. Your class should include methods to send GET and POST requests to a specified URL and handle the responses appropriately. Additionally, you need to implement error handling for potential excep... | ```java
package com.wiley.http;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class HttpService {
public Response sendGetRequest(String url) {
try {
return RestAssured.get(url);
} catch (Exc... | magicoder | java |
You are working on a security system that requires encoding data using a custom algorithm. The `encode` function takes three parameters `p1`, `p2`, and `p3` and returns an encoded result. The encoding process involves bitwise operations and arithmetic calculations.
The `encode` function is defined as follows:
```pytho... | ```python
def decode(encoded_result):
p3 = ((encoded_result >> 8) & 0xffff) ^ ((encoded_result >> 8) & 0xfff0)
p2 = ((encoded_result & 0xff) ^ ((encoded_result >> 4) & 0xfff0)) & 0xffffffff
p1 = chr(((encoded_result & 0xff) - 1) ^ ((encoded_result >> 4) & 0xff))
return p1, p2, p3
```
The `decode` func... | magicoder | python |
You are tasked with creating a Python function that evaluates the performance of a set of models on a dataset. The function takes in a folder containing subfolders, each representing a different dataset, and a set of options for evaluation. The function iterates through each subfolder, performs evaluation on the datase... | ```python
import glob
import subprocess
def eval_all(this_folder, this_options, out):
for folder in glob.glob(this_folder + '/*'):
subprocess.check_output(["gunzip", "-r", folder])
values = eval_folder_lemma(folder, this_options['prefix_models'], this_options['min_ocs'])
if values is not N... | magicoder | python |
You are tasked with implementing a DNS packet builder function for a mock DNS library. The function should take raw DNS data and an IP address as input and construct a DNS packet with the appropriate format.
The DNS packet format is as follows:
- The first 12 bytes represent the DNS header.
- The remaining bytes repre... | ```python
import unittest
from mockdock import dns
class DNSTest(unittest.TestCase):
def test_build_packet(self):
data = b"^4\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06google\x03com\x00\x00\x01\x00\x01"
packet = dns.build_packet(data, "192.168.0.1")
expected_result = b"^4\x81\x80\x00\x01\... | magicoder | python |
You are tasked with creating a Python program to manage a simple inventory system for a small business. The program should allow users to add, remove, and update items in the inventory, as well as display the current inventory status.
Your program should include a class `Inventory` with the following methods:
- `__ini... | ```python
class Inventory:
def __init__(self):
self.inventory = {}
def add_item(self, item_name, quantity):
if item_name in self.inventory:
self.inventory[item_name] += quantity
else:
self.inventory[item_name] = quantity
def remove_item(self, item_name, quan... | magicoder | python |
You are tasked with implementing a function to manage a list of problems in a software system. The function should allow adding, retrieving, and resetting problems in the list. The code snippet provided gives a glimpse of the operations involved in this task.
You are given the following information:
- The function `se... | ```cpp
#include <string>
#include <unordered_map>
#include <memory>
// Define a class to manage problems
class ProblemManager {
private:
std::string name; // Variable to store the name
// Define a structure to represent a problem
struct Problem {
// Define the properties of a problem
// .... | magicoder | cpp |
You are working on a web application that utilizes various modules for different functionalities. The code snippet provided includes imports for modules related to counters, progress tracking, internationalization, and streams. Additionally, it defines two variables, `withDefault` and `orEmpty`, which are used for hand... | ```javascript
function getLocalizedProgressMessage(progressPercentage, progressStatus, languageCode) {
var progressMessage = tdliteProgress.getProgressMessage(progressStatus);
var localizedMessage = tdliteI18N.translate(progressMessage, languageCode);
var formattedMessage = `${progressPercentage}% - ${localizedMe... | magicoder | javascript |
You are working on a medical imaging project and need to implement a function to warp images based on given transformation points. The code snippet provided is a part of the image warping process. The `_warp_images` function takes several parameters, including `from_points`, `to_points`, `image`, `output_region`, `inte... | ```python
def _warp_images(from_points, to_points, image, output_region, interpolation_order, approximate_grid):
x_start, y_start, z_start, x_end, y_end, z_end = output_region
warped_image = np.zeros((x_end - x_start, y_end - y_start, z_end - z_start))
for x in range(x_start, x_end):
for y in range... | magicoder | python |
You are tasked with creating a function to distribute parts of a table to different servers while ensuring that the part sizes are balanced. Each part of the table is represented by a list of files, and the goal is to distribute these parts across two servers in a balanced manner based on file sizes.
You are given the... | ```python
from typing import List
class SnapshotFile:
def __init__(self, file_size: int):
self.file_size = file_size
def create_part_from_part_files(part_files: List[SnapshotFile]) -> List[SnapshotFile]:
return part_files
def distribute_parts_to_servers(parts: List[List[SnapshotFile]], server_files: ... | magicoder | python |
You are given an integer `n`, and you need to reverse the bits of this number. For example, if the input is `43261596`, which is `00000010100101000001111010011100` in binary, the output should be `964176192`, which is `00111001011110000010100101000000` in binary.
Write a function `reverseBits` to achieve this.
The fu... | ```python
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return result
```
The `reverseBits` function initializes `result` to 0. It then iterates th... | magicoder | python |
You are tasked with implementing a program that reads a series of file names from the command line and processes each file to build an integer vector. The program uses the Succinct Data Structure Library (SDSL) to create an integer vector of 8-bit integers from the contents of each file. Your task is to write a functio... | ```cpp
#include <iostream>
#include <sdsl/int_vector.hpp>
#include <fstream>
size_t processFiles(int argc, char* argv[]) {
size_t totalSize = 0;
for(int i = optind; i < argc; i++) {
std::string base_name = argv[i];
std::cout << "File: " << base_name << std::endl;
sdsl::int_vector<8> text;
sdsl::cac... | magicoder | cpp |
You are tasked with creating a Python function that calculates the gradient of a given mathematical function with respect to a tensor using PyTorch. PyTorch is a popular open-source machine learning library for Python that provides support for automatic differentiation and gradient computation.
Your task is to complet... | ```python
import torch
def calculate_gradient(function, tensor_values):
# Create a new tensor y by applying the given function to the input tensor
y = function(tensor_values)
# Use PyTorch's automatic differentiation to calculate the gradient of y with respect to the input tensor
y.backward()
... | magicoder | python |
You are tasked with implementing a class that represents a Mercator space and provides methods for working with geographical locations. The Mercator space is defined by its height, minimum and maximum coordinates, and a center point. Your goal is to create a class that encapsulates this information and provides functio... | ```csharp
public class MercatorSpace
{
public static readonly double Height;
public static readonly MercatorLocation Min;
public static readonly MercatorLocation Max;
public static readonly MercatorLocation Center;
static MercatorSpace()
{
// Initialize the properties with appropriate v... | magicoder | csharp |
You are tasked with implementing a dependency injection system for a simple web application. The application has a set of services that need to be provided to various components. Each service has its own dependencies, and the goal is to ensure that the dependencies are resolved and injected correctly.
Given the follow... | ```typescript
class DependencyInjector {
private serviceRegistry: Map<any, any>;
private resolvedServices: Map<any, any>;
constructor() {
this.serviceRegistry = new Map();
this.resolvedServices = new Map();
}
registerService(service: any, dependencies: any[]) {
this.serviceRegistry.set(service, ... | magicoder | typescript |
You are given a function `expressive_words` that takes a string `s` and a vector of strings `words`. The function is designed to determine the number of words in the `words` vector that can be formed from the string `s` by extending some characters. The extension of characters in a word is considered valid if it follow... | ```rust
fn expressive_words(s: String, words: Vec<String>) -> i32 {
fn is_expressive(s: &str, word: &str) -> bool {
let (mut i, mut j) = (0, 0);
let (n, m) = (s.len(), word.len());
let s: Vec<char> = s.chars().collect();
let word: Vec<char> = word.chars().collect();
while i ... | magicoder | rust |
You are tasked with implementing a custom `FloatNdArray` class that extends the `NdArray` class and provides various methods for handling multidimensional arrays of floating-point numbers. The provided code snippet outlines some of the methods that need to be implemented or overridden in the `FloatNdArray` class. Your ... | ```java
public class FloatNdArray extends NdArray<Float> {
@Override
NdArraySequence<FloatNdArray> elements(int dimensionIdx) {
// Implement logic to return an NdArraySequence containing elements of type FloatNdArray for the specified dimension index
// Your implementation here
}
@Over... | magicoder | java |
You are tasked with implementing a simplified instruction cycle for a hypothetical processor. The processor executes a series of instructions in a loop, and each instruction involves fetching data from memory. Your task is to write a function that simulates this instruction cycle by fetching data from memory and proces... | ```python
from typing import List
def instruction_cycle(memory: List[int]) -> List[int]:
running = True # Assume the instruction cycle is initially running
while running:
# Fetch
for i in range(len(memory)):
fetched_value = memory[i]
processed_value = fetched_value + 1 ... | magicoder | python |
You are working on a data processing task for a psychology experiment. The task involves processing a DataFrame containing information about stimuli used in the experiment. Each row of the DataFrame represents a trial, and the columns contain various details about the stimuli presented during the trial.
The code snipp... | ```python
import re
# Extract category and name of the stimuli from 'stim_file' and populate 'stim_category' and 'stim_name' columns
for k in range(len(ret)):
ret.loc[k, 'trial_number'] = k+1
stimInfo = ret.loc[k, 'stim_file']
ret.loc[k, 'stim_category'] = re.findall('(.+?)_', stimInfo)[0]
ret.loc[k, '... | magicoder | python |
You are tasked with creating a Python package version checker. Your program should take a package name and a version number as input and determine if the provided version number is the latest available for the given package. The package information will be retrieved from an external API.
You are provided with the foll... | ```python
import requests
def is_latest_version(package_name, version_number):
try:
response = requests.get(f"https://api.example.com/package_info/{package_name}")
response.raise_for_status() # Raise an exception for 4xx/5xx status codes
package_info = response.json()
latest_versio... | magicoder | python |
You are tasked with implementing a class to simulate a simple ecosystem with a population of rabbits and foxes. The ecosystem will be represented by a Python class called `Ecosystem`. The class will have the following functionalities:
1. `initialize_population(rabbit_count, fox_count)`: A method to initialize the popu... | ```python
import matplotlib.pyplot as plt
class Ecosystem:
def __init__(self):
self.rabbit_population = 0
self.fox_population = 0
self.years = 0
self.rabbit_population_log = []
self.fox_population_log = []
def initialize_population(self, rabbit_count, fox_count):
... | magicoder | python |
You are working on a machine learning project and need to implement a custom oversampling technique for handling imbalanced datasets. The goal is to create a function that takes in the input features `x`, the corresponding target labels `y`, a classifier `clsf`, and performs the following steps:
1. Vectorize the input ... | ```python
def custom_oversampling(x, y, model, clsf) -> Any:
vectorized_x = model.fit_transform(x, y)
return fit(vectorized_x, y, clsf, oversample=True)
```
In the solution, the `custom_oversampling` function takes the input features `x`, target labels `y`, vectorization model `model`, and classifier `clsf`. It... | magicoder | python |
You are tasked with implementing a function that sets up a renderer for a game based on the capabilities of the device. The function should check if the device is capable of using the requested renderer and set it up, or choose an alternative if the device is not capable.
You are given the following TypeScript functio... | ```typescript
import { Game, RendererType, Renderer } from 'phaser'; // Assuming the necessary imports
export default function setUpRenderer(game: Game): void {
const deviceCapabilities = getDeviceCapabilities(); // Assume a function to retrieve device capabilities
if (deviceCapabilities.supports(game.renderer)) ... | magicoder | typescript |
You are tasked with implementing a Python function that simplifies a given string representing a name. The simplification process involves resolving camel case, removing leading and trailing whitespaces, and replacing any remaining spaces with underscores. You are provided with a code snippet that includes a function `... | ```python
def resolve_camel_case(name):
resolved_name = ""
for i, char in enumerate(name):
if i > 0 and char.isupper():
resolved_name += " " + char
else:
resolved_name += char
return resolved_name
```
The `resolve_camel_case(name)` function iterates through each chara... | magicoder | python |
You are tasked with implementing a thread-safe queue data structure in C++ using Win32 synchronization primitives. The queue should support the following operations:
1. `void Enqueue(int value)`: Add an integer value to the end of the queue.
2. `int Dequeue()`: Remove and return the integer value at the front of the qu... | ```cpp
#include <windows.h>
#include <queue>
class ThreadSafeQueue {
private:
CRITICAL_SECTION _cs;
std::queue<int> _queue;
public:
ThreadSafeQueue() {
InitializeCriticalSection(&_cs);
}
~ThreadSafeQueue() {
DeleteCriticalSection(&_cs);
}
void Enqueue(int value) {
... | magicoder | cpp |
You are tasked with implementing a custom hashing algorithm for a network communication protocol. The provided code snippet is a part of the hashing function used to generate a unique identifier for a network connection. The function takes various parameters and performs a series of operations to produce the final hash... | ```rust
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::num::Wrapping;
struct ConnectionId {
remote: RemoteInfo,
local: LocalInfo,
}
struct RemoteInfo {
address: u32,
port: u16,
}
struct LocalInfo {
address: u32,
port: u16,
}
struct ConnectionHasher {
... | magicoder | rust |
You are given a chessboard represented as an 8x8 grid. Each cell on the board can be either empty (denoted by ".") or occupied by a chess piece (denoted by "Q" for a queen). Your task is to write a function that takes the row and column indices of a queen on the board and returns the count of empty cells that the queen... | ```python
from typing import List
def count_attacked_cells(board: List[List[str]], r_ind: int, c_ind: int) -> int:
count = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
for dr, dc in directions:
cur_r, cur_c = r_ind, c_ind
while 0 <= cur_r + dr < 8 a... | magicoder | python |
You are tasked with creating a test case for a Laravel application's `Store` method. The `Store` method is responsible for creating a new record in the database, and the test case should ensure that the method behaves as expected. The test case is written in PHP using Laravel's testing framework.
The test case involve... | ```php
public function testStoreSuccess()
{
// Create a new user (cashier) and a new customer using Laravel's factory methods
$cashier = factory(User::class)->create();
$customer = factory(Customer::class)->create();
// Make a POST request to the 'store' endpoint with the necessary data
$response =... | magicoder | php |
You are tasked with creating a Python function that simulates a simple game of dice. The game involves rolling two dice and summing the values that appear on the faces. The function should take an integer `n` as input and simulate rolling the dice `n` times. It should then return a dictionary containing the frequency o... | ```python
import numpy as np
def simulate_dice_rolls(n: int) -> dict:
results = np.random.randint(1, 7, size=(n, 2)) # Simulate rolling two dice n times
sums = np.sum(results, axis=1) # Calculate the sum of each pair of dice
frequency = {i: np.sum(sums == i) for i in range(2, 13)} # Count the frequency ... | magicoder | python |
You are tasked with implementing a Python function that processes a list of strings representing Python code and identifies any incomplete function definitions. An incomplete function definition is identified by an opening parenthesis '(', followed by a function name, and ending with a colon ':' on a separate line. You... | ```python
from typing import List, Tuple
def find_incomplete_functions(code_lines: List[str]) -> List[Tuple[int, str]]:
incomplete_functions = []
for i, line in enumerate(code_lines):
if line.strip().startswith("def ") and line.strip().endswith("("):
function_name = line.strip().split("(")[... | magicoder | python |
You are tasked with implementing a simple menu system for a command-line application. The menu should allow the user to select options and perform corresponding actions. The menu system should be designed using object-oriented programming principles.
Your task is to create a Python class called `Menu` that provides th... | ```python
class Menu:
def __init__(self):
self.options = {}
def add_option(self, description, action):
option_number = len(self.options) + 1
self.options[option_number] = (description, action)
def display_menu(self):
for option_number, (description, _) in self.options.items... | magicoder | python |
You are tasked with creating a modular synthesizer software that simulates various audio effects. One of the modules you need to implement is a wavefolder, which is a non-linear audio effect that folds the waveform when it exceeds a certain threshold. Additionally, you need to create a metallic noise generator module t... | ```cpp
// Implementation of the SharpWavefolder class
class SharpWavefolder {
public:
// Process audio signal by folding the waveform
float process(float input, float threshold) {
if (input > threshold) {
return 2 * threshold - input;
} else if (input < -threshold) {
retu... | magicoder | cpp |
You are tasked with implementing a Python class that serves as a base augmenter for image processing. The class should provide methods for applying various image augmentation techniques commonly used in computer vision tasks. Your task is to complete the implementation of the `BaseAugmenter` class by adding methods for... | ```python
class BaseAugmenter:
def rotate_image(self, image, angle):
# Implement image rotation logic using a suitable library like OpenCV or PIL
# Example using PIL:
from PIL import Image
import numpy as np
img = Image.fromarray(image)
rotated_img = img.rotate(angle... | magicoder | python |
You are tasked with implementing a function that handles protected execution of user-defined code. The provided code snippet includes a static variable `CURRENT_EXECUTABLE_BUFFER` and a function `call_protected` that takes various parameters. Your task is to create a Rust function that traps errors early and handles us... | ```rust
fn handle_protected_execution(
handler_data: &HandlerData,
trampoline: Trampoline,
ctx: *mut Ctx,
func: *const Func,
param_vec: *const u64,
return_vec: *mut u64,
) -> RuntimeResult<()> {
if CURRENT_EXECUTABLE_BUFFER.get() == ptr::null() {
return Err("CURRENT_EXECUTABLE_BUFFER... | magicoder | rust |
You are working on a project that involves converting TensorFlow models to Core ML models for use in an iOS application. Core ML is a framework developed by Apple that allows integration of machine learning models into iOS apps. You have been given the task of converting multiple TensorFlow models to Core ML models and... | ```python
import coremltools as ct
def convert_and_save_models(tf_model_paths, dimensions):
saved_mlmodel_paths = []
for i in range(len(tf_model_paths)):
tf_model_path = tf_model_paths[i]
height, width = dimensions[i]
mlmodel = ct.convert(tf_model_path, source='tensorflow')
save... | magicoder | python |
You are tasked with implementing a custom property wrapper in Swift that provides a way to store and retrieve repeated values of different types. The property wrapper should support storing and retrieving repeated values of Protobuf messages, nested enums, and foreign enums.
Your task is to create a custom property wr... | ```swift
// Define the RepeatedValue property wrapper
@propertyWrapper
struct RepeatedValue<T> {
private var storage: [T] = []
var wrappedValue: [T] {
get { return storage }
set { storage = newValue }
}
}
// Define the ProtobufUnittest_TestAllTypes message
struct ProtobufUnittest_TestAllTy... | magicoder | swift |
You are tasked with implementing a program to calculate the total number of lines of code in a given set of C++ source files. The program should read the source files, count the lines of code (excluding empty lines and comments), and then output the total number of lines.
Your program should consider the following rul... | ```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <regex>
// Function to count lines of code in a file
int countLinesOfCode(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error opening file: " << filename << std... | magicoder | cpp |
You are tasked with implementing a custom learning rate scheduler for a deep learning model training process. The learning rate scheduler should adjust the learning rate during training based on a predefined schedule. The training process involves using a MobileUNet model to perform semantic segmentation on a dataset o... | ```python
# learning_rate.py
def create_lr_schedule(initial_lr, warmup_epochs, decay_rate):
def lr_schedule(epoch):
if epoch < warmup_epochs:
return initial_lr * (epoch + 1) / warmup_epochs
else:
return initial_lr * decay_rate ** (epoch - warmup_epochs)
return lr_schedul... | magicoder | python |
You are tasked with creating a Python function that generates a radar chart for a given set of data. A radar chart, also known as a spider or star chart, is a graphical method of displaying multivariate data in the form of a two-dimensional chart of three or more quantitative variables represented on axes starting from... | ```python
import numpy as np
import matplotlib.pyplot as plt
def generate_radar_chart(categories, values, title):
num_vars = len(categories)
angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
ax.fill(angles, values... | magicoder | python |
You are tasked with creating a custom progress bar widget for a user interface library. The progress bar should be able to display the progress of a task as a percentage and should have the ability to be styled using XML serialization.
Your task is to implement the `ProgressBar` class, which is a subclass of the `Widg... | ```csharp
using System.ComponentModel;
using System.Xml.Serialization;
using Myra.Graphics2D.UI.Styles;
using Myra.Utility;
#if !XENKO
using Microsoft.Xna.Framework;
#else
using Xenko.Core.Mathematics;
#endif
namespace Myra.Graphics2D.UI
{
public class ProgressBar : Widget
{
private int _value;
... | magicoder | csharp |
You are tasked with implementing a memory management system for a virtual memory environment. The system needs to keep track of allocated and unallocated pages in the virtual memory space. To achieve this, you are provided with a `MemoryManager` struct containing an `allocated_page_map` field, which is a vector of bool... | ```rust
struct MemoryManager {
allocated_page_map: Vec<bool>,
}
impl MemoryManager {
fn new(num_pages: usize) -> MemoryManager {
MemoryManager {
allocated_page_map: vec![false; num_pages],
}
}
fn allocate_page(&mut self) -> Option<usize> {
if let Some(index) = self.... | magicoder | rust |
You are tasked with developing a command-line interface for a deep learning model training script. The script will train a neural network for a specific number of epochs, with options to specify the validation data ratio, pre-training epochs, and aspect-level to document-level epochs ratio. Your task is to implement th... | ```python
import argparse
def main():
parser = argparse.ArgumentParser(description="Neural Network Training Script")
parser.add_argument("--epochs", dest="epochs", type=int, metavar='<int>', default=80, help="Number of epochs (default=80)")
parser.add_argument("--validation-ratio", dest="validation_ratio"... | magicoder | python |
You are tasked with creating a Python class that generates SVG color codes based on a given value and colormap. The class should be able to handle both continuous color mapping and stripe pattern generation. Your task is to implement the `PatternContinousColors` class, which inherits from the `ContinousColors` class. T... | ```python
class ContinousColors:
def __init__(self, cmap):
self.cmap = cmap
def to_rgb(self, value: float) -> str:
color = self.cmap.to_rgba(value, bytes=True)[:3]
color = 'rgb({})'.format(', '.join([str(c) for c in color]))
return color
class PatternContinousColors(ContinousC... | magicoder | python |
You are tasked with implementing a Python class that can parse and manipulate Python code snippets. Your class should be able to handle the following functionalities:
1. Extracting the default value assigned to a keyword argument in a function definition.
2. Modifying a function definition to include a default value f... | ```python
class PythonCodeManipulator:
@staticmethod
def extract_default_value(func_def, keyword):
start_index = func_def.find(keyword + "=")
if start_index != -1:
start_index += len(keyword) + 1
end_index = func_def.find(",", start_index)
if end_index == -1:
... | magicoder | python |
You are tasked with implementing a caching system using a hash table in Swift. The cache will store items of type `RedisItem`, which represents an item in a Redis database. Each `RedisItem` has a unique `name` and a `value`, and is associated with a `RedisItemType`. Your task is to implement the `RedisCache` struct wit... | ```swift
struct RedisCache {
private var capacity: Int
private var cache: [String: RedisItem]
private var accessOrder: [String]
init(capacity: Int) {
self.capacity = capacity
self.cache = [:]
self.accessOrder = []
}
mutating func addItem(_ item: RedisItem) {
if ... | magicoder | swift |
You are tasked with creating a Python function to analyze performance data from a computing project. The function should parse the data from a specified directory and return four lists containing information about the area, runtime, frequency, and power consumption of the computing project.
The function signature and ... | ```python
from typing import List, Tuple
def data_parse(dir_root: str, power_mode: int) -> Tuple[List[float], List[float], List[float], List[float]:
# Placeholder implementation for demonstration purposes
area_list = [10.5, 15.2, 12.8, 18.6] # Placeholder area data
runtime_list = [25.3, 30.1, 27.8, 32.5] ... | magicoder | python |
You are working on a continuous integration system where you need to create a custom build step for a Jenkins job. The build step should involve resolving environment variables and launching a specific task based on the resolved environment variables. You need to implement a custom Jenkins plugin to achieve this functi... | ```java
import hudson.EnvVars;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.tasks.Builder;
import hudson.util.VariableResolver;
import org.kohsuke.stapler.DataBoundConstructor;
public class CustomBuilder extends Builder {
private final String taskToL... | magicoder | java |
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the average score of the game, excluding any scores that are negative. If there are no positive scores, the function should return 0.
Write a function `calculate_average_score(scores)` that takes in a l... | ```python
def calculate_average_score(scores):
positive_scores = [score for score in scores if score >= 0]
if positive_scores:
average_score = sum(positive_scores) / len(positive_scores)
return average_score
else:
return 0
```
The `calculate_average_score` function first filters out ... | magicoder | python |
You are given a snippet of code that operates on a DataFrame `df` using PySpark. The code filters the DataFrame to count the number of records where the value in the 6th column is 'Writer' and the value in the 5th column is less than 100000. Your task is to write a PySpark program to achieve the same result as the give... | ```python
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
# Create a Spark session
spark = SparkSession.builder.appName("FilterDataFrame").getOrCreate()
# Read the CSV file into a DataFrame
df = spark.read.csv("input.csv", header=True, inferSchema=True)
# Filter the DataFrame and count th... | magicoder | python |
You are tasked with implementing a localization mode generator for an ASP.NET application using C#. The `ILocalizationModeGenerator` interface defines a method to construct localization data based on a set of files, the current culture, and specific options.
Your task is to create a class that implements the `ILocaliz... | ```csharp
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using Askmethat.Aspnet.JsonLocalizer.Localizer;
namespace YourNamespace
{
internal class YourLocalizationModeGenerator : ILocalizationModeGenerator
{
public ConcurrentDictionary<st... | magicoder | csharp |
You are tasked with implementing a C++ template class that simulates a stack data structure. The stack should have the following functionalities:
1. Push: Add an element to the top of the stack.
2. Pop: Remove the element from the top of the stack.
3. Top: Retrieve the element at the top of the stack without removing i... | ```cpp
#include <iostream>
#include <vector>
#include <stdexcept>
template <typename T>
class Stack {
private:
std::vector<T> elements;
public:
// Constructor to initialize the stack
Stack() {
// No additional initialization logic needed
}
// Add an element to the top of the stack
voi... | magicoder | cpp |
You are tasked with implementing a logging system for a software application. The provided code snippet contains partial implementations of two logging functions: `LogsInfo` and `LogsDebug`. The `LogsInfo` function logs informational messages, while the `LogsDebug` function logs debug messages. Each function has three ... | ```python
def LogsFilewrite(message):
# Implement the function to write the message to a log file
# Example implementation:
with open('logfile.txt', 'a') as file:
file.write(message + '\n')
def GetLogString(message):
# Implement the function to format the log message
# Example implementatio... | magicoder | python |
You are tasked with implementing a simplified version of a Session Initiation Protocol (SIP) server in Rust. The SIP server is responsible for handling incoming messages and managing the state of the communication session. Your task is to complete the implementation of the `handle_msg` method in the `SipServer` struct,... | ```rust
impl SipServer {
fn handle_msg(&mut self, response: TsxResponse) -> Result<TsxResponse> {
match response.line.code.kind() {
CodeKind::Provisional => {
self.state = State::Proceeding;
}
_ => {
let registration = self.registration.tak... | magicoder | rust |
You are tasked with creating a Python function that retrieves all files in a specified directory and sorts them by creation date in descending order. Additionally, you need to parse the creation date of each file and return a dictionary mapping each file path to its corresponding creation date.
You are provided with a... | ```python
from datetime import datetime
from typing import Dict
from pathlib import Path
def get_datetime_by_age(age: str) -> datetime:
age_delta = timedelta(seconds=parse_time(age))
return datetime.now() - age_delta
def get_dir_files_by_date(path: Path) -> Dict[Path, datetime]:
"""Get all files in the sp... | magicoder | python |
You are tasked with implementing a class that manages products in an e-commerce system. The class should handle various operations related to products, such as adding, updating, and retrieving product information. Additionally, the class should interact with a general service to perform certain operations.
Your task i... | ```php
class ProductManager {
private $products = [];
public function addProduct($productId, $productName, $price, $quantity) {
if (!isset($this->products[$productId])) {
$this->products[$productId] = [
'name' => $productName,
'price' => $price,
... | magicoder | php |
You are tasked with creating a Java program to manage a library's book inventory. The program should allow users to add new books, remove existing books, and search for books by title or author. Additionally, the program should be able to display the entire inventory of books.
Your task is to implement the `Library` c... | ```java
import java.util.ArrayList;
import java.util.List;
class Book {
private String title;
private String author;
private int quantity;
public Book(String title, String author, int quantity) {
this.title = title;
this.author = author;
this.quantity = quantity;
}
pub... | magicoder | java |
You are tasked with implementing a class that calculates the entropy of a given text message based on a language model. Entropy is a measure of uncertainty or randomness in a message. In this problem, you need to implement the `entropy` method of the class. The method should calculate the total entropy of a message wit... | ```python
import math
class LanguageModel:
def __init__(self, model):
self.model = model # Assuming the language model is provided during initialization
def entropy(self, text):
'''Evaluate the total entropy of a message with respect to the model.
This is the sum of the log probabilit... | magicoder | python |
You are tasked with implementing a function that simulates an infinite scroller for fetching Pokémon information. The function should use the provided `useInfiniteQuery` hook to fetch Pokémon data in groups of a specified size. The `InfiniteScroller` function takes two parameters: `group_size` and `query`. The `group_s... | ```javascript
export default function InfiniteScroller({ group_size, query }: Props) {
const { data, fetchMore, canFetchMore } = useInfiniteQuery<
number[],
string,
number
>(
"pokemoninfo" + group_size,
async (key, offset = 0) => {
const exclusive_offset = offset + 1
const id_list = ... | magicoder | javascript |
You are tasked with implementing a peer validation system for a TCP server to protect against Denial of Service (DoS) and other attacks. The peer validation system will enforce a set of rules before allowing further processing of the peer connection.
Your task is to implement a function `validatePeer` that takes in a ... | ```java
import java.util.Set;
public class PeerValidation {
private Set<String> maliciousIpAddresses;
private int minAllowedPort;
private int maxAllowedPort;
public PeerValidation(Set<String> maliciousIpAddresses, int minAllowedPort, int maxAllowedPort) {
this.maliciousIpAddresses = maliciousI... | magicoder | java |
You are tasked with implementing a simple class that simulates a basic stack data structure. The class should have the following functionalities:
1. Push: Add an element to the top of the stack.
2. Pop: Remove and return the element at the top of the stack.
3. Peek: Return the element at the top of the stack without r... | ```java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Test the nextGreaterElement function
int[] nums = {4, 2, 3, 1};
int[] result = nextGreaterElement(nums);
System.out.println("Next Greater Elements for " + Arrays.toString(nums) + ": " + ... | magicoder | java |
You are tasked with implementing a function to merge multiple sets of top elements using different methods. The function `merge_top` takes a list of top sets and a method as input, and returns the merged top set based on the specified method.
The function signature is as follows:
```python
def merge_top(top_list: list... | ```python
def merge_top(top_list: list, method: str = 'cap') -> set:
if method not in ['cap', 'cup']:
raise NotImplementedError("Unsupported method")
if method == 'cap':
merged_top = set.intersection(*top_list)
else: # method == 'cup'
merged_top = set.union(*top_list)
return m... | magicoder | python |
You are tasked with creating a Python function that processes a schedule text in BC format and generates SQL queries for inserting the full schedule and schedule info into a database. The schedule text is in BC (Business Calendar) format and contains information about events, their timings, and other relevant details. ... | ```python
def process_schedule(text_sc):
# Parse the schedule text and extract relevant information
# Generate unique IDs for insertion into the database
# Construct SQL queries for inserting the full schedule and schedule info
full_schedule_query = "INSERT INTO full_schedule (event_id, event_name, date... | magicoder | python |
You are tasked with creating a custom error handling system for a software application. The system should include a set of error codes and their corresponding descriptions. Each error code should be represented by a unique integer value, and the descriptions should be associated with the error codes in a way that allow... | ```rust
pub struct CustomErrorSystem;
impl CustomErrorSystem {
pub const UPDATE_ERROR_FILE_NOT_FOUND: i32 = 4;
pub const UPDATE_ERROR_INCORRECT_OS_VERSION: i32 = 2;
pub const UPDATE_ERROR_UNKNOWN: i32 = 1;
pub fn get_error_description(error_code: i32) -> Option<&'static str> {
match error_code... | magicoder | rust |
You are tasked with implementing a Python class method that processes output data. The method should handle an OutputData object and a stream (stm) as input. The method should log an error message and return a default result if the input data is invalid. Otherwise, it should iterate through the output segments of the d... | ```python
class DataProcessor:
@classmethod
def process_output_single(cls, data, stm):
res = None # Default result
if not isinstance(data, OutputData) or stm is None or not stm.readable():
cls._logger.error("Invalid OutputData object or stream for output single")
return ... | magicoder | python |
You are tasked with implementing a program that reads a sequence of integers from the standard input until an end-of-file (EOF) is encountered. The program should then find the maximum and minimum values from the input sequence and print them to the standard output. If an empty sequence is encountered (i.e., no integer... | ```python
try:
numbers = []
while True:
num = input("Enter an integer (or press Enter to finish): ")
if num == '':
break
numbers.append(int(num))
if not numbers:
print("No integers provided")
else:
print("Maximum value:", max(numbers))
print("M... | magicoder | python |
You are tasked with creating a Python function that determines the specificity of a given date input. The function should take a string representing a date as input and return the specificity of the date. The specificity can be one of the following: "full" (indicating a complete date with day, month, and year), "month_... | ```python
def determine_date_specificity(user_input):
full_date_patterns = [...] # predefined list of patterns for full dates
month_year_date_patterns = [...] # predefined list of patterns for dates with month and year
year_date_patterns = [...] # predefined list of patterns for dates with only the year
... | magicoder | python |
You are tasked with creating a program that manages and renders various types of images on a tiny LED matrix display. The program should support rendering static images, animating sequences of images, and displaying bitmapped images.
The program should have three main components:
1. `Render`: A module from the `tiny_l... | ```rust
extern crate tiny_led_matrix;
extern crate scrolling;
extern crate image;
use tiny_led_matrix::Render;
use scrolling::Animate;
use image::BitImage;
fn main() {
// Render a static image on the LED matrix
let static_image = vec![
vec![1, 0, 1],
vec![0, 1, 0],
vec![1, 0, 1],
]... | magicoder | rust |
You are tasked with implementing a key-value (KV) data structure using Python classes. The KV data structure consists of key-value pairs, where the key is a string and the value can be either a single value or another KV data structure. The provided code snippet is a part of the implementation of the KV data structure.... | ```python
def add_KVPart_finished(self, part):
if part is not None:
self.values.append(part)
```
In the `add_KVPart_finished` method, we check if the input `part` is not `None`. If it is not `None`, we add the `part` to the `values` list of the current KVPart using the `append` method. This completes the implemen... | magicoder | python |
You are given a string containing hexadecimal escape sequences. Your task is to write a function to decode the string and return the corresponding ASCII representation.
Write a function `decode_hex_escape` that takes a string `hex_string` as input and returns the decoded ASCII representation.
Function Signature: `def... | ```python
def decode_hex_escape(hex_string: str) -> str:
hex_list = hex_string.split("\\x")[1:] # Split the string and remove the empty first element
decoded_string = ""
for hex_val in hex_list:
decoded_string += chr(int(hex_val, 16)) # Convert each hexadecimal value to ASCII character
return ... | magicoder | python |
You are tasked with creating a simple game in Unity where the player has to navigate through a maze. To add an element of challenge, you want to implement a feature where the player has a limited amount of time to complete the maze. You decide to use coroutines to handle the timing aspect. Below is a simplified version... | To solve this problem, you would need to create a Unity project and set up the maze environment. Here's a high-level overview of the steps you would take:
1. Create a new Unity project or open an existing one.
2. Set up the maze environment using Unity's 3D modeling tools or import a pre-made maze model.
3. Create a p... | magicoder | python |
You are tasked with implementing a function to merge multiple datasets into a single dataset for training a machine learning model. The function should take a list of pickle files, the size of the training dataset, and the size of the validation dataset as input. It should then merge the datasets from the pickle files ... | ```python
import numpy as np
import random
import pickle
def make_arrays(nb_rows, img_size):
if nb_rows:
dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32)
labels = np.ndarray(nb_rows, dtype=np.int32)
else:
dataset, labels = None, None
return dataset, labels
def ... | magicoder | python |
You are tasked with creating a Python class to represent a YouTube video using the `pytube3` library. Your class should have the following functionalities:
1. A method to initialize the video object with its title, author, and length in seconds.
2. A method to add available video streams to the video object.
3. A metho... | ```python
from pytube.streams import Stream
class YouTubeVideo:
def __init__(self, title, author, length):
self.title = title
self.author = author
self.length = length
self.streams = []
def add_stream(self, stream):
if isinstance(stream, Stream):
self.stream... | magicoder | python |
You are tasked with implementing a generic function that filters elements of a given array based on a specified type. The function should take an array of elements of any type and a type parameter, and return a new array containing only the elements that match the specified type.
The function signature should be:
```s... | ```swift
func filterByType<T>(_ array: [Any], _ type: T.Type) -> [T] {
var filteredArray = [T]()
for element in array {
if let typedElement = element as? T {
filteredArray.append(typedElement)
}
}
return filteredArray
}
// Test the function
let inputArray: [Any] = [1, "two",... | magicoder | swift |
You are tasked with creating a language translation tool that can convert English phrases to their corresponding Chinese translations. The tool should be able to handle multiple phrases and their translations, and should also support the ability to mark certain translations as "confirmed" or "unconfirmed".
You are giv... | ```python
def translate_to_chinese(phrases):
translations = {}
for english, _, (chinese, _, (confirmed, _)) in phrases:
english_phrase, _ = english
translations[english_phrase] = {
"translation": chinese,
"confirmed": confirmed
}
return translations
``` | magicoder | python |
You are given a Python code snippet that calculates the sum of all numbers that are multiples of 3 within a given range. Your task is to write a Python function that achieves the same result as the code snippet. The function should take two integer parameters, `start` and `end`, representing the inclusive range of numb... | ```python
def sum_of_multiples_of_3(start, end):
cont = 0
soma = 0
for imp in range(start, end + 1):
if imp % 3 == 0:
cont = cont + 1
soma = soma + imp
return soma
# Test the function
print(sum_of_multiples_of_3(1, 10)) # Output: 18
``` | magicoder | python |
You are tasked with implementing a JWT (JSON Web Token) authentication mechanism for a web application. Your goal is to create a Java class that generates and validates JWT tokens using the `com.xhiteam.xauth.impl.jwt` package. The JWT tokens should contain a user's ID and role, and should be signed using a secret key.... | ```java
package com.xhiteam.xauth.impl.jwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;
public class JwtTokenUtil {
private static final Key SECRET_KEY = Keys.secretKe... | magicoder | java |
You are tasked with implementing a class that extracts the content of a comment from a given string. The comment is enclosed within `/*` and `*/` and may span multiple lines. Your task is to write a method that takes the input string and returns the content of the comment.
You are given the following code snippet as a... | ```swift
class CommentExtractor {
public func getData(from input: String) -> String {
guard let startRange = input.range(of: "/*"), let endRange = input.range(of: "*/") else {
return ""
}
let startIndex = startRange.upperBound
let endIndex = endRange.lowerBound
... | magicoder | swift |
You are tasked with implementing a simple timer-based control view dismissal mechanism for a video player application. The provided code snippet shows the initialization of a timer and a task for dismissing the control view after a certain duration. Your task is to complete the implementation by defining the `DismissCo... | ```java
import java.util.Timer;
import java.util.TimerTask;
public class DismissControlViewTimerTask extends TimerTask {
private JZVideoPlayer player;
public DismissControlViewTimerTask(JZVideoPlayer player) {
this.player = player;
}
@Override
public void run() {
// Dismiss the co... | magicoder | java |
You are tasked with implementing a class that manages media compounds for a biological simulation. The given code snippet is a method within the class that adds compounds to the media dictionary. Each compound has an ID, lower bound, and upper bound. If a compound has a specific component (cmp), its ID is appended with... | ```python
class Compound:
def __init__(self, id, lower_bound, upper_bound):
self.id = id
self.lower_bound = lower_bound
self.upper_bound = upper_bound
class MediaManager:
def __init__(self):
self.mediacompounds = []
self.media = {}
def add_compound_to_media(self, co... | magicoder | python |
You are working on a project that involves processing and manipulating sparse matrices efficiently. Sparse matrices are matrices in which most of the elements are zero. There are various formats for representing sparse matrices, each with its own advantages and use cases. In this problem, you are tasked with implementi... | ```python
import numpy as np
from typing import Tuple
def convert_csr_to_csc(data, indices, indptr, num_rows, num_cols) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
csc_data = np.empty_like(data)
csc_indices = np.empty_like(indices)
csc_indptr = np.zeros(num_cols + 1, dtype=np.int32)
col_counts = np.... | magicoder | python |
You are tasked with creating a script to automate the deployment process for a blockchain application. The deployment process involves starting a Docker container for the EOSIO blockchain and launching a frontend React app. Your script should handle the execution of the necessary commands to start the EOSIO Docker cont... | ```bash
#!/bin/bash
# Function to handle errors
handle_error() {
echo "Error: $1" >&2
exit 1
}
# Execute start_eosio_docker.sh with --nolog option
./start_eosio_docker.sh --nolog || handle_error "Failed to start EOSIO Docker container"
# Check if the EOSIO Docker container is running
docker ps | grep eosio_conta... | magicoder | shell |
You are given a code snippet that appears to set environment variables and contains a placeholder `<gh_stars>0`. Your task is to write a program that parses the code snippet and replaces the placeholder with the actual number of stars for a given GitHub repository.
Write a function or program that takes the code snip... | ```python
import requests
import re
def get_github_stars(code_snippet, github_repo):
# Extract the GitHub repository name from the URL
repo_name = github_repo.split('/')[-1]
# Make a GET request to the GitHub API to retrieve the repository information
try:
response = requests.get(f'https://api... | magicoder | python |
You are tasked with implementing a simple URL routing system for a web application. The URL routing system should be able to handle both traditional HTTP requests and WebSocket connections. You are given a code snippet that sets up the URL routing for WebSocket connections using the `URLRouter` class.
Your task is to ... | ```python
from django.urls import path
from apps.websocket.routing import websocket_urlpatterns
from django.urls import include
# Define URL patterns for traditional HTTP requests
http_urlpatterns = [
path('home/', views.home, name='home'),
path('about/', views.about, name='about'),
# Add more URL patterns... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.