query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are working on a Django project that involves managing user data. The project has a `users` app with a migration file named `0009_auto_20201021_2108.py`. The migration file contains a `Migration` class that inherits from `migrations.Migration`. Within this class, there is a `dependencies` attribute that lists the d...
```python # Generated by Django 3.1.2 on <current_date_time> from django.db import migrations, models import uuid def populate_uuid(apps, schema_editor): User = apps.get_model('users', 'User') for user in User.objects.all(): user.uuid = uuid.uuid4() user.save() class Migration(migrations.Mi...
magicoder
python
You are tasked with implementing a configuration management system for a web application using Python and Flask. The given code snippet is a part of the configuration setup for the application. The application's configuration is loaded based on the environment and is then customized further. Additionally, a logging han...
```python import os import sys import logging import sentry_sdk from flask import Flask app = Flask(__name__) if os.environ.get("FLASK_ENV") == "production": app.config.from_object("doppelkopf.config.ProductionConfig") else: app.config.from_object("doppelkopf.config.DevelopmentConfig") app.logger.addHandler(...
magicoder
python
You are tasked with implementing a function to manage a database session in a multi-threaded environment. The function `interruptor` is responsible for creating a new database session and adding a participant to it. However, the function needs to be modified to ensure thread safety and proper management of the database...
To address the requirements and ensure thread safety in the `interruptor` function, the following modifications can be made: ```python import threading # Create a lock to ensure atomicity and thread safety session_lock = threading.Lock() def interruptor(): if not interrupted: # Acquire the lock before cr...
magicoder
python
You are tasked with creating a Python function that simulates the download of a file from a given URL. Your function should take in the URL of the file to be downloaded, the name of the output file where the downloaded data will be saved, and a boolean flag indicating whether to show a progress bar during the download....
```python import requests from tqdm import tqdm def download_file(url: str, output_file: str, show_progress_bar: bool) -> None: response = requests.get(url, stream=True) total_size = int(response.headers.get('content-length', 0)) with open(output_file, 'wb') as file: if show_progress_bar: ...
magicoder
python
You are tasked with implementing a function to adapt a collection view to display a grid of items with a specific number of rows and grid line spacing. The provided code snippet demonstrates the usage of the function `adaptBeautifulGrid` to achieve this. The `rowStepper` and `spaceStepper` are UI components that allow ...
```swift func adaptBeautifulGrid(_ rows: Int, gridLineSpace: CGFloat) { // Implementation of adaptBeautifulGrid function // Adjust the collection view to display a grid with the specified number of rows and grid line spacing // Example implementation: // collectionView.layout.minimumLineSpacing = gridLi...
magicoder
swift
You are tasked with creating a custom registration system for various data manipulation functions in R using the dplyr package. The registration system should allow users to register new functions and retrieve a list of registered functions. The registration system should support both time and date manipulation functio...
```R # Define the custom registration class RegistrationSystem <- R6Class("RegistrationSystem", public = list( registeredFunctions = list(), # Method to register a new function registerFunction = function(func) { if (is.function(func)) { self$registeredFunctions <- c(self$registeredFunc...
magicoder
r
You are tasked with implementing a function that manipulates strings in Rust. Your task is to create a function that takes a string as input and returns a new string with the first letter of each word capitalized. You should ignore any leading or trailing white spaces and ensure that the function handles both lowercase...
```rust fn capitalize_words(input: &str) -> String { input.split_whitespace() .map(|word| { let mut chars = word.chars(); match chars.next() { None => String::new(), Some(first_char) => first_char.to_uppercase() .chain(chars) ...
magicoder
rust
You are working on a Python application that requires configuration settings to be stored in a separate file. The settings include API keys, file paths, and database connection strings. You want to create a module to manage these settings and ensure that they are securely stored and easily accessible throughout the app...
```python import configparser class ConfigManager: def __init__(self, config_file='config.ini'): self.config = configparser.ConfigParser() self.config.read(config_file) def get_setting(self, section, key): return self.config.get(section, key) def update_setting(self, section, key,...
magicoder
python
You are tasked with implementing a function that generates a unique identifier (UUID) for an image file and returns an object containing the UUID along with other image properties. The function should take in an object of type `ImageProps` and return an object of type `ImageWithUuid`. The UUID should be generated using...
```typescript const deterministicUUID = (file: Buffer): string => { // Assume this function is provided and returns a unique UUID for the given buffer // Implementation details are not necessary for this problem return "generated-uuid"; // Replace with actual implementation } const imageUuid = ({ file, ...rest }...
magicoder
typescript
You are tasked with implementing a TypeScript interface and a class that implements the interface. The interface represents a service for managing tasks in a project management tool. Your goal is to create the interface and a class that adheres to it. The interface `IRosService` is defined as follows: ```typescript im...
```typescript import { IRosService, TaskName } from './IRosService'; class RosService implements IRosService { private tasks: Map<string, TaskName>; constructor() { this.tasks = new Map(); } async createTask(taskName: string, isBuildCommand?: boolean): Promise<void> { this.tasks.set(t...
magicoder
typescript
You are tasked with creating a Python function that calculates the average of a list of numbers. Your function should take a list of numbers as input and return the average of those numbers. You should also write unit tests to ensure the correctness of your function. Write a Python function `calculate_average(numbers)...
```python import unittest def calculate_average(numbers): if not numbers: return 0 return sum(numbers) / len(numbers) class TestCalculateAverage(unittest.TestCase): def test_positive_integers(self): self.assertEqual(calculate_average([1, 2, 3, 4, 5]), 3.0) def test_negative_integers(s...
magicoder
python
You are tasked with implementing a key binding system for a game. The game has a feature where players can flip blueprints, and you need to create a key binding for this action. The provided code snippet shows a static variable `Blueprint_Flip` of type `KeyBindingDef`, which is intended to represent the key binding for...
```csharp using System; public class KeyBindingDef { public int KeyCode { get; set; } public string ActionName { get; set; } // Other properties related to key binding public KeyBindingDef(int keyCode, string actionName) { KeyCode = keyCode; ActionName = actionName; } } public...
magicoder
csharp
You are tasked with creating a shell script that automates the process of opening a specific file in a given environment. The script should source two other shell scripts, `path.sh` and `open.sh`, to set up the necessary environment variables and functions before opening the file. Your task is to write a shell script ...
```bash #!/bin/bash set -eu # Check if EOPEN_ROOT environment variable is set if [ -z "${EOPEN_ROOT-}" ]; then echo "Error: EOPEN_ROOT environment variable is not set." >&2 exit 1 fi # Source the path.sh script if ! source "$EOPEN_ROOT/cygwin/path.sh"; then echo "Error: Failed to source path.sh script." >&2 e...
magicoder
shell
You are given two arrays, `a` and `b`, both of length `n`. Your task is to find the maximum value of `k` such that the sum of the first `k` elements in array `a` is equal to the sum of the first `k` elements in array `b`. If there is no such `k`, the output should be 0. Write a function `max_equal_sum_subarray` that t...
```python from typing import List def max_equal_sum_subarray(a: List[int], b: List[int]) -> int: n = len(a) a_sum, b_sum = 0, 0 max_k = 0 prefix_sums = [[0, 0] for _ in range(n + 1)] # prefix_sums[i][0] stores the sum of first i elements of a, prefix_sums[i][1] stores the sum of first i elements of b ...
magicoder
python
You are tasked with creating a function that finds the first existing file in a given directory with a specific naming pattern. The function should take in the directory path and an array of file extensions, and return the path of the first existing file that matches the naming pattern. The naming pattern for the file...
```javascript const path = require('path'); const fs = require('fs'); function findExistingFile(directory, extensions) { let indexPath = ''; for (let i = 0, len = extensions.length; i < len; i++) { indexPath = path.resolve(directory, `index.${extensions[i]}`); if (fs.existsSync(indexPath)) return indexPath...
magicoder
javascript
You are tasked with creating a Python function that takes a list of URL patterns and returns a dictionary mapping the URL names to their corresponding view classes. Each URL pattern is represented as a tuple containing the URL path, the view class, and the name of the URL. Write a function `extract_url_mappings` that ...
```python def extract_url_mappings(url_patterns): url_mappings = {} for url_path, view_class, url_name in url_patterns: url_mappings[url_name] = view_class return url_mappings ``` The `extract_url_mappings` function iterates through the list of URL patterns and constructs a dictionary where the URL...
magicoder
python
You are tasked with implementing a RESTful API endpoint for deleting groups in a group management system. The API endpoint should handle bulk deletion of groups and return appropriate status codes and messages based on the outcome of the deletion process. You are given a Python code snippet that includes a dictionary ...
To implement the bulk deletion of groups and handle the POST request for the API endpoint, the following logic can be used: ```python def POST_api_groups_delete(request): # Extract group IDs from the request group_ids = request.data.get('group_ids', []) # Perform bulk deletion of groups deleted_groups...
magicoder
python
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should keep track of the account holder's name and account balance. Create a Python class `BankAccount` wi...
```python class BankAccount: def __init__(self, account_holder): self.account_holder = account_holder self.balance = 0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount <= self.balance: self.balance -= amount else: ...
magicoder
python
You are tasked with creating a Python program that interacts with the Strava API to retrieve and display information about a user's activities. Strava is a popular platform for tracking athletic activities such as running, cycling, and swimming. The program should authenticate with the Strava API using OAuth 2.0 and th...
```python import os import httpx from urllib.parse import urlencode from http.server import HTTPServer, BaseHTTPRequestHandler import webbrowser import json # Constants STRAVA_AUTHORIZATION_URL = "https://www.strava.com/oauth/authorize" STRAVA_API_BASE_URL = "https://www.strava.com/api/v3" DEFAULT_ACTIVITY_LABEL = "NO...
magicoder
python
You are tasked with implementing a class method that processes XML data and optionally draws the parsed information. The method should be able to handle both file paths and file-like objects as input. Your task is to complete the implementation of the `__init__` method in the given class, ensuring that it properly init...
```python class XMLProcessor: def __init__(self, xml_path=None, fp=None, draw=False): if xml_path and fp: self.xml_path = xml_path elif xml_path: self.xml_path = xml_path elif fp: self.xml_path = None # or set to default XML path else: ...
magicoder
python
You are tasked with creating a script to automate the setup and configuration of a user for a monitoring tool on a Linux system. The script should check if the user "vsphere-monitor" exists and, if not, create the user with specific settings. Additionally, the script should handle moving configuration files into place ...
```bash #!/bin/bash # Check if the user vsphere-monitor exists if ! getent passwd vsphere-monitor >/dev/null; then # Create vsphere-monitor user with specific settings sudo useradd -r -s /usr/bin/nologin vsphere-monitor fi # Move configuration files into place # Replace /path/to/source/config with the actual sour...
magicoder
shell
You are working on a computer graphics project and need to implement a function to calculate material properties for rendering. The given code snippet is part of a larger function that computes anisotropy, roughness, and coating weights based on input parameters. Your task is to complete the function by implementing th...
```cpp // Complete the function to calculate material properties for rendering void CalculateMaterialProperties(float u, float v, float ks, Vector3 fixedDir) { const float u2 = u * u; const float v2 = v * v; float anisotropy, roughness, wCoating, wBase; // Calculate anisotropy and roughness based on th...
magicoder
cpp
You are tasked with implementing a simple task management system using Python and FastAPI. The provided code snippet is a part of the main application setup, where a router for handling tasks is being included. Your task is to complete the implementation of the task router and create endpoints for managing tasks. Your...
```python from fastapi import APIRouter, HTTPException from typing import List from .models import Task task_router = APIRouter() tasks = [] @task_router.get("/", response_model=List[Task]) async def get_tasks(): return tasks @task_router.post("/", response_model=Task) async def create_task(task: Task): tas...
magicoder
python
You are tasked with implementing a function that calculates the total length of all the lines in a given SVG (Scalable Vector Graphics) code snippet. The SVG code snippet consists of multiple `<line>` elements, each specifying the coordinates and attributes of a line. The function should parse the SVG code and return t...
```javascript function calculateTotalLineLength(svgCode) { const lineRegex = /<line x1="(\d*\.?\d+)" y1="(\d*\.?\d+)" x2="(\d*\.?\d+)" y2="(\d*\.?\d+)" .*\/>/g; let totalLength = 0; let match; while ((match = lineRegex.exec(svgCode)) !== null) { const x1 = parseFloat(match[1]); const y1 = parseFloat(ma...
magicoder
javascript
You are tasked with implementing a function that extracts the text content within HTML tags. Your function should take an HTML string and return a list of all the text content within the tags. The HTML string may contain multiple tags and nested tags. The text content within the tags should be returned in the order the...
```python from typing import List from html.parser import HTMLParser class HTMLTextExtractor(HTMLParser): def __init__(self): super().__init__() self.text_content = [] def handle_data(self, data): self.text_content.append(data.strip()) def extract_text_from_html(html: str)...
magicoder
python
You are tasked with implementing a class method for a quantum computing simulator. The method, `applyH`, is responsible for recursively calculating the action of the Hadamard gate raised to the power of `k` on a given input vector `x`. The Hadamard gate, denoted as H, is a fundamental quantum gate used in quantum compu...
```python import os import numpy as np class QuantumSimulator: def applyH(self, x, k, _depth=0): """ Recursive calculation of H_k x, for any x. :param x: Input vector on which the Hadamard gate is to be applied. :type x: numpy.ndarray :param k: The power to...
magicoder
python
You are tasked with creating a function that processes a message and grants access based on the message content. The message contains subject, object, action, and namespace IDs. Your task is to implement the `grant_access` function that takes in the message and grants access based on certain conditions. The function sh...
```rust use diesel::prelude::*; use crate::models::Message; use crate::schema::granted_access; fn grant_access(msg: &Message, conn: &Connection) -> Result<bool, Error> { // Implement the logic to grant access based on the message content and any additional conditions let granted = // Your logic to determine ac...
magicoder
rust
You are tasked with implementing a file loading functionality within a pipeline state for Xcode projects. The given code snippet is part of a Swift application and represents a function that is intended to be run within a pipeline state. The `run` function takes a `PipelineState` object as a parameter and is responsibl...
```swift // Define the Xcode project class class XcodeProject { // Method to load files for the project func loadFiles(context: PipelineState) { // Implementation to load files for the project // ... } } // Define the PipelineState class class PipelineState { var xcodeProjects: [XcodePr...
magicoder
swift
You are tasked with implementing a flashcard management system using Python classes and methods. The system should allow users to create, practice, and track their progress with flashcards. Each flashcard has fields for "front" (the question), "back" (the answer), and "user" (the user who created the flashcard). Additi...
```python from datetime import datetime, timedelta class FlashCard: def __init__(self, front, back, user): self.front = front self.back = back self.user = user self.next_practice = datetime.now() self.times_practiced = 0 self.easy_factor = 2.5 # Initial easy factor ...
magicoder
python
You are tasked with creating a Python function that parses metadata from a given Python package setup file and returns a dictionary containing the extracted metadata. The setup file follows the format of a typical `setup.py` file used in Python projects. The metadata includes version, description, author, author email,...
```python def parse_setup_file(file_path: str) -> dict: metadata = {} with open(file_path, 'r') as file: for line in file: if '=' in line: key, value = line.strip().split('=') key = key.strip() value = value.strip().rstrip(',') ...
magicoder
python
You are tasked with implementing a text editor component that supports adding and removing document listeners. The text editor should have the ability to notify its listeners when the document is modified. Your task is to design a class that represents the text editor and its associated listeners. Your class should ha...
```java import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.L...
magicoder
java
You are tasked with implementing a Python class that simulates a simple text-based adventure game. The game will involve navigating through different rooms, interacting with objects, and solving puzzles. Your class should provide methods for moving between rooms, examining objects, and picking up items. Your task is t...
```python class AdventureGame: def __init__(self, initial_room, available_rooms): self.current_room = initial_room self.available_rooms = available_rooms self.player_inventory = [] def move_to_room(self, direction): adjacent_room = self.current_room.get_adjacent_room(direction) ...
magicoder
python
You are tasked with implementing a security checker for a web application that handles orders. The given code snippet is part of a method responsible for setting the visibility of a component based on the security rules defined for the order line. Your task is to complete the implementation of the `GetSecurityChecker` ...
```csharp public class UblEntityResolvingStrategy { // Other methods and properties public Func<Order, bool> GetSecurityChecker() { // Implement the security checker logic based on the provided requirements return (order) => { // Example: Check if the current user has pe...
magicoder
csharp
You are tasked with implementing a class for solving the Stokes equation using the sin-cos method. The Stokes equation is a system of partial differential equations that describes the motion of a viscous fluid. The sin-cos method is a spectral method used to solve partial differential equations by representing the solu...
```python class Stokes_SinCos1: """ The sin cos test case 1. """ def __init__(self, es): super(Stokes_SinCos1, self).__init__(es) self._es_.standard_properties.name = 'Stokes-sin-cos-1' def initialize_grid(self, nx, ny): # Add code to initialize the grid for the sin-cos meth...
magicoder
python
You are tasked with implementing a program that processes a list of compute template operations. Each operation is represented by a string in the format "[END operation_name]". Your goal is to extract the unique operation names from the list and return them in lexicographically sorted order. Write a function `extract_...
```python from typing import List def extract_operations(operations: List[str]) -> List[str]: unique_operations = set() for operation in operations: operation_name = operation.split("[END ")[1].split(" ]")[0] unique_operations.add(operation_name) return sorted(list(unique_operations)) ``` T...
magicoder
python
You are tasked with implementing a function that converts a field element into a byte array and then writing test cases to verify its correctness. The field element is represented as an array of integers, and the byte array should be created by converting each integer into its corresponding byte representation. The fun...
```javascript /** * Converts a field element into a byte array based on the specified byte order. * @param {number[]} fieldElement - Array of integers representing the field element. * @param {boolean} [littleEndian=false] - Boolean indicating the byte order (default: false for big-endian). * @returns {number[]} - ...
magicoder
javascript
You are tasked with creating a Java class that interacts with a database to perform CRUD (Create, Read, Update, Delete) operations on a "Cliente" entity. The "Cliente" entity is represented by the `Cliente` class in the `com.jacksonf.dto` package. The database interaction is handled by the `CrudDB` class in the `com.ja...
```java import com.jacksonf.dto.Cliente; import com.jacksonf.service.CrudDB; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class ClienteDAO { private CrudDB crudDB; // Constructor to initialize the CrudDB instance public Clie...
magicoder
java
You are tasked with implementing a Python decorator that measures the execution time of a function and logs the result. The decorator should use the `time` module to measure the elapsed time and the `logging` module to log the result. Create a decorator function called `measure_time` that takes a function as input and...
```python import time import logging from functools import wraps logging.basicConfig(level=logging.INFO) def measure_time(func): @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() execution_time = end_time -...
magicoder
python
You are tasked with implementing a generic method that checks if the result of a given function is greater than a specified lower limit. The method should throw an exception if the result is not greater than the lower limit. You are provided with the following code snippet as a reference: ```csharp public static clas...
```csharp public static void BeGreater<T>(Func<T> argumentFunc, T lowerLimit) where T : IComparable { T result = argumentFunc(); if (result.CompareTo(lowerLimit) <= 0) { throw new ArgumentException("The result must be greater than the specified lower limit."); } } ``` The `BeGreater` method fir...
magicoder
csharp
You are tasked with creating a Python program that will recursively search for all files with a specific file extension within a given directory and its subdirectories. Your program should take in the directory path and the file extension as input and return a list of all the file paths that match the given file extens...
```python import os def find_files_by_extension(directory, file_extension): file_paths = [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith(file_extension): file_paths.append(os.path.join(root, file)) return file_paths # Example usage di...
magicoder
python
You are tasked with implementing a peer management system for a network simulation. The system keeps track of various statistics and parameters related to the network and its peers. The provided code snippet is a part of the implementation and includes a method to add a new peer to the system. The system maintains the ...
```rust impl PeerManagementSystem { pub fn add_peer(&mut self) { // Increment the network size by 1 self.network_size += 1.0; // Update the maximum age based on the network size self.max_b_age = Age::from(cmp::max(1, self.network_size.ln().ln().ceil() as u8)); // Update the...
magicoder
rust
You are tasked with creating a program to parse and extract information from HTML code containing dropdown menu items. The HTML code represents a navigation bar with dropdown menus, and each dropdown menu contains a list of links. Your task is to extract the text and URLs of the dropdown menu items and their correspond...
```python from bs4 import BeautifulSoup def extractDropdownMenuItems(htmlCode): soup = BeautifulSoup(htmlCode, 'html.parser') dropdown_items = {} dropdown_toggle = soup.find('a', class_='dropdown-toggle') if dropdown_toggle: dropdown_text = dropdown_toggle.get_text(strip=True) dropdown_...
magicoder
python
You are tasked with implementing a function to analyze free/busy time blocks in a given list. The list represents a series of time slots, and your function should identify contiguous blocks of free time within the list. You are provided with a code snippet that initializes a database connection and retrieves the curre...
```python from typing import List, Tuple from datetime import datetime def find_free_blocks(time_slots: List[Tuple[datetime, datetime]]) -> List[Tuple[datetime, datetime]]: free_blocks = [] start_time = time_slots[0][0] end_time = time_slots[0][1] for slot in time_slots[1:]: if slot[0] > end_t...
magicoder
python
You are tasked with implementing a function to calculate the vapor pressure deficit (VPD) in a greenhouse environment. VPD is a measure of the difference between the amount of moisture in the air and how much moisture the air can hold when it is saturated. It is an important metric for understanding plant transpiration...
```rust fn calculate_vpd(temperature: f64, relative_humidity: f64, atmospheric_pressure: f64) -> f64 { let es = saturation_vapor_pressure(temperature); let ea = actual_vapor_pressure(relative_humidity, atmospheric_pressure); es - ea } fn saturation_vapor_pressure(temperature: f64) -> f64 { 610.78 * 2.7...
magicoder
rust
You are tasked with implementing a function to decode a byte array and extract specific information from it. The function `decode` takes a reference to a byte array `data` and returns a tuple containing the decoded information. The byte array `data` contains structured data in a specific format. The format of the byte...
```rust // Define the EventType enum representing different event types enum EventType { Type1, Type2, Type3, // Add more event types as needed } // Implement the decode function to extract information from the input byte array pub fn decode<'a>(data: &'a [u8]) -> (EventType, u32, &'a [u8], &'a [u8]) {...
magicoder
rust
You are tasked with creating a Python function that processes parameters for a custom Ansible lookup plugin called `keepass_http_password`. The function should handle different parameter types and extract a URL from the parameters if it is not explicitly provided. Write a Python function `process_params` that takes in...
```python class AnsibleParserError(Exception): pass def process_params(term, params): if not isinstance(term, (str, int, float, list, dict)): raise AnsibleParserError("Unsupported parameter type '{}' passed to keepass_http_password lookup.".format(type(term))) url = params.get('url', None) if...
magicoder
python
You are tasked with simulating the behavior of a space shuttle ejection system. The ejection process involves waiting for a random amount of time before the ejection sequence is initiated. Your goal is to implement a Java program that models this behavior using object-oriented principles and multithreading. You are pr...
```java import java.util.Random; class EjectionSystem implements Runnable { private String shuttleName; private Random random; public EjectionSystem(String shuttleName) { this.shuttleName = shuttleName; this.random = new Random(); } public void logInfo(String message) { Sy...
magicoder
java
You are tasked with creating a Python function that generates a directed acyclic graph (DAG) for a data pipeline. The DAG should have specific configurations and attributes based on the given code snippet. Your function should accept parameters for the DAG ID, schedule interval, and tags, and should incorporate the pro...
```python from datetime import timedelta from airflow import DAG def generate_data_pipeline_dag(dag_id, schedule_interval, tags): default_args = { 'retries': 1, 'retry_delay': timedelta(minutes=1), 'catchup': False, 'max_active_runs': 1 } dag = DAG( dag_id=dag_id, ...
magicoder
python
You are tasked with implementing a Python class that represents a code repository. The class should have a method that takes an input string and returns a modified version of the string along with the source codes stored in the class instance. You need to implement the `CodeRepository` class with the following methods...
```python from typing import List, Tuple class CodeRepository: def __init__(self): self._source_codes = [] def add_source_code(self, code: str): self._source_codes.append(code) def modify_and_return(self, input_string: str) -> Tuple[str, List[str]]: modified_string = input_string ...
magicoder
python
You are tasked with implementing a method to validate and process user input for a command-line application. The application takes command-line arguments and performs specific actions based on the input. The code snippet provided is a part of the input processing logic. The `args` array contains the command-line argume...
```java public class InputProcessor { public void validateAndProcessInput(String[] args, Player p) { if (args.length == 1) { HelpPageListener.sendMessage(p, 0); } else if (args.length > 1) { if (Math.isInt(args[1])) { // Perform necessary processing for intege...
magicoder
java
You are tasked with implementing a function that processes a list of room sagas and extracts specific information from them. A room saga is represented as an object with the following structure: ```typescript interface RoomSaga { name: string; actionType: string; timeout: number; channel: string; } ``` The `nam...
```typescript interface RoomSaga { name: string; actionType: string; timeout: number; channel: string; } interface ProcessedRoomSagas { totalSagasWithTimeoutGreaterThan1000: number; uniqueActionTypes: string[]; channelsBySaga: { [key: string]: string[] }; } function processRoomSagas(roomSagas: RoomSaga[...
magicoder
typescript
You are tasked with creating a Python function that processes a given mesh file and extracts specific information about the mesh elements. The mesh file is in the Fluent format and contains information about the elements' types (triangles, quadrilaterals, tetrahedra, or hexahedra). Your function should read the mesh fi...
```python import fvm.fvmbaseExt as fvmbaseExt import fvm.importers as importers import fvm.fvmparallel as fvmparallel from mpi4py import MPI from FluentCase import FluentCase from optparse import OptionParser etype = { 'tri' : 1, 'quad' : 2, 'tetra' : 3, 'hexa' : 4 } def count_...
magicoder
python
You are tasked with creating a Java annotation processor that processes annotations on classes and generates a report based on the annotations found. The provided code snippet shows the definition of an annotation interface with two elements: `type()` of type `ModuleType` with a default value of `ModuleType.Hidden`, an...
```java // Define the ModuleType enum public enum ModuleType { Hidden, Visible, Internal } // Define the annotation interface import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ModuleInfo { ModuleType type() default ModuleType.Hidden; String info...
magicoder
java
You are tasked with creating a Django REST framework view for a new feature in an e-commerce platform. The platform needs a view to list all the Simple Product Units (SPUs) along with their specifications. You are required to implement the view using Django REST framework's ListAPIView and ensure that only admin users ...
```python from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAdminUser from rest_framework import status from rest_framework.response import Response from goods.models import SPU, SPUSpecification from meiduo_admin.serializers.spus import SPUSimpleSerializer, SPUSpecSerializer c...
magicoder
python
You are tasked with implementing a pagination utility for handling HIPAA (Health Insurance Portability and Accountability Act) data in a Python web application. The provided code snippet is a partial implementation of a `HipaaDataHandler` class that inherits from `BaseHandler`. The `get` method is decorated with `pagin...
```python class HipaaDataHandler(BaseHandler): @pagination_util def get(self, *args, **kwargs): page_number = int(self.get_argument('page', default=1, strip=True)) page_size = int(self.get_argument('page_size', default=10, strip=True)) key = self.get_argument('key', default=None, strip=...
magicoder
python
You are tasked with implementing a Huffman encoding algorithm to compress and decompress data. Huffman encoding is a widely used technique for lossless data compression. In this problem, you are required to write a Python class that can encode and decode a given input string using Huffman coding. Your task is to compl...
```python class HuffmanNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None class HuffmanEncoder: def __init__(self): self.root = None self.codes = {} def build_huffman_tree(self, frequency_map): ...
magicoder
python
You are tasked with creating a Python function that extracts information from a Facebook API response. The function should take the API response as input and return a dictionary containing specific details from the response. The API response is obtained by sending a GET request to the Facebook Graph API. The response ...
```python import requests import json def extract_facebook_post_details(api_response): parsed_data = json.loads(api_response) post_message = parsed_data['data'][0]['message'] if 'message' in parsed_data['data'][0] else '' # Truncate post message if it contains more than 4 words post_words = p...
magicoder
python
You are tasked with implementing a quantum circuit simulator using the ProjectQ library. The ProjectQ library provides a high-level interface for quantum programming and allows for the simulation of quantum circuits on classical hardware. Your goal is to create a Python class that encapsulates the functionality of a qu...
```python from projectq import MainEngine from projectq.ops import H, X, Y, Z, Measure, CNOT, Swap class ProjectqQuantumSimulator: def __init__(self, num_qubits): self.num_qubits = num_qubits self.engine = MainEngine() def apply_single_qubit_gate(self, gate, target_qubit): if gate == '...
magicoder
python
You are tasked with creating a SwiftUI component for displaying and interacting with different types of activities. The component should consist of buttons representing various activity types, each with its own emoji and color. When a button is tapped, a callback function should be invoked to handle the selected activi...
```swift import SwiftUI enum ActivityType { case sleep(emoji: String, color: Color) case play(emoji: String, color: Color) case eat(emoji: String, color: Color) // Add more activity cases as needed var emoji: String { switch self { case .sleep(let emoji, _): return emoj...
magicoder
swift
You are tasked with implementing a program that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player can move up, down, left, or right within the grid. The grid is represented by a 2D array, where each cell can con...
```csharp using System; class Program { static void Main() { char[,] grid = { { '.', '.', '.', 'X', '.', 'T' }, { '.', 'X', '.', '.', '.', '.' }, { '.', '.', '.', 'X', '.', '.' }, { '.', '.', '.', '.', '.', 'T' }, { 'X', '.', '.', '.', '.', '....
magicoder
csharp
You are working on a distributed system that involves creating and managing groups of nodes. Each node in the system is identified by a unique nodeid. The code snippet provided is a part of the test suite for managing these groups. The `setUp` method initializes a group with a custom nodeid, and the `tearDown` method e...
```python class Group: def __init__(self, nodeid): self.nodeid = nodeid def free(self): # Implementation not provided def wait(self, timeout): # Implementation not provided class Server: def __init__(self): self.nodes = set() class GroupTest: def __init__(self, se...
magicoder
python
You are given a code snippet that uses the NumPy library to create an array of frames and then iterates through a range of values. Your task is to create a program that simulates a simple animation by displaying the frames in the given range at a specified interval. Write a Python program that takes the frames array a...
```python import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Define the frames array frames = np.arange(35, 165) # Create a figure and axis for the animation fig, ax = plt.subplots() ax.set_xlim(0, 1) ax.set_ylim(0, 1) # Define a function to update the frames for each itera...
magicoder
python
You are tasked with creating a custom attribute system for a C# application. The goal is to implement a mechanism that allows developers to mark classes with specific attributes, which will then be used to control the behavior of the application. Your task is to create a custom attribute system that can be used to mar...
```csharp // Define a base attribute class that can be extended to create custom attributes public class CustomAttribute : Attribute { // Add any common properties or methods that should be available to all custom attributes } // Example of a custom attribute public class MyCustomAttribute : CustomAttribute { ...
magicoder
csharp
You are tasked with implementing a class that manages access to a shared resource using the readers-writers problem. The class should ensure that multiple readers can access the resource simultaneously, but only one writer can access the resource at a time, and no reader can access the resource while a writer is writin...
```python import threading class _LightSwitch: def __init__(self): self.counter = 0 self.mutex = threading.Lock() def lock(self, lock): with self.mutex: self.counter += 1 if self.counter == 1: lock.acquire() def unlock(self, lock): w...
magicoder
python
You are tasked with creating a Python class to represent a person's physical attributes and calculate their Body Mass Index (BMI). The BMI is calculated as the individual's weight in kilograms divided by the square of their height in meters. Your class should have the following attributes and methods: Attributes: - `n...
```python class Persona: def __init__(self, nombre, edad, sexo, estatura, peso): self.nombre = nombre self.edad = edad self.sexo = sexo self.estatura = estatura self.peso = peso def imc(self): return self.peso / (self.estatura * self.estatura) def __str__(se...
magicoder
python
You are tasked with creating a program to manage a library of publications. Each publication can be a book, journal, magazine, or any other type of printed material. Your program should be able to add new publications, remove existing ones, and display information about them. Additionally, it should be able to categori...
```rust struct Publication { pub sub: String, // Other fields and methods will be added by you } struct Library { publications: Vec<Publication>, } impl Library { fn new() -> Library { Library { publications: Vec::new(), } } fn add_publication(&mut self, pub: Publi...
magicoder
rust
You are tasked with implementing a module system for a JavaScript application. The module system should allow for the export and import of properties between different modules. The code snippet provided is an example of exporting all properties from a module named "property". Your task is to create a function that sim...
```javascript // property.js export const name = "John"; export const age = 25; export const address = "123 Main St"; function importModule(moduleName) { // Simulate the import functionality if (moduleName === "property") { return { name, age, address }; } else { throw new Error(`Mo...
magicoder
javascript
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. Your program should read the text file, count the occurrences of each word, and then display the frequency of a given set of target words. Your program should follow these requirements: - The text file sh...
```python def count_word_occurrences(file_path, target_words): word_counts = {} with open(file_path, 'r') as file: for line in file: words = line.lower().split() for word in words: word = word.strip('.,!?:;"') if word in word_counts: ...
magicoder
python
You are tasked with creating a TypeScript class that implements a specific interface and handles the creation of quote items for a quote management system. The system relies on a repository to store and retrieve quote items. Your task is to create a class that implements the `CreateQuoteItemsCommand` interface and inte...
```typescript import { CreateQuoteItemsCommand } from './CreateQuoteItemsCommand'; import { IQuoteItemRepository } from 'src/Domain/Accounting/Repository/IQuoteItemRepository'; class CreateQuoteItemsCommandImpl implements CreateQuoteItemsCommand { constructor(private quoteItemRepository: IQuoteItemRepository) {} ...
magicoder
typescript
You are tasked with implementing a memory management system for a custom object attribute in a programming language. The provided code snippet is part of a library that interacts with a database, and it contains a method to release the memory associated with an object attribute. Your task is to design a memory manageme...
To implement the memory management system for the custom object attribute, you can use a combination of reference counting and smart pointers. Here's a possible solution using Rust: ```rust use std::sync::{Arc, Mutex}; use std::ptr; struct ObjectAttr { inner: *mut ODPIObjectAttr, ref_count: Arc<Mutex<usize>>,...
magicoder
rust
You are tasked with implementing a custom stack data structure in C#. The stack should support the standard push, pop, and peek operations, as well as a method to retrieve the minimum element in the stack in constant time. Additionally, the implementation should be space-efficient, aiming to minimize the memory footpri...
```csharp public class MinStack { private StackNode _top; public MinStack() { _top = null; } public void Push(int x) { if (_top == null) { _top = new StackNode(x, x, null); } else { int min = Math.Min(x, _top.Min); ...
magicoder
csharp
You are tasked with implementing a custom module for a deep learning framework. The module, named "CustomModule", is designed to provide a set of custom layers for neural network architectures. The provided code snippet contains a list of classes that are part of the "CustomModule" and are intended to be used for build...
```python class CustomModule: class CPConv2D: def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0): # Initialize the convolutional layer parameters self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = ke...
magicoder
python
You are tasked with implementing a Python class that parses source code and extracts information about local variables and functions. Your class should provide methods to retrieve this information and should be able to handle different types of source code. Your task is to complete the implementation of the `SourcePar...
```python class SourceParser: def __init__(self): self.local_variables = [] self.functions = [] def __parse_source(self, source): # Your implementation to parse the source code and extract local variables and functions pass def __get_local_variables_from_functions(self): ...
magicoder
python
You are given an array of integers `input` and an integer `k`. Your task is to write a function `findKthLargest` to find the `k`-th largest element in the array. The function signature is: ```python def findKthLargest(nums: List[int], k: int) -> int: ``` The function should return the `k`-th largest element in the ar...
```python def findKthLargest(nums, k): nums.sort(reverse=True) # Sort the array in descending order return nums[k - 1] # Return the k-th largest element ``` The `findKthLargest` function first sorts the array `nums` in descending order using the `sort` method. Then, it returns the element at index `k - 1` to...
magicoder
python
You are working on a data pipeline project and need to create a custom data quality operator for Apache Airflow. The operator will perform data quality checks on a specified database using SQL queries and send notifications if the checks fail. Your task is to implement the `get_data_quality_operator` function that gene...
```python from airflow.operators import BaseOperator from airflow.utils.decorators import apply_defaults from airflow.hooks.base_hook import BaseHook from airflow.exceptions import AirflowException import logging class DataQualityThresholdSQLCheckOperator(BaseOperator): @apply_defaults def __init__(self, conn_...
magicoder
python
You are tasked with implementing a Python class for logging system events. The class should have the ability to generate log messages in different formats based on the provided parameters. The class should support both CSV and verbose formats for the log messages. Your task is to implement the `LogEvent` class with th...
```python import uuid class LogEvent: def __init__(self): self.id = uuid.uuid4() def generate_log_message(self, time_str, name, severity, arg_str, csv=False, verbose=False): if csv: return f"{time_str}, {name}, {self.id}, {severity}, {arg_str}" elif verbose: ret...
magicoder
python
You are tasked with creating a Python function that processes and visualizes time series data related to environmental variables. Specifically, you need to implement a function that calculates the moving average of a given time series and then plots the original time series along with the moving average. Your function...
```python import matplotlib.pyplot as plt import numpy as np def plot_moving_average(time, data, window_size): moving_avg = np.convolve(data, np.ones(window_size)/window_size, mode='valid') padding = (window_size - 1) // 2 time_ma = time[padding:-padding] plt.figure(figsize=(10, 6)) plt.plot(t...
magicoder
python
You are working on a machine learning project and need to implement a model selection process using cross-validation. You have three different classifiers: a logistic regression classifier (lr_clf), a multi-layer perceptron classifier (mlp_clf), and a naive Bayes classifier (nb_clf). Each of these classifiers needs to ...
```python from sklearn.model_selection import GridSearchCV def select_best_parameters(lr_clf, mlp_clf, nb_clf, training_set): # Define parameter grids for each classifier lr_param_grid = {'C': [0.1, 1, 10]} mlp_param_grid = {'hidden_layer_sizes': [(50,), (100,), (50, 50)]} nb_param_grid = {'alpha': [0....
magicoder
python
You are tasked with implementing a Python class that represents a geographical point in a 3D space. The class should have attributes for icon, opacity, x and y positions, latitude, longitude, altitude, model, and emulation server. Your task is to create the class and implement a method that calculates the distance betw...
```python import math class GeographicalPoint: def __init__(self, icon, opaque, x_position, y_position, latitude, longitude, altitude, model, emulation_server): self.icon = icon self.opaque = opaque self.x_position = x_position self.y_position = y_position self.latitude = la...
magicoder
python
You are tasked with implementing a default method for a struct in Rust. The struct represents a geometric shape, and the default method should return a default instance of the shape. The default instance for each shape type is as follows: - Circle: A circle with radius 1.0 and centered at the origin (0, 0). - Rectangle...
```rust #[derive(Debug)] enum ShapeType { Circle, Rectangle, Triangle, } #[derive(Debug)] struct Shape { shape_type: ShapeType, // Add necessary fields here } impl Shape { fn default(shape_type: ShapeType) -> Self { match shape_type { ShapeType::Circle => Shape { ...
magicoder
rust
You are tasked with creating a simple TypeScript class that models a user account and its relationship with a user entity. Your goal is to implement the missing parts of the `Acconts` class to establish a one-to-one relationship with the `User` entity using TypeORM decorators. Your task is to complete the `Acconts` cl...
```typescript import { Entity, PrimaryColumn, OneToOne, JoinColumn } from 'typeorm'; import { User } from './User'; @Entity('accounts') class Acconts { @PrimaryColumn('uuid') id: string; @OneToOne(() => User) @JoinColumn({ name: 'user_id' }) user: User; } ``` In the solution, the `Acconts` class is complet...
magicoder
typescript
You are working on a system that involves optical ports and matrix algorithms for port coupling. Your task is to implement a function that sets up the coupling between ports based on certain conditions. The code snippet provided is a part of the system and contains two methods: `port_update_get` and `system_setup_coupl...
```python def setup_port_coupling(ports_optical, matrix_algorithm): for port in ports_optical: for kfrom in matrix_algorithm.port_set_get(port.i): iwavelen_m, freq = system.optical_frequency_extract(kfrom) if kfrom.subkey_has(ports.LOWER): cplg = phase_lower(iwavelen_...
magicoder
python
You are a security analyst investigating a potential security vulnerability in a web application. You have intercepted a suspicious code snippet from a network request made by the application. Your task is to analyze the code and identify the potential security risk it poses. The intercepted code snippet is as follows...
The intercepted code snippet contains a potential security risk known as command injection. The line `"User-Agentt": "zerodiumsystem('" + cmd + "');"}` suggests that the variable `cmd` is being concatenated directly into the User-Agent header without proper sanitization or validation. This can allow an attacker to inje...
magicoder
http
You are tasked with creating a Python script to simulate the orbit of a celestial body around a planet. The script will take command-line arguments in the form of a JSON string and perform the necessary calculations to simulate the orbit. The JSON string will contain the following parameters: - "py": The name of the P...
```python import sys import json import math def simulate_orbit(json_input): params = json.loads(json_input) GM = params["GM"] x0 = params["x0"] y0 = params["y0"] vx0 = params["vx0"] vy0 = params["vy0"] # Define simulation parameters num_steps = 1000 delta_t = 0.1 # Initialize...
magicoder
python
You are tasked with implementing a graph algorithm for variable elimination in a probabilistic graphical model. In this context, each variable in the model is represented as a node in the graph, and the edges between nodes represent dependencies between variables. The algorithm aims to eliminate variables from the grap...
```python class VariableElimination: def __init__(self): self.nodes = {} # dictionary to store nodes and their incoming edges self.eliminated = [] # list to store eliminated variables def initialize_graph(self, variables, edges): for variable in variables: self.nodes[varia...
magicoder
python
You are tasked with implementing a neural network architecture for image generation using PyTorch. The given code snippet represents a portion of the generator network in a deep convolutional generative adversarial network (DCGAN). The network is responsible for transforming a random noise vector into a synthetic image...
To complete the generator network and achieve the desired output image size, the following layers and activation functions need to be added: ```python import torch.nn as nn class Generator(nn.Module): def __init__(self, nz, ngf, nc): super(Generator, self).__init__() self.main = nn.Sequential( ...
magicoder
python
You are tasked with creating a Python class that utilizes the `summarize_from_text` method to generate a summary from a given text. The method uses the `PlaintextParser` from the `sumy` library to parse the text, a stemmer, and a summarizer to generate the summary. The summarized output is then written to two separate ...
```python from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.tokenizers import Tokenizer from sumy.nlp.stemmers import Stemmer from sumy.summarizers.lsa import LsaSummarizer class TextSummarizer: def __init__(self, language, sentences_count): self.LANGUAGE = language self.SENTENCES_CO...
magicoder
python
You are tasked with creating a Python class to represent font metrics for a text rendering system. The class should encapsulate various typographic and rendering metrics and provide methods to manipulate and access these metrics. The metrics include 'x-height', 'cap-height', 'ascent', 'descent', 'pixel-size', 'directio...
```python class FontMetrics: def __init__(self, x_height, cap_height, ascent, descent, pixel_size, direction, offset, tracking): self._x_height = x_height self._cap_height = cap_height self._ascent = ascent self._descent = descent self._pixel_size = pixel_size self._d...
magicoder
python
You are tasked with implementing a function to validate passport data based on specific rules. The function will take a dictionary representing passport data as input and return True if the passport data is valid according to the specified criteria, and False otherwise. The passport data dictionary will contain key-va...
```python import re def validate_passport_data(passport_data: dict) -> bool: def validate_year(value, min_year, max_year): return value.isdigit() and min_year <= int(value) <= max_year def validate_height(value): if value.endswith('cm'): height = int(value[:-2]) return ...
magicoder
python
You are tasked with implementing a custom serialization system for a 3D rendering engine. The provided code snippet shows the initialization of serialized properties for various rendering parameters. Your task is to create a class that can efficiently serialize and deserialize these properties, ensuring that the data c...
```java import java.io.*; public class RenderSettings implements Serializable { private float shadowDistance; private float shadowTranslucency; private MaskType maskType; private int maskLayer; private String maskEffect; private Vector3 maskPivot; // Constructor and other methods // S...
magicoder
java
You are tasked with creating a class to manage irregular income transactions. Your class should include properties for the description of the income and the date it was received. Additionally, you need to implement a method to calculate the total irregular income received within a specified time range. Create a class ...
```csharp using System; using System.Collections.Generic; using System.Linq; public class IrregularIncomeManager { public string NotRegularIncome { get; set; } public DateTime NotRegularIncomeDate { get; set; } private List<(string, DateTime)> incomeTransactions = new List<(string, DateTime)>(); publ...
magicoder
csharp
You are tasked with implementing a function that calculates the volume of a 3D hexahedral mesh. The mesh is represented using the `HexFixture` class from the `stk_mesh` library. The `HexFixture` class provides methods to access the mesh nodes and elements. You need to write a function `calculateMeshVolume` that takes ...
```cpp #include <stk_mesh/fixtures/HexFixture.hpp> #include <cmath> namespace panzer_stk { double calculateMeshVolume(const stk::mesh::fixtures::HexFixture& mesh) { const auto& nodes = mesh.get_nodes(); const auto& hexElements = mesh.get_hex_elements(); double totalVolume = 0.0; f...
magicoder
cpp
You are tasked with creating a Python function that utilizes the prefix beam search algorithm to decode sequences generated by an optical character recognition (OCR) system. The prefix beam search algorithm is commonly used in sequence generation tasks, such as speech recognition and machine translation. In this proble...
```python import numpy as np from .util import * from .prefix_beam_search import decode def ocr_decode(log_probs, beam_width): T, C = log_probs.shape initial_beam = [((), 0)] # Initialize the beam with an empty sequence and zero score for t in range(T): # Iterate over each time step new_beam = {}...
magicoder
python
You are tasked with creating a Python class that parses job details from a website using XPath and CSS selectors. Your task is to complete the implementation of the `DataScienceJobsParser` class, which inherits from the `Parser` class. The `Parser` class provides methods for web scraping and parsing HTML content. The `...
```python class DataScienceJobsParser(Parser): X_BASE = '//div[@id="detailView"]/' X_TITLE = X_BASE + '/h1/text()' X_KEYWORDS = X_BASE + 'div[4]/div[2]/text()' X_ABSTRACT = X_BASE + 'div[2]/div[2]/text()' X_DESCRIPTION = X_BASE + 'div[3]/div[2]/text()' CSS_COMPANY_ADDRESS = 'tr>td>address::text'...
magicoder
python
You are tasked with creating a shell script that organizes files in a specified directory based on their file extensions. Your script should take a directory path as an argument and move files into corresponding subdirectories based on their extensions. If a subdirectory for a specific file extension does not exist, it...
```bash #!/bin/bash # Check if BIN_HOME environment variable is set if [ -z "$BIN_HOME" ]; then echo "Error: BIN_HOME environment variable is not set" exit 1 fi # Check if the specified directory exists if [ ! -d "$1" ]; then echo "Error: Specified directory does not exist" exit 1 fi # Move to the sp...
magicoder
shell
You are tasked with implementing a multi-threaded data processing system for a radio scanner application. The system is designed to handle multiple channels, each with its own frequency. The given code snippet is a part of the system's processing logic, which involves updating the frequency of a specific channel and ha...
```rust // Define the data structure for channels and their frequencies struct Channel { freq: Option<f64>, // Other channel properties } // Define the shared data structure protected by a mutex struct SharedData { channels: Vec<Channel>, // Other shared data properties } // Implementation of the mult...
magicoder
rust
You are tasked with creating a Bash script that generates a self-signed SSL certificate using OpenSSL. The script should take two input parameters: the key name and the certificate name. The script should then use these parameters to generate a private key, a certificate signing request (CSR), and a self-signed certifi...
```bash #!/usr/bin/env bash set -euo pipefail if [ "$#" -ne 2 ]; then echo "Usage: $0 <key_name> <cert_name>" exit 1 fi KEYNAME="$1" CERTNAME="$2" CSRNAME="${KEYNAME%.*}.csr" openssl req -new -newkey rsa:4096 -nodes -keyout $KEYNAME -out $CSRNAME openssl x509 -req -sha256 -days 365 -in $CSRNAME -signkey $KEY...
magicoder
shell
You are tasked with implementing a symbolic integration function using the heurisch algorithm. The heurisch algorithm is a heuristic algorithm for indefinite integration, which attempts to find an antiderivative of a given function. Your task is to implement the `heurisch` function that takes a rational function and a ...
```python from sympy import symbols, log, sin def heurisch(rational_function, variable): x = symbols(variable) # Handle simple rational functions of the form 1/(ax + b) if rational_function == 1/(x + sin(x)): return log(x + sin(x)) # Handle more complex rational functions elif rational_func...
magicoder
python
You are working on a project that involves optimizing video processing algorithms for a multimedia application. As part of this project, you need to implement a function that calculates the masked sub-pixel variance for different block sizes. The masked sub-pixel variance is a measure of the variation in pixel values w...
```python import numpy as np def calculate_masked_sub_pixel_variance(block_size, mask, pixels): block_width, block_height = block_size mask = np.array(mask) pixels = np.array(pixels) included_pixels = pixels[mask == 1] # Select pixels based on the mask mean_value = np.mean(included_pixels) # Cal...
magicoder
python
You are given a string containing repeated characters. Your task is to write a function that compresses the string by replacing repeated characters with the character followed by the count of the repetition. If the compressed string is not shorter than the original string, the function should return the original string...
```python def compress_string(s: str) -> str: compressed = '' count = 1 for i in range(len(s)): if i == len(s) - 1 or s[i] != s[i + 1]: compressed += s[i] + str(count) count = 1 else: count += 1 return compressed if len(compressed) < len(s) else s ``` ...
magicoder
python