query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are working on a computer graphics project and need to implement a function to convert light sample weight to a solid angle measure. The function takes into account a few parameters such as the distance between two points, the normal vector, and the area of the light source. Your task is to implement the function t...
```python import math class Vector3d: # Assume implementation of Vector3d class class Ray: # Assume implementation of Ray class class LightSource: def Area(self): # Implementation of the Area method def convert_to_solid_angle_measure(p, ray, thit, dgLight, wi): distance_squared = (p - ray.ge...
magicoder
python
You are tasked with creating a program that efficiently organizes and manages interrupt service routines (ISRs) for a microcontroller. The ISRs are represented as strings in the following format: "NVIC_<PERIPHERAL_NAME>_IRQ". The program should allow for registering, unregistering, and invoking ISRs, as well as providi...
```python from typing import Callable, List class ISRManager: def __init__(self): self.isr_handlers = {} def register_isr(self, isr_name: str, handler: Callable[[], None]) -> None: self.isr_handlers[isr_name] = handler def unregister_isr(self, isr_name: str) -> None: if isr_name i...
magicoder
python
You are tasked with implementing a program to manage a sports tournament. The program should be able to update the points of the participating teams based on the match results. Each team is identified by a unique integer ID, and the program should be able to handle ties as well. You are given a partial code snippet fo...
```cpp #include <iostream> #include <vector> struct TeamPoints { int ID; int points; }; std::vector<TeamPoints> teamPoints; // Assuming this vector is initialized with team IDs and initial points void updateTeamPoints(int fTeam, int sTeam, int winner) { for (int i = 0; i < teamPoints.size(); i++) { ...
magicoder
cpp
You are tasked with implementing a function to parse and extract color information from a given code snippet. The code snippet contains a comment that describes a color in either RGB or named format. Your task is to write a function that extracts the color information and returns it in a standardized format. Write a f...
```python from typing import Union, Tuple def parseColor(code: str) -> Union[Tuple[int, int, int], str]: comment_start = code.find('//') # Find the start of the comment if comment_start != -1: comment = code[comment_start + 2:] # Extract the comment portion parts = comment.split() # Split th...
magicoder
python
You are tasked with creating a program to manage a list of items with their respective values. The program should prompt the user to input the number of items and then enter the value for each item. However, the program should validate the input to ensure that the value of each item is greater than 0. If the user enter...
```cpp #include <iostream> using namespace std; int main() { int items; double totalValue = 0.0; cout << "Enter the number of items: "; cin >> items; while (items <= 0) { cout << "Number of items must be greater than 0. Enter a valid number: "; cin >> items; } for (int in...
magicoder
cpp
You are tasked with creating a Python module for image transformation workflows. The module should include classes for different types of transformation workflows, such as affine transformation, linear transformation, coordinate transformation, and general transformation. The code snippet provided imports these classes...
```python # transformation_workflows.py class AffineTransformationWorkflow: def __init__(self): # Initialize affine transformation workflow pass def apply_transformation(self, image): # Apply affine transformation to the input image pass class LinearTransformationWorkflow: ...
magicoder
python
You are tasked with creating a Python function that retrieves and processes data from a web page. Your function should utilize the `requests` library to fetch the content of a given URL and then parse the HTML to extract specific information. The function should return a structured representation of the data for furthe...
```python import requests from lxml import html def extract_page_data(url): try: page = requests.get(url, verify=False) page_tree = html.fromstring(page.content) # Extract specific information from the page_tree # Example: Extract all the links from the page extracted_data =...
magicoder
python
You are tasked with implementing a Python class that manages audio files using the AVFoundation framework. The class, named `SoundAvplayer`, should provide methods for loading and unloading audio files, as well as playing and stopping the loaded audio. The class should also handle errors that may occur during the loadi...
```python import objc from Foundation import * from AVFoundation import * class SoundAvplayer(NSObject): SUPPORTED_FORMATS = ("mp3", "m4a", "snd", "au", "sd2", "wav") def __init__(self, filename, **kwargs): self._avplayer = None self.filename = filename super(SoundAvplayer, self).__ini...
magicoder
python
You are tasked with creating a Python web service that utilizes the aiohttp library to handle HTTP requests and manage user sessions. Your goal is to implement a simple web server that can handle user authentication and session management using the `aiohttp` and `servicelib` libraries. Your task is to create a Python ...
```python import aiohttp from aiohttp import web from servicelib.session import get_session async def login_handler(request): data = await request.post() username = data.get('username') password = data.get('password') # Perform authentication logic here # Assuming successful authentication ...
magicoder
python
You are tasked with implementing a data structure to manage the state of sectors in a storage system. The system has two states for sectors: staged and sealed. The staged state contains sector IDs and their corresponding metadata, while the sealed state only contains sector IDs and their sealed metadata. Your task is ...
```rust use std::collections::HashMap; use serde::{Serialize, Deserialize}; type SectorId = u64; #[derive(Default, Serialize, Deserialize, Debug, PartialEq)] pub struct StagedState { pub sector_id_nonce: SectorId, pub sectors: HashMap<SectorId, StagedSectorMetadata>, } #[derive(Default, Serialize, Deserializ...
magicoder
rust
You are tasked with creating a Rust module for a simple task queue system. The task queue should support adding tasks, executing tasks in a first-in-first-out (FIFO) manner, and retrieving the result of the executed tasks. You need to implement the `TaskQueue` module with the following specifications: 1. The `Task` st...
```rust pub mod queue { pub struct Task { id: u64, task_fn: Box<dyn Fn() -> u64>, } pub struct TaskQueue { tasks: Vec<Task>, } impl TaskQueue { pub fn new() -> TaskQueue { TaskQueue { tasks: Vec::new() } } pub fn add_task(&mut self, id: ...
magicoder
rust
You are given a Python code snippet that appears to be part of a function to process a sequence of characters. Your task is to complete the function by implementing the missing part. The function is intended to process a sequence of characters and extract valid base characters from it. The provided code snippet initia...
```python def process_sequence(seq, validbase): newseq = ["" for _ in seq] inseq = False lastbase = 0 for (i, j) in enumerate(seq): if j in validbase: inseq = True newseq[i] = j lastbase = i elif inseq: break # Stop processing the sequence...
magicoder
python
You are tasked with creating a Python script to manage a database using the provided functions from the `pages.db.db` module. The module contains the following functions: - `db_clean()`: This function cleans up the database by removing any redundant or obsolete data. - `db_creation()`: This function initializes a new d...
```python from pages.db.db import db_clean, db_creation, db_insert, db_select def main(): # Clean up the database db_clean() # Initialize a new database db_creation() # Insert data into the database data_to_insert = [ {'id': 1, 'name': 'John', 'age': 25}, {'id': 2, 'name': 'Al...
magicoder
python
You are tasked with creating a program that analyzes the frequency of words in a given text file. Your program should read a text file and output the top N most frequently occurring words along with their respective frequencies. For the purpose of this problem, a word is defined as a sequence of alphanumeric characters...
```python import re from collections import Counter def analyze_word_frequency(file_path, N): with open(file_path, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) word_counts = Counter(words) top_words = word_counts.most_common(N) for word, coun...
magicoder
python
You are tasked with implementing a simple stack data structure in Python. A stack is a Last-In-First-Out (LIFO) data structure that supports two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack. Additionally, you need to implement a method to ge...
```python class MinStack: def __init__(self): self.stack = [] self.min_stack = [] def push(self, val): self.stack.append(val) if not self.min_stack or val <= self.min_stack[-1]: self.min_stack.append(val) def pop(self): if self.stack: if self...
magicoder
python
You are tasked with creating a program that processes a given HTML file and extracts the labels and input types from the form elements. The HTML file contains form elements with various attributes, and your program should be able to identify and extract the relevant information. You need to write a function or method ...
```python from bs4 import BeautifulSoup def extract_form_elements(html_content: str) -> dict: form_elements = {} soup = BeautifulSoup(html_content, 'html.parser') form_groups = soup.find_all('div', class_='form-group') for group in form_groups: label = group.find('label').text.strip() ...
magicoder
python
You are tasked with creating a program that simulates a simple file system. The file system will consist of directories and files, and you need to implement basic operations such as creating directories, creating files, listing the contents of a directory, and navigating through the file system. Your task is to implem...
```python class FileSystem: def __init__(self): self.root = {'/': []} self.current_path = '/' def create_directory(self, path): if path in self.root: print("Directory already exists") else: self.root[path] = [] self.root[self.current_path].app...
magicoder
python
You are tasked with creating a Python program that analyzes the memory usage of a given function and identifies the most memory-intensive parts of the code. To achieve this, you will need to utilize the `tracemalloc` module, which allows you to trace memory allocation in Python. The `tracemalloc` module provides a `tak...
```python import tracemalloc import linecache def find_memory_intensive_line(func: callable) -> (str, int): tracemalloc.start() func() # Execute the given function snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('traceback') most_memory_intensive = top_stats[0] # Get the m...
magicoder
python
You are tasked with creating a program to manage a collection of books in a library. Each book has a unique ISBN (International Standard Book Number), a title, an author, and a quantity available. The program should allow users to perform various operations such as adding a new book, removing a book, updating the quant...
```java import java.util.HashMap; class Book { private String ISBN; private String title; private String author; private int quantity; public Book(String ISBN, String title, String author, int quantity) { this.ISBN = ISBN; this.title = title; this.author = author; t...
magicoder
java
You are tasked with creating a custom test case class for a PHP application using PHPUnit. Your task is to extend the `TestCase` class provided by PHPUnit and implement a custom test case method that checks the functionality of a specific class or method within your application. Your custom test case class should have...
```php use PHPUnit\Framework\TestCase; class CustomTestCase extends TestCase { public function testAddMethod() { $calculator = new Calculator(); $result = $calculator->add(3, 5); $this->assertEquals(8, $result); } } class Calculator { public function add($a, $b) { r...
magicoder
php
You are tasked with creating a Python program that generates a colorful title for a given text. The program should take the input text and display it as a title with a colorful border around it. The colors for the border will be randomly selected from a predefined list of colors. The length of the border should be dete...
```python import random colors = { 'preto': '\033[30m', 'vermelho': '\033[31m', 'verde': '\033[32m', 'amarelo': '\033[33m', 'azul': '\033[34m', 'roxo': '\033[35m', 'ciano': '\033[36m', 'cinza': '\033[37m' } def generate_colorful_title(text, padding): color_border = random.choice(li...
magicoder
python
You are given an array of UIImage objects `imgArray` and an array of strings `descArray`. Your task is to write a function that combines these arrays into a dictionary where the strings from `descArray` are the keys and the corresponding UIImage objects from `imgArray` are the values. If there are more strings than ima...
```swift func createImageDictionary(imgArray: [UIImage], descArray: [String]) -> [String: UIImage] { var imageDictionary = [String: UIImage]() for (index, desc) in descArray.enumerated() { if index < imgArray.count { imageDictionary[desc] = imgArray[index] } } retur...
magicoder
swift
You are tasked with implementing a simplified version of a publish-subscribe system using Python. The system consists of a Publisher class and a Subscriber class, which communicate through a shared connection. The Publisher publishes messages to a specific topic, and the Subscriber listens for messages on the same topi...
```python class Subscriber: def __init__(self, pub_sub_connection, topic, latch): self._pub_sub_connection = pub_sub_connection self.__topic = topic self._latch = latch def subscribe(self): self._pub_sub_connection.subscribe(self.__topic) def listen(self): while Tru...
magicoder
python
You are tasked with implementing a function that performs a binary search on a sorted array to find the index of a given target value. However, there's a twist - the search algorithm has a time constraint and must terminate if it exceeds a specified timeout period. You are required to handle this constraint within your...
```python import time def timed_binary_search(arr, target, timeout): start_time = time.time() end_time = start_time + timeout left, right = 0, len(arr) - 1 while left <= right: if time.time() > end_time: return -1 # Timeout exceeded, return -1 mid = left + (right - left) ...
magicoder
python
You are tasked with creating a Python program to analyze a list of gamma distributed values representing gene fragment lengths. The program should calculate the average length of the gene fragments and identify the number of fragments that exceed a certain threshold length. Additionally, the program should determine th...
```python import numpy def analyze_gene_fragments(gamma_numbers, threshold): average_length = sum(gamma_numbers) / len(gamma_numbers) count_exceeding_threshold = sum(1 for length in gamma_numbers if length > threshold) longest_fragment_index = gamma_numbers.index(max(gamma_numbers)) return (average_len...
magicoder
python
You are given a Swift code snippet that contains a nested enum, struct, and class. Your task is to write a function that takes a generic type `T` conforming to a protocol `P` and returns a new instance of a specific type defined within the code snippet. The code snippet is as follows: ```swift if true { enum b { ...
```swift // Define a protocol P protocol P { // Define any protocol requirements if needed } // Implement the createInstance function func createInstance<T: P>() -> T { // Return a new instance of type T return T() } ``` In this solution, we define a protocol `P` and implement the `createInstance` functio...
magicoder
swift
You are tasked with implementing a custom middleware in a Django web application. The middleware should intercept incoming requests and set environment variables based on the values provided in the request. These environment variables will then be used by the Django application to customize its behavior for each reques...
```python import os from django.core.wsgi import get_wsgi_application class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Extract values from request headers entidad_id = request.headers.get('ENTIDAD_ID') ent...
magicoder
python
You are tasked with implementing a function that evaluates an abstract syntax tree (AST) and returns the result. The AST represents a sequence of expressions and reference sequences, and the evaluation involves recursively evaluating the expressions and handling reference sequences based on certain conditions. You are...
```rust fn eval( list: &Ast, current_scope: &Scope, stack_key: &StackKey, ) -> Result<Vec<ResultType>, EvalError> { match *list { Ast::Seq(ref exprs, ..) => { let mut evals = vec![]; for ex in exprs { evals.push(eval(ex, current_scope, stack_key)?); ...
magicoder
rust
You are tasked with implementing a text formatting utility that applies different styles to a given text. The utility should support various styles such as bold, italic, underline, and color. You need to create a function that takes a text string and a style object as input and returns the formatted text according to t...
```javascript function applyStyle(text, style) { let formattedText = text; if (style.bold) { formattedText = `\x1b[1m${formattedText}`; } if (style.italic) { formattedText = `\x1b[3m${formattedText}`; } if (style.underline) { formattedText = `\x1b[4m${formattedText}`; } if (style.color) { ...
magicoder
javascript
You are tasked with implementing a function to project 3D points onto a 2D image plane using a pinhole camera model. The function should take as input the 3D points, camera rotation matrix, translation vector, and focal length, and return the corresponding 2D image coordinates of the projected points. The pinhole came...
```python import numpy as np def project_points(pts, cam_R, cam_t, cam_f): # Convert pts to homogeneous coordinates pts = np.array(pts) pts = np.hstack((pts, np.ones((pts.shape[0], 1)))) # Apply camera transformation cam_pts = np.dot(cam_R, pts.T) + cam_t.reshape(3, 1) # Apply perspective pro...
magicoder
python
You are tasked with implementing a voting system for identifying a ball in a computer vision application. The provided code snippet is part of a larger system that processes observations of a ball and updates its state based on certain conditions. Your task is to complete the implementation by writing the logic for the...
```cpp void updateBallIdentification(Ball* ball) { if (ball->identified) { // Ball is already identified, no further action needed return; } // Increment the observed times ball->cc_observed_times++; // Check conditions for further action if (ball->templatevotes[3] >= 1 || ball...
magicoder
cpp
You are tasked with implementing a function to process a series of image files using the QBetaKarttakuva library. The QBetaKarttakuva library provides functions for reading and manipulating image files in a proprietary format. Your task is to write a function that takes a list of image file paths as input, processes ea...
```c++ #include "qbetakarttakuva.h" void processAndSaveImages(const std::vector<std::string>& imagePaths, const std::string& outputDirectory) { for (const auto& imagePath : imagePaths) { Image image; if (loadImage(imagePath, image)) { applyProcessingAlgorithm(image); std::st...
magicoder
python
You are tasked with creating a program that processes save files for a game called "Satisfactory." The save files are in a custom binary format and need to be parsed and analyzed. The save file format is represented by the `SaveFile` struct provided by the `satisfactory_save_file` crate. The `SaveFile` struct has metho...
```rust use satisfactory_save_file::SaveFile; fn analyze_save_file(data: &[u8]) -> (usize, Vec<String>) { let save_file = SaveFile::from_reader(&mut Cursor::new(data)).unwrap(); let mut item_names = Vec::new(); for item in save_file.items() { item_names.push(item.name().to_string()); } (s...
magicoder
rust
You are working for a data processing company that needs to clean and merge multiple datasets. Your task is to write a Python function that takes in several dataframes, performs a series of data cleaning and manipulation operations, and then returns the final merged dataframe. The function should perform the following...
```python import pandas as pd def clean_and_merge_data(full_data08, full_data12, new_13): full_data12 = full_data12[full_data12.year != 13] full_data12 = pd.concat([new_13, full_data12], join="inner") full_data12["year"] = full_data12["year"] + 2000 full_data08 = full_data08.rename(columns={"zip code":...
magicoder
python
You are tasked with creating a Java method that securely sets up environment variables for an Impala web server and starts an Impala cluster. The method should ensure that sensitive information, such as passwords, is handled securely. Your task is to implement the `setUpImpalaWebServer` method, which sets up the enviro...
```java import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class ImpalaWebServerSetup { private static final String TEST_USER_1 = "test_user_1"; private Metrics metrics_; // Assuming Metrics class is defined elsewhere public int setUpImpalaWebServer(String...
magicoder
java
You are tasked with implementing a function to calculate the multi-modified Damerau-Levenshtein distance between a given string and an array of strings. The multi-modified Damerau-Levenshtein distance is a measure of the similarity between two strings, taking into account insertions, deletions, substitutions, and trans...
```rust fn multi_modified_damlev(input: &str, words: &[&str]) -> Vec<usize> { let mut distances = Vec::new(); for word in words { let distance = modified_damlev(input, word); distances.push(distance); } distances } fn modified_damlev(s1: &str, s2: &str) -> usize { let len1 = s1.ch...
magicoder
rust
You are tasked with implementing a simulation control system for a graphical user interface (GUI) application. The simulation control system will manage the timing and layout of various components within the GUI. The provided code snippet contains constants that will be used in the implementation. The constants `SIMCO...
```java public class SimulationControlSystem { public static final int SIMCONTROL_COL = 0; public static final int SIMCONTROL_ROW_SPAN = 1; public static final int SIMCONTROL_COL_SPAN = 2; public static final int FRAMES_PER_SECOND = 10; // Method to initialize the simulation control component withi...
magicoder
java
You are working on a machine learning project and need to preprocess image data for training and testing. You have a set of image data in the form of a 3D numpy array and corresponding labels. Additionally, you have a test dataset with image names and labels stored in a CSV file. Your task is to create a function that ...
```python import numpy as np import pandas as pd import os def preprocess_data(traindata, labels, testdir): # Step 1: Convert traindata dictionary and labels list into a list of tuples train_data_list = [(traindata[i], label) for i, label in enumerate(labels)] # Step 2: Read the CSV file and extract i...
magicoder
python
You are tasked with implementing a memoization technique to optimize a recursive function. Memoization is a method used to store the results of expensive function calls and return the cached result when the same inputs occur again. The code snippet provided is a placeholder for the actual memoization logic. Your task ...
```python import time def memoize(func): cache = {} def memoized_func(*args): if args not in cache: cache[args] = func(*args) return cache[args] return memoized_func def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) # Applying memoi...
magicoder
python
You are tasked with creating a program to simulate a simple database connection pool and data retrieval process. The program will involve generating random world IDs, querying a database, and returning the corresponding world data. You are given a code snippet that represents part of the program. The `conn` variable r...
```rust use rand::Rng; use diesel::prelude::*; // Assuming Diesel ORM is used for database operations // Define a struct representing the database connection pool struct DatabaseConnectionPool { // Define the necessary fields and methods for the connection pool } impl DatabaseConnectionPool { // Implement a m...
magicoder
rust
You are tasked with implementing a function that translates Win32 error codes to ART (Application Response Time) equivalents. The function should take a Win32 error code as input and return the corresponding ART equivalent. Additionally, you need to handle the mapping of Win32 error codes to ART equivalents for a speci...
```c DEFRESULT TranslateWin32ToART(DWORD win32ErrorCode) { switch (win32ErrorCode) { case ERROR_FILE_NOT_FOUND: return ART_FILE_NOT_FOUND; case ERROR_ACCESS_DENIED: return ART_ACCESS_DENIED; case ERROR_INVALID_HANDLE: return ART_INVALID_HANDLE; // ...
magicoder
c
You are tasked with implementing a Python class for calculating the Kernel Inception Distance (KID) to compare two sets of image intensity distributions. The KID is a statistical measure used to evaluate the similarity between two distributions. Your task is to create a class `KID` with the following functionalities: -...
```python import torch import numpy as np class KID: def __init__(self, subset_size): self.subset_size = subset_size self.real_imgs = [] self.generated_imgs = [] def update(self, imgs, real): if real: self.real_imgs.append(imgs) else: self.genera...
magicoder
python
You are tasked with creating a Python class that simulates a simple notification system. The class should be able to send notifications to different recipients and allow for customization of the notification message. Your task is to implement the `NotificationSystem` class with the following specifications: - The clas...
```python from direct.directnotify import DirectNotifyGlobal class NotificationSystem: def __init__(self): self.recipients = [] def add_recipient(self, recipient): self.recipients.append(recipient) def send_notification(self, message): notify = DirectNotifyGlobal.directNotify.newC...
magicoder
python
You are tasked with simulating a user management system using Python. The system should be able to perform actions such as inserting a new user, updating an existing user, adding an order for a user, and deleting a user. The actions are chosen randomly from a list of possible actions, and the corresponding functions ar...
```python from random import choice POSSIBLE_ACTIONS = ["insert_user", "update_user", "insert_order", "delete_user"] def insert_user(): print("Inserting a new user") def update_user(): print("Updating an existing user") def add_order(): print("Adding an order for a user") def delete_user(): print("...
magicoder
python
You are tasked with creating a custom form component in React that supports various layouts and validation functionalities. Your goal is to implement a `Form` component with the following features: - The `Form` component should accept the following props: - `layout` (optional): Specifies the layout of the form, defa...
```jsx import React from 'react'; import { Form } from 'antd'; // Assuming the use of Ant Design library for form components class CustomForm extends React.Component { render() { const { layout = 'vertical', form, onSubmit, onFinishFailed, className, style } = this.props; ...
magicoder
jsx
You are tasked with creating a migration script for a database table in a Laravel application. The table, named "cell", needs to have a composite index created on two columns: "meta_y_id" and "instance_id". Additionally, you need to ensure that the migration script includes the necessary code to reverse the index creat...
```php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCellTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('cell', func...
magicoder
php
You are tasked with implementing a Python function, `recursive_sum(arr)`, that calculates the sum of all elements in a nested list of integers. The function should handle both empty lists and lists containing integers or nested lists of integers. For example, given the input `[1, [2, [3, 4], 5], 6]`, the function shoul...
```python def recursive_sum(arr): total = 0 for element in arr: if isinstance(element, list): total += recursive_sum(element) # Recursively sum nested lists else: total += element # Add integers to the total return total # Run the unit tests unittest.main(argv=['']...
magicoder
python
You are tasked with creating a program to categorize and organize different types of electrical plugs based on their specifications. Each plug type is represented by a string in the format "standard-voltage-phase-connector-amperage", where: - "standard" is the standardization organization (e.g., "iec" for International...
```python def organize_plug_types(plug_list): plug_dict = {} for plug in plug_list: parts = plug.split("-") voltage = parts[1].split("")[0] phase = parts[2] connector = parts[3] key = (voltage, phase, connector) if key in plug_dict: plug_dict[key].appe...
magicoder
python
You are tasked with implementing a custom pretty-printing module in Python. The module should provide two main functions: `pretty` and `pretty_print`. The `pretty` function should take an object as input and return a string representation of the object in a human-readable format. The `pretty_print` function should take...
```python # custom_pprint.py pprint_use_unicode = False # Default configuration option def pretty(obj): if isinstance(obj, dict): return _pretty_dict(obj) elif isinstance(obj, list): return _pretty_list(obj) elif isinstance(obj, tuple): return _pretty_tuple(obj) elif isinstanc...
magicoder
python
You are tasked with implementing a class that calculates the point of closest approach (POCA) between two tracks in a particle physics experiment. The class `TrkPocaBase` takes in two track parameters (`flt1` and `flt2`) and a precision value, and it should compute the POCA with the given precision. The `TrkPocaBase` ...
```cpp #include <cmath> class TrkPocaBase { private: double trackParam1; double trackParam2; double pocaPrecision; public: TrkPocaBase(double flt1, double flt2, double precision) : trackParam1(flt1), trackParam2(flt2), pocaPrecision(precision) { // Perform POCA calculation here using t...
magicoder
cpp
You are tasked with implementing a password change functionality for a user in a web application. The `UserController` class is responsible for handling user-related actions, and the `actionChangePwd` method is specifically designed to allow users to change their passwords. Your task is to complete the implementation o...
```php class UserController extends MetaBaseController { /** * 修改个人密码 * @param string $newPassword The new password to be set for the user * @return string A message indicating the success or failure of the password change operation */ public function actionChangePwd($newPassword) { ...
magicoder
php
You are tasked with implementing a function that calculates the total number of parameters in a convolutional neural network (CNN) layer. The function should take the input shape of the layer as a tuple and return the total number of parameters, considering the weights and biases. The total number of parameters in a C...
```python def calculate_cnn_parameters(input_shape): filter_width = input_shape[-3] filter_height = input_shape[-2] input_channels = input_shape[-1] output_channels = input_shape[-4] total_parameters = (filter_width * filter_height * input_channels + 1) * output_channels return total_parame...
magicoder
python
You are given an HTML code snippet that is intended to display a list item with a link to Instagram and an image. However, the code contains several errors and is not rendering as expected. Your task is to identify and correct the errors in the code to ensure that the list item and image are displayed correctly. Given...
The given HTML code snippet contains several errors. Here's the corrected HTML code: ```html <ul> <li><a href="#">Instagram</a></li> <li><div id="y"><img src="image/instra.jpg" height="40px" width="40px" style="border-radius:50%;"></div></li> </ul> ``` Explanation: 1. The opening `<ul>` tag was missing in the ori...
magicoder
html
You are working on a project that involves analyzing and extracting metrics from a machine learning model using TensorFlow. As part of this project, you need to implement a custom metric extractor that utilizes TensorFlow's model variables and logging capabilities. Your task is to create a Python class called `CustomM...
```python from logging import log from signver.extractor import MetricExtractor from tensorflow.python.ops.variables import model_variables class CustomMetricExtractor(MetricExtractor): def extract_metrics(self, tensorflow_model): log("Extraction process started", level=20) model_vars = model_varia...
magicoder
python
You are tasked with implementing a custom random number generator that uses a linear congruential generator (LCG) algorithm. The LCG algorithm generates a sequence of pseudo-randomized numbers using the formula: Xn+1 = (a * Xn + c) % m, where Xn is the current number, a is a multiplier, c is an increment, and m is the ...
```python def init_seeds(multiplier, increment, modulus, seed=0): def rand(): nonlocal seed seed = (multiplier * seed + increment) % modulus return seed return rand ```
magicoder
python
You are tasked with creating a simple iOS app that displays information about various locations. The app's main view is defined using SwiftUI, and it includes a ZStack containing a VStack and an HStack. Within the HStack, there is a VStack with alignment set to .leading, and within this VStack, there is a Text view dis...
```swift func updateLocationName(locationName: String) -> String { let modifiedCodeSnippet = """ var body: some View { ZStack { HStack { VStack(alignment: .leading) { Spacer() Text("\(locationName.uppercased())") // ...
magicoder
swift
You are tasked with implementing a function to calculate the exact solution of a partial differential equation using the given code snippet as a reference. The function `exact_solution` takes in three parameters: `x` (position), `t` (time), and an optional parameter `q` with a default value of 1. The function uses a su...
```python import numpy def exact_solution(x, t, coefficients, q=1): exact_solution_value = sum( coefficient * numpy.exp(-q * (k * numpy.pi) ** 2 * t) * numpy.sin(k * numpy.pi * x) for k, coefficient in enumerate(coefficients) ) return exact_solution_value ``` The `exact_solution` function a...
magicoder
python
You are tasked with creating a Python function that generates a classification report for a given dataset. The dataset is represented as a pandas DataFrame and contains features and target values for a classification problem. The function should calculate and display a classification report including precision, recall,...
```python import pandas as pd from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier def show_classification_report(df: pd.DataFrame) -> None: # Split the dataset into features and target features = df.drop(columns=...
magicoder
python
You are tasked with implementing a function to convert the linearization of a kimchi circuit polynomial into a printable string. The linearization is based on a specific evaluation domain and involves generating a set of linearization columns and constraints expressions. Your task is to create a function that takes the...
```rust pub fn linearization_strings<F: ark_ff::PrimeField + ark_ff::SquareRootField>( ) -> (String, Vec<(String, String)>) { let d1 = ark_poly::EvaluationDomain::<F>::new(1).unwrap(); let evaluated_cols = linearization_columns::<F>(None); let (linearization, powers_of_alpha) = constraints_expr(d1, false, N...
magicoder
rust
You are tasked with implementing a Python function that calculates the bounds of a given area based on the input parameters. The function should take four arguments: `width`, `height`, `margin`, and `action_metadata`. The `width` and `height` represent the dimensions of the area, while the `margin` indicates the margin...
```python from enum import Enum class ActionMetaData(Enum): NoMetaData = 0 # Add other action metadata if needed def bounds(width, height, margin, action_metadata): if action_metadata == ActionMetaData.NoMetaData: return (0, width - margin, height - margin) # Handle other action metadata cases...
magicoder
python
You are tasked with creating a Python class that manages a to-do list and contact list for a project management application. The class should have a method `solve` that takes in various parameters and performs operations based on the input. Your task is to implement the `solve` method of the class. The class should ha...
```python class ProjectManager: def __init__(self, task_list, contact_list, internal_constraint_list, rf_des=None, verbose=False): self.task_list = task_list self.contact_list = contact_list self.internal_constraint_list = internal_constraint_list self.rf_des = rf_des self.ve...
magicoder
python
You are tasked with creating a PHP class method that processes an email body to hide hidden mail fields using regular expressions. Your task is to implement the `hide_hidden_mail_fields_regex_callback` method within the given PHP class. The `hide_hidden_mail_fields_regex_callback` method should take a match as input a...
```php class EmailProcessor { private $mail_body; public function __construct($mail_body) { $this->mail_body = $mail_body; } public function getParsedMail() { return preg_replace_callback(WPCF7CF_REGEX_MAIL_GROUP, array($this, 'hide_hidden_mail_fields_regex_callback'), $this->mail_body...
magicoder
php
You are tasked with implementing a Python class that represents a deck of playing cards and provides various methods for manipulating and interacting with the deck. The class should support shuffling the deck, dealing a specified number of cards, and returning the number of cards remaining in the deck. Your task is to...
```python import random class PlayingCard: def __init__(self, suit, value): self.suit = suit self.value = value def __str__(self): return f"{self.value} of {self.suit}" class PlayingCardDeck: def __init__(self): suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] val...
magicoder
python
You are tasked with implementing a Python function that handles SSH client connections using the `paramiko` library. The function should establish a secure SSH connection to a specified hostname using a given username and password. Additionally, it should handle potential exceptions related to host key verification and...
```python import paramiko class RaiseUnknownHostKeyPolicy(paramiko.MissingHostKeyPolicy): def missing_host_key(self, client, hostname, key): raise paramiko.BadHostKeyException(hostname, key) class BadHostKeyError(Exception): def __init__(self, hostname, key, expected_key): self.hostname = host...
magicoder
python
You are tasked with creating a Python program to manage a playlist of audio files. Your program should be able to load, play, pause, resume, and stop audio files using the `pygame` library. The program should also allow the user to navigate through the playlist and play the next or previous audio file. Your program sh...
```python import pygame class AudioPlayer: def __init__(self): pygame.init() self.playlist = [] self.current_track_index = 0 self.paused = False def load_playlist(self, files): self.playlist = files def play(self): if self.playlist: pygame.mixer...
magicoder
python
You are tasked with creating a Python package manager tool that can handle dependencies and provide warnings for missing dependencies. Your tool should be able to import modules from the package and handle potential ImportError exceptions. Your task is to implement a function `import_package_module(package_name, modul...
```python import importlib import warnings class MissingDependencyWarning(Warning): pass def import_package_module(package_name, module_name): try: package = importlib.import_module(package_name) module = getattr(package, module_name) return module except ImportError: messa...
magicoder
python
You are tasked with implementing a function to retrieve a list of categories from a database based on a given parent category ID, sorting order, limit, and offset. The provided code snippet is a part of a larger codebase for a C++ application that interacts with a database using the C++ Database Connectivity (CppDB) li...
```cpp void retrieveCategories(int parentCategoryId, int sort, int limit, int offset, Vector<Category>& ret) { try { // Acquire a database session std::unique_ptr<DataSession> session = this->session(); // Construct and execute the database query Statement select(*session); ...
magicoder
cpp
You are given a parallelized code snippet that performs a matrix-vector multiplication using OpenMP directives. Your task is to understand the code and identify potential issues related to parallel execution. The code snippet is part of a larger program that performs matrix-vector multiplication using OpenMP for paral...
The code snippet provided uses OpenMP directives for parallel execution. However, there are potential issues related to data race and performance that need to be addressed. 1. Data Race: The use of `#pragma omp atomic` ensures that the updates to the result vector are performed atomically, preventing data race conditi...
magicoder
c
You are tasked with creating a module registration system for a university. The system should allow students to observe and register for different modules offered by the university. Each module has a unique code and a maximum capacity of students it can accommodate. The system should also keep track of the number of st...
```rust // Define a module struct to hold module information struct Module { code: String, max_capacity: usize, current_capacity: usize, } impl Module { // Create a new module with a unique code and maximum capacity fn new(code: String, max_capacity: usize) -> Module { Module { ...
magicoder
rust
You are tasked with creating a program that processes a list of GitHub repositories and calculates the total number of stars for each repository within a specified range. The program should also be able to filter repositories based on the number of stars and generate a report of repositories that fall within the specif...
To solve this problem, you can start by creating a Rust program that utilizes the GitHub API to fetch repository information and calculate the total number of stars for each repository within the specified range. Here's a high-level solution using the given code snippet as a starting point: ```rust use std::path::Path...
magicoder
rust
You are tasked with creating a web application for a university's student accommodation booking system. The code snippet provided is a part of the web application's view file written in PHP using the Yii framework. Your task is to implement a function that generates the HTML code for a form to allow students to book a...
```php function generateAccommodationBookingForm($options) { $title = isset($options['title']) ? $options['title'] : 'Accommodation Booking Form'; $model = isset($options['model']) ? $options['model'] : null; $html = '<div class="units-booked-by-students-create">'; $html .= '<h1>' . Html::encode($title...
magicoder
php
You are tasked with implementing a timer event handler that manages a composite disposable object in a multi-threaded environment. The `timer` object has a method `setEventHandler` which takes a closure as a parameter. Inside the closure, you need to check if a `compositeDisposable` object is disposed. If it is dispose...
```swift import Foundation class CompositeDisposable { private var disposables: [Disposable] = [] private let lock = NSLock() func addDisposable(_ disposable: Disposable) { lock.lock() disposables.append(disposable) lock.unlock() } func dispose() { lock.lock() ...
magicoder
swift
You are tasked with creating a Python class that integrates with a specific context plugin system. The provided code snippet is a simplified example of such a class. Your task is to expand upon this snippet and create a class that can be used to version-up workfiles in a hypothetical content management system. Your cl...
```python class IntegrateVersionUpWorkfile(api.ContextPlugin): """Save as new workfile version""" order = api.IntegratorOrder + 10.1 label = "Version-up Workfile" hosts = ["hiero"] optional = True def __init__(self, workfile): self.workfile = workfile def version_up(self): ...
magicoder
python
You are tasked with implementing a memory manager for a custom memory pool in C++. The memory manager should support allocating and deallocating memory blocks of varying sizes from a pre-allocated memory region. The memory manager should also handle fragmentation and reuse of freed memory blocks to minimize memory wast...
```cpp #include <iostream> #include <vector> #include <algorithm> class MemoryManager { private: struct MemoryBlock { size_t size; bool free; }; std::vector<MemoryBlock> memoryRegion; public: void initialize(size_t regionSize) { memoryRegion.clear(); memoryRegi...
magicoder
cpp
You are tasked with developing a JupyterHub configuration management system. Your system should be able to read a configuration file and apply the specified settings to the JupyterHub instance. The configuration file will contain settings for DockerSpawner, JupyterHub, and other related configurations. Your task is to ...
```python def apply_jupyterhub_config(config_file): with open(config_file, 'r') as file: config_settings = file.readlines() for setting in config_settings: exec(setting) # Example usage apply_jupyterhub_config('jupyterhub_config.py') ``` In the solution, the `apply_jupyterhub_config` function...
magicoder
python
You are given a singly linked list where each node contains an integer value. Write a function to reverse the linked list in place. The linked list is represented by the following class: ``` class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next ``` You need to imple...
```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def reverseLinkedList(head: ListNode) -> ListNode: prev = None current = head while current is not None: next_node = current.next current.next = prev prev = current ...
magicoder
python
You are tasked with implementing a function that processes a collection of frames to create an animated image. Each frame is represented by an object containing an image and a duration. The function should generate an animated image by repeating each frame's image a certain number of times based on its duration and ret...
```swift func generateAnimatedImage(frames: [Frame]) -> UIImage { var images: [UIImage] = [] var duration: TimeInterval = 0.0 for frame in frames { let image = UIImage(cgImage: frame.image) for _ in 0 ..< Int(frame.duration * 100.0) { images.append(image) // Add fill frames ...
magicoder
swift
You are given a code snippet that calculates the variable `thetap` based on the values of `Lz`, `L`, `t`, `vt`, `p`, `thetaz`, and the numpy library functions. Your task is to implement a function that replicates the behavior of the code snippet and returns the value of `thetap` given the input values. The code snippe...
```python import numpy as np def calculate_thetap(Lz, L, t, vt, p, thetaz): LR = Lz / L sinu = LR / np.sqrt(1. - LR**2) / np.tan(t) u = 0 if sinu > 1.: u = np.pi / 2. elif sinu < -1.: u = -np.pi / 2. else: u = np.arcsin(sinu) if vt > 0.: u = np.pi - u the...
magicoder
python
You are tasked with implementing a caching decorator in Python. A caching decorator is a higher-order function that can be used to cache the results of a function, thus avoiding redundant computations for the same input arguments. The provided code snippet serves as a starting point for creating the caching decorator. ...
```python import time import functools class CachingDecorator: def __init__(self, timeout=None, ignore=None, key=None): self.timeout = timeout self.ignore = ignore if ignore else [] self.key = key self.cache = {} def __call__(self, func): """Entry point. :arg ...
magicoder
python
You are tasked with creating a Python program to extract the text content from a given URL and perform specific text processing tasks. The program should retrieve the HTML content from the URL, extract the text, and then perform word frequency analysis and text manipulation. Your program should perform the following s...
```python import requests from bs4 import BeautifulSoup from collections import Counter import re from nltk.corpus import stopwords # Function to retrieve HTML content from a given URL def get_html_content(url): response = requests.get(url) return response.text # Function to extract text content from HTML usi...
magicoder
python
You are tasked with implementing a class to handle secondary location groups in a meteorological report parsing library. A secondary location group is a part of a weather report that provides additional information about a specific location. The class should support parsing, appending, and checking the result of append...
```cpp #include <string> #include <optional> namespace metaf { enum class ReportPart { RMK, ... }; // Other report parts omitted for brevity enum class AppendResult { APPENDED, NOT_APPENDED }; class SecondaryLocationGroup { public: static std::optional<SecondaryLocationGroup> parse(const std::string& group, Re...
magicoder
cpp
You are tasked with creating a program that can analyze the copyright information in a given file and extract the year and organization name. The copyright information is typically found at the beginning of the file as a comment block. The format of the comment block is as follows: ``` # Copyright <year> <organizati...
```python from typing import Tuple import re def extract_copyright_info(file_path: str) -> Tuple[str, str]: with open(file_path, 'r') as file: content = file.read() match = re.search(r'Copyright (\d{4}) (.+?)\n', content) if match: year = match.group(1) organization ...
magicoder
python
You are tasked with implementing a custom URI (Uniform Resource Identifier) class in Python. The URI class should support string representation, hashing, and equality comparison based on its attributes. Your URI class should have the following attributes: - `scheme`: The protocol or scheme of the URI (e.g., http, http...
```python import zlib class Uri: def __init__(self, scheme, host, path, query, fragment): self.scheme = scheme self.host = host self.path = path self.query = query self.fragment = fragment def get_url(self): url = f"{self.scheme}://{self.host}{self.path}" ...
magicoder
python
You are tasked with creating a Python function that generates convolutional neural network (CNN) layers based on a given convolution type. The function should take the convolution type as input and return the corresponding CNN layers. You are provided with a code snippet that sets random seeds for NumPy and PyTorch, a...
```python import torch import torch.nn as nn def return_conv_layers(conv_type): if conv_type == '512to256to64_1x1': conv = nn.Sequential( nn.Conv2d(512, 256, kernel_size=1), nn.ReLU(), nn.Conv2d(256, 64, kernel_size=1), nn.ReLU() ) return conv...
magicoder
python
You are tasked with implementing a system for creating different types of documents using the abstract factory design pattern. The system should support the creation of two types of documents: `Letter` and `Resume`. Each document type has its own set of attributes and functionalities. Your task is to implement the abs...
```python from abc import ABC, abstractmethod # Abstract Product Interfaces class Letter(ABC): @abstractmethod def write(self, content: str) -> None: pass class Resume(ABC): @abstractmethod def format(self) -> None: pass # Concrete Product Classes class FormalLetter(Letter): def w...
magicoder
python
You are tasked with creating a Python script that monitors a directory for any new or modified files and logs the changes to a specified log file. The script should utilize the `watchdog` library to achieve this functionality. Your script should accept the following command-line arguments: 1. The directory to monitor....
```python import sys import time import logging from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class FileChangeHandler(FileSystemEventHandler): def __init__(self, log_file): super().__init__() self.log_file = log_file def on_any_event(self, event): ...
magicoder
python
You are tasked with implementing a Python class that represents a quantum circuit element. The quantum circuit element will be a part of a larger quantum circuit simulation, and it will have specific properties and methods to interact with other elements in the circuit. Your task is to create a class called `QuantumEl...
```python class QuantumElement: def __init__(self, name, type): self.name = name self.type = type def apply(self, quantum_state): raise NotImplementedError("Subclasses must override apply method") def __str__(self): return f"{self.name} ({self.type})" class BravyiKitaevEl...
magicoder
python
You are tasked with implementing a Python class for object detection using the Faster R-CNN (Region-based Convolutional Neural Network) model. The provided code snippet is a partial implementation of the class, and your task is to complete the implementation by adding the `infer` method. The `__init__` method initiali...
```python def infer(self, image, threshold): # Perform object detection using the Faster R-CNN model detections = self.model.detect_objects(image) # Filter detections based on the threshold filtered_detections = [(obj, score) for obj, score in detections if score >= threshold] return filtered_dete...
magicoder
python
You are tasked with implementing a simple tokenizer and lexer for a custom programming language. The tokenizer should take a string of code as input and split it into tokens, while the lexer should analyze these tokens and categorize them into different types. Your task is to complete the implementation of the `Tokeni...
```python import re class Tokenizer: def tokenize(self, code): tokens = re.findall(r'\bif\b|\belse\b|\bwhile\b|\bfor\b|\b[a-zA-Z][a-zA-Z0-9]*\b|\+|-|\*|/|=|\(|\)|\{|\}|\;', code) return tokens class Lexer: def analyze(self, tokens): categorized_tokens = [] for token in tokens: ...
magicoder
python
You are given a list of integers representing the heights of buildings in a city skyline. Your task is to write a function that calculates the total area of the skyline when viewed from one side. The skyline is formed by the buildings and the spaces between them. The width of each building is 1 unit. Write a function ...
```python def calculateSkylineArea(buildings): if not buildings: return 0 total_area = 0 stack = [] for i in range(len(buildings)): while stack and buildings[i] >= buildings[stack[-1]]: top = stack.pop() if stack: width = i - stack[-1] - 1 ...
magicoder
python
You are tasked with implementing a snapshot reconciler for a JavaScript application. The reconciler is responsible for comparing a given value with a snapshot (sn) and updating the value based on any differences found. The reconciler function is registered with a specific priority and is called when a snapshot matches ...
```javascript function reconcilePlainObjectSnapshot(value, sn, modelPool) { // Check if the snapshot is a plain object if (isPlainObject(sn)) { // Iterate through the keys of the snapshot for (const key in sn) { // Check if the key exists in the value if (sn.hasOwnProperty(key) && value.hasOwnPr...
magicoder
javascript
You are working on a version control system and need to resolve ambiguities between paths and other arguments. You have a script that creates a new file called "master" and another file with a name stored in the variable `$commit_id2`. These files are added to the version control system using the `got add` command and ...
```bash #!/bin/bash # Function to resolve ambiguities between paths and other arguments resolve_ambiguities() { local testroot=$1 local commit_id2=$2 echo "new file called master" > $testroot/wt/master echo "new file called $commit_id2" > $testroot/wt/$commit_id2 (cd $testroot/wt && got add master...
magicoder
shell
You are tasked with implementing a custom extension method for the `IEnumerable<T>` interface in C#. The method should return true if all elements in the collection satisfy a given condition, and false otherwise. The method signature should be as follows: ```csharp public static bool AllSatisfy<T>(this IEnumerable<T> ...
```csharp using System; using System.Collections.Generic; public static partial class MaestriaExtensions { /// <summary> /// Check if all elements in the collection satisfy the given condition /// </summary> /// <typeparam name="T">The type of elements in the collection</typeparam> /// <param name=...
magicoder
csharp
You are tasked with creating a Python class that validates alphanumeric strings using regular expressions. Your task is to implement a class `AlphanumericValidator` that provides a method `validate` to check if a given string contains only alphanumeric characters. Your `AlphanumericValidator` class should have the fol...
```python import re class AlphanumericValidator: def __init__(self, pattern): self.pattern = pattern def validate(self, input_string): return bool(re.fullmatch(self.pattern, input_string)) # Example usage: # Create an instance of AlphanumericValidator with a pattern validator = AlphanumericVa...
magicoder
python
You are tasked with creating a CSS class generator function that takes in a set of parameters and outputs a CSS class string based on those parameters. The function should handle various CSS properties and their values to generate a valid CSS class string. Your task is to implement the `generateCSSClass` function, whi...
```javascript function generateCSSClass(cssProperties) { let cssClass = ''; for (const property in cssProperties) { if (typeof cssProperties[property] === 'object') { cssClass += `${property} { ${generateCSSClass(cssProperties[property])} } `; } else { cssClass += `${property}: ${cssProperties[p...
magicoder
javascript
You are tasked with creating a program that processes a given software license agreement to extract specific permissions granted within the agreement. The license agreement is provided as a string, and the permissions are defined by the text following the "Permission is hereby granted" statement. Your program should ex...
```python import re def extractPermissions(licenseAgreement): permission_start = "Permission is hereby granted" start_index = licenseAgreement.find(permission_start) permissions = licenseAgreement[start_index + len(permission_start):].strip() return re.findall(r'[\w\s,/&]+', permissions) # Test the fu...
magicoder
python
You are tasked with implementing a program that processes a video stream to detect and annotate objects using a pre-trained neural network model. The provided code snippet is a part of this program and uses the OpenCV library to perform object detection and annotation. The `cap.read()` function reads a frame from the v...
```python import cv2 def process_video_stream(cap, net, classNames, threshold): while True: success, img = cap.read() if not success: print("Failed to read frame from the video stream.") break classIds, confs, bbox = net.detect(img, confThreshold=threshold) ...
magicoder
python
You are tasked with implementing a custom integer caching mechanism in Java. The goal is to optimize memory usage by reusing integer objects within a specific range. The provided code snippet contains a partial implementation of the caching mechanism using a factory class and a custom integer class. Your task is to co...
```java // MyInteger class representing a custom integer object class MyInteger { private int value; public MyInteger(int value) { this.value = value; } public int getValue() { return value; } } // MyIntegerFactory class managing the caching of MyInteger objects class MyIntegerFac...
magicoder
java
You are tasked with implementing a Python function that calculates the partitioned norm of a given vector. The partitioned norm of a vector is a generalization of the Euclidean norm, where the vector is divided into multiple partitions, and the norm is calculated for each partition separately. The partitioned norm is t...
```python from typing import List from .partitioned_norm import calculate_norm def partitioned_norm(vector: List[float], partition_size: int) -> float: partitioned_norms = [] for i in range(0, len(vector), partition_size): partition = vector[i:i+partition_size] partition_norm = calculate_norm(p...
magicoder
python
You are tasked with implementing a multi-threaded file processing system using Rust's standard library. The system will involve managing a collection of file paths and tracking the progress of reading and processing these files concurrently. You are provided with a code snippet that initializes two static lazy-initial...
```rust use std::sync::{Arc, Mutex, RwLock}; use std::path::PathBuf; mod hash; mod status_info; mod status_read; pub use hash::*; use status_info::StatusInfo; lazy_static! { static ref CIPHER_FILES: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new()); static ref CIPHER_PROGRESS: Mutex<Vec<Arc<RwLock<ReadItem>>> = M...
magicoder
rust