query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are given a list `A` of integers. Write a function `rearrange_max_to_front` that rearranges the elements of the list such that the maximum absolute value element is moved to the front of the list. If there are multiple elements with the same maximum absolute value, the one with the lower index should be moved to th...
```python from typing import List def rearrange_max_to_front(A: List[int]) -> List[int]: a_max = A[0] i_max = 0 for i, item in enumerate(A): if abs(item) >= abs(a_max): i_max, a_max = i, item A.insert(i_max, A[0]) A.pop(i_max+1) return A ```
magicoder
python
You are tasked with creating a Swift protocol that defines a base conversion functionality and implementing a mock class that conforms to this protocol. The protocol should have a method to convert a given string from one base to another, and the mock class should keep track of the number of times the conversion method...
```swift // Define the BaseConversionProtocol protocol BaseConversionProtocol { func convertString(_ string: String, fromBase: Int, toBase: Int) -> String } // Implement the BaseConversionMock class conforming to BaseConversionProtocol class BaseConversionMock: BaseConversionProtocol { var convertStringCallCou...
magicoder
swift
You are tasked with implementing a custom probability density function (PDF) for a statistical analysis library. The PDF function should be able to handle various input types and provide the probability density function normalized over a specified range. Your task is to complete the implementation of the `ext_pdf` met...
```python def ext_pdf( self, var: ztyping.VarInputType, norm: ztyping.NormInputType = None, *, options=None, ) -> ztyping.PDFReturnType: """Probability density function, normalized over `norm`. OneDim. Args: var: ztyping.VarInputType - Input variable for the prob...
magicoder
python
You are tasked with creating a Rust library that provides a unified interface for querying system information on various Linux distributions. The library should be able to retrieve data related to the distribution, uptime, package managers, shell, screen resolution, window manager, and desktop environment. Your task i...
```rust // Define traits for system information components pub trait Distro { fn get_distribution(&self) -> String; } pub trait Uptime { fn get_uptime(&self) -> u64; } pub trait PackageManagers { fn get_package_managers(&self) -> Vec<String>; } pub trait Shell { fn get_shell(&self) -> String; } pub ...
magicoder
rust
You are tasked with creating a script that processes input using AWK. The script should be designed to take advantage of environment variables and produce specific output based on the input provided. Your task is to write a Bash script that meets the following requirements: - The script should check if the environment...
```bash #!/bin/bash if [[ -z "$AWK" || -z "$WORKDIR" ]]; then printf '$AWK and $WORKDIR must be set\n' >&2 exit 1 fi SCRIPT=$WORKDIR/test.temp.run cat > $SCRIPT <<EOF #!$AWK -f { print } EOF chmod a+rx $SCRIPT printf 'a\nb\nc\nd\n' | $SCRIPT ``` The solution provided is a Bash script that checks if the env...
magicoder
shell
You are tasked with implementing a Python class for simulating a universe. The universe is represented as a grid of cells, where each cell can either contain a value or be empty. The class should provide methods for creating a universe from a given dataset and for generating a random universe of specified dimensions. ...
```python from typing import TypeVar, Generic, Callable, Optional T = TypeVar('T') BaseUniverseType = TypeVar('BaseUniverseType', bound='Universe') def is_cell(value: T) -> bool: """Checks if the value is a valid cell.""" # Implementation not provided class Universe(Generic[T]): def __init__(self, width:...
magicoder
python
You are tasked with creating a validation function for a decentralized application (dApp) using the Holochain framework. Holochain is a platform for building decentralized applications that uses a unique approach to data storage and validation. In this problem, you will be working with the Rust programming language and...
```rust #[entry_def] fn person_entry_def() -> ValidatingEntryType { entry!( name: "person", description: "Represents a person entry", validation_package: || { hdk::ValidationPackageDefinition::Entry }, validation: |person: Person, _ctx: hdk::ValidationData| { ...
magicoder
rust
You are tasked with implementing a method to calculate the total cost of a user's shopping cart items, including any applicable taxes and shipping costs. You are provided with the following interfaces and classes: ```java import com.rrcorpus.domain.ShippingAddress; import com.rrcorpus.domain.ShoppingCart; import com.r...
```java import com.rrcorpus.domain.Order; import com.rrcorpus.domain.ShippingAddress; import com.rrcorpus.domain.ShoppingCart; import com.rrcorpus.domain.User; public class OrderServiceImpl implements OrderService { private TaxCalculator taxCalculator; private ShippingCalculator shippingCalculator; public...
magicoder
java
You are tasked with implementing a dependency resolution algorithm for a package manager. The package manager maintains a list of dependencies for each package, and your goal is to resolve these dependencies in a way that satisfies all requirements and detects any unexpected dependencies. You are given a Rust function...
```rust use std::collections::{HashSet, HashMap}; struct Package { name: String, dependencies: HashSet<String>, } impl Package { fn new(name: &str, dependencies: HashSet<String>) -> Self { Package { name: name.to_string(), dependencies, } } } fn resolve_depende...
magicoder
rust
You are tasked with implementing a class to simulate the behavior of a screw (Sruba in Polish). The class, named `Sruba`, has a member function `krec` that rotates the screw by a specified angle. The rotation angle is accumulated in the member variable `kat_obrotu_sruby`. The function also checks if the total rotation ...
```cpp #include <iostream> class Sruba { public: double kat_obrotu_sruby; void krec(double kat) { kat_obrotu_sruby += kat; if (kat_obrotu_sruby >= 360 || kat_obrotu_sruby <= -360) { kat_obrotu_sruby = 0; std::cout << "Screw has completed a full rotation" << std::endl; ...
magicoder
cpp
You are tasked with implementing a function to calculate the joint probability distribution of a given set of random variables. A joint probability distribution represents the probability of each combination of values for the random variables. You are given a code snippet that demonstrates part of the implementation. ...
```python from collections import defaultdict import itertools class JointProbabilityDistribution: def __init__(self, variables, cardinalities, probabilities): self.variables = variables self.cardinalities = cardinalities self.probabilities = probabilities def calculate_joint_probability_d...
magicoder
python
You are working on a data analysis project that involves predicting stock market behavior. You have a dataset containing historical stock prices and corresponding features. Your task is to implement a function that processes the data and makes predictions based on a linear model. The given code snippet is part of the p...
```python class LinearModel: def __init__(self, coeffs): self.coeffs = coeffs def make_prediction(chances: dict, chance_modifier: float, linear_model: LinearModel) -> str: chances['slow-spike'] -= chance_modifier chances['sudden-spike'] -= chance_modifier if linear_model.coeffs[0] <= -1: ...
magicoder
python
You are tasked with implementing a file reading utility in Rust that can asynchronously read a file from a given path with an initial offset and endianness. Your task is to complete the implementation of the `from_file_with_offset_async` function, which is an asynchronous function that reads a file from the specified p...
```rust use std::path::{Path, PathBuf}; use tokio::task::spawn_blocking; use std::fs::File; use std::io::{Read, Result as IoResult}; enum Endianness { BigEndian, LittleEndian, } struct YourType; // Replace with the actual type you are working with impl YourType { #[inline] async fn from_file_with_off...
magicoder
rust
You are tasked with implementing a simple observer pattern in Python. The observer pattern is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. In this problem, you will create a class that ...
```python class DefaultSubscription: pass class Observable: def __init__(self): self.observers = [] def add_observer(self, observer): self.observers.append(observer) def remove_observer(self, observer): self.observers.remove(observer) def notify_observers(self, value, is_...
magicoder
python
You are tasked with implementing a method to extract and set the video orientation metadata for filmstrip items in a media processing application. The provided code snippet contains a method `loadRotationMetadata` that takes a `FilmstripItem` object as a parameter. The `FilmstripItem` class has a method `getData()` tha...
```java static boolean loadRotationMetadata(final FilmstripItem data) { final String path = data.getData().getFilePath(); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setDataSource(path); String orientation = retriever.extractMetadata(MediaMetadataRetrieve...
magicoder
java
You are given a list of floating-point numbers representing the daily temperatures in degrees Celsius over a period of time. Your task is to write a program to find the longest consecutive sequence of days where the temperature was strictly increasing. For example, given the following list of temperatures: ``` 1.85, 1...
```python def longest_increasing_sequence(temperatures): max_length = 0 current_length = 1 max_start_index = 0 current_start_index = 0 for i in range(1, len(temperatures)): if temperatures[i] > temperatures[i - 1]: current_length += 1 if current_length > max_length: ...
magicoder
python
You are tasked with creating a program to parse a Java class file and extract the names of the private fields along with their associated comments. The comments are written in Chinese and may contain multi-line descriptions. Your program should output the field names and their corresponding comments. You are given a s...
```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class FieldCommentParser { public static void main(String[] args) { String classSnippet = "public class FileUpload {\n" + " /**\n" + " * 文件上传类型\n" + " */\n" + ...
magicoder
java
You are tasked with implementing a function to process and save annotations from a given file. The function `saveAnn(annpath, outpath, termcodes)` takes three parameters: - `annpath`: a string representing the file path to the annotation file. - `outpath`: a string representing the file path where the processed annotat...
```python import csv def saveAnn(annpath, outpath, termcodes): annotation_content = [] # Load annotation, and save with new field. with open(annpath, 'r', newline='') as ann_file, open(outpath, 'w', newline='') as out_file: ann_reader = csv.reader(ann_file, dialect='excel', delimiter="\t") ...
magicoder
python
You are tasked with implementing a simple authentication and post management system using React and Redux. The given code snippet is a part of a React component that displays a list of posts and provides functionality for user authentication and post management. Your task is to complete the implementation of the authe...
```javascript // Assuming the usage of Redux and React-Redux for state management // Define the action types const LOGIN = 'LOGIN'; const LOGOUT = 'LOGOUT'; const SET_INIT_RETRIES = 'SET_INIT_RETRIES'; const ADD_POST = 'ADD_POST'; // Define the action creators const login = (userData) => { // Implement the login ac...
magicoder
javascript
You are given a code snippet from a graphical user interface (GUI) application. The code appears to be part of a function that updates the display of a horizontal scroll bar and associated label. The function seems to be responsible for drawing the label, formatting and drawing text, and updating the scroll bar's posit...
1. The `HScrollBar_DrawLabel` function is likely responsible for drawing the label associated with a horizontal scroll bar. It may set the appearance and position of the label within the GUI, ensuring it aligns correctly with the scroll bar. 2. The `DrawFormatText` function appears to format and draw text within a spe...
magicoder
python
You are tasked with implementing a C++ program to calculate the total surface area and volume of various 3D shapes. The program should utilize classes and inheritance to represent different shapes and should provide accurate calculations for each shape. You are provided with the following class declarations in separat...
```cpp // cone.hpp #ifndef CONE_HPP #define CONE_HPP #include "shape.hpp" class Cone : public Shape { private: double radius; double height; public: Cone(double r, double h) : radius(r), height(h) {} double calculateVolume() { return (1.0 / 3.0) * PI * radius * radius * height; } do...
magicoder
cpp
You are tasked with implementing a custom asynchronous task scheduler in Rust. The scheduler will manage a set of tasks and execute them in a non-blocking, concurrent manner. To achieve this, you need to create a `Task` struct that represents an asynchronous task and a `Scheduler` struct responsible for managing and ex...
```rust use std::task::{Context, Poll, Waker, RawWaker, RawWakerVTable}; use std::sync::{Arc, Mutex}; use futures::future::Future; struct Task { id: usize, future: Box<dyn Future<Output = ()> + Send>, waker: Waker, } struct Scheduler { tasks: Arc<Mutex<Vec<Task>>>, } impl Task { fn new(id: usize,...
magicoder
rust
You are tasked with creating a build automation tool that can handle dependencies and parallel execution. Your tool should be able to parse a configuration file, resolve dependencies, and execute build tasks in parallel. The configuration file will contain a list of tasks, each with its own dependencies and commands to...
```python import concurrent.futures def executeTasks(tasks): task_map = {task["name"]: task for task in tasks} task_outputs = {} def execute_task(task_name): task = task_map[task_name] if task["dependencies"]: with concurrent.futures.ThreadPoolExecutor(max_workers=len(task["dep...
magicoder
python
You are tasked with creating a program to encode and decode messages using the rail fence cipher. The rail fence cipher is a form of transposition cipher that rearranges the plaintext letters in a zigzag pattern along a set number of "rails" or rows. For encoding, the message is written in a zigzag pattern down the ra...
```python def encode(plain_text: str, rails: int) -> str: rail_matrix = [list() for _ in range(rails)] indices = [*[i for i in range(rails)], *[i for i in range(rails-2, 0, -1)]] for i, char in enumerate(plain_text): rail_matrix[indices[i % len(indices)]].append(char) return ''.join(''.join(ro...
magicoder
python
You are tasked with implementing a timer module in Rust. The timer should be able to start and measure the elapsed time since its start. You are provided with a code snippet that includes a method to create a new timer and start it. Your task is to complete the implementation of the timer module by adding the necessary...
```rust use std::time::{Duration, Instant}; pub struct Timer { start_time: Instant, period: Duration, } impl Timer { pub fn new(period: Duration) -> Self { Timer { start_time: Instant::now(), period, } } pub fn new_start(period: Duration) -> Self { ...
magicoder
rust
You are tasked with implementing a binary search tree (BST) in Python. A binary search tree is a binary tree in which each node has a key, and for any node, all the keys in its left subtree are less than its key, and all the keys in its right subtree are greater than its key. Your task is to implement the `insert` and ...
```python class TreeNode: def __init__(self, key): self.key = key self.left = None self.right = None def insert(self, value): if value < self.key: if self.left is None: self.left = TreeNode(value) else: self.left.insert(val...
magicoder
python
You are tasked with implementing a pagination system for a web application. The pagination system should generate the necessary HTML code for displaying page numbers and navigation controls. You are given a JavaScript function `generatePagination` that takes in three parameters: - `totalPages` (integer): The total num...
```javascript function generatePagination(totalPages, currentPage, containerId) { const container = document.getElementById(containerId); if (!container) { console.error(`Container element with ID '${containerId}' not found.`); return; } let paginationHTML = '<ul class="pagination float...
magicoder
javascript
You are tasked with implementing a function that calculates the number of edits required to transform a given string into a target string using a sliding window approach. The function should take in three parameters: the original string, the target string, and the window size. The sliding window should move through the...
```python def count_edits(original: str, target: str, window: int) -> int: if len(original) != len(target): return -1 # Strings must be of equal length for comparison edits = 0 for i in range(len(original) - window + 1): substring = original[i:i + window] target_substring = target[...
magicoder
python
You are tasked with creating a program that processes video files and extracts specific frames based on user-defined criteria. The program should utilize the AVKit framework for video processing and be designed to run on iOS devices. Your task is to implement a function called `extractFrames` that takes in the followi...
```swift import AVKit func extractFrames(videoURL: URL, outputURL: URL, frameNumbers: [Int]) { let asset = AVURLAsset(url: videoURL) let imageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.requestedTimeToleranceBefore = .zero imageGenerator.requestedTimeToleranceAfter = .zero do { ...
magicoder
swift
You are tasked with implementing a class that represents an image plotter. The class has three properties: `_f160`, `_grid`, and `pixels_per_image`. Your task is to complete the implementation of the `pixels_per_image` property, which should return the total number of pixels in the image based on the dimensions of the ...
```python class ImagePlotter: def __init__(self, f160, grid): self._f160 = f160 self._grid = grid @property def f160(self): return self._f160 @property def grid(self): """ grid onto which the image is plotted """ return self._grid ...
magicoder
python
You are tasked with creating a Python module for analyzing and evaluating a set of Tweets. The module should include functionality for audience and/or conversation analysis. The provided code snippet is the beginning of the module and sets up the logging configuration. Your task is to implement the following functions...
```python # gnip_tweet_evaluation.py import logging from typing import List, Dict, Any logger = logging.getLogger('analysis') logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) def perform_audience_analysis(tweets: List[str]) -> Dict[str, Any]: # Perform audience analysis logic here logg...
magicoder
python
You are tasked with implementing a Python function that extracts the argument specification from a function definition. The function should handle cases where the function has decorator(s) and return the argument specification if no decorator is present. The argument specification should include the function's argument...
```python def get_argspec_from_func_def(node, obj, mod): if node.decorator_list: return None # Function has decorator, return None argspec = {} for arg in obj.__code__.co_varnames[:obj.__code__.co_argcount]: arg_default = obj.__defaults__[obj.__code__.co_varnames.index(arg) - (len(obj.__co...
magicoder
python
You are tasked with debugging a shader definition function in a game engine. The function `AddShaderDefinition` is used to add a new definition to a shader, but it seems that there is a bug in the code. The function takes two parameters: the name of the shader definition and a boolean value indicating whether the defin...
The bug in the code snippet is that the condition for adding the "USE_LIGHTING" shader definition is written in reverse. The ternary operator should be modified to correctly evaluate the condition and set the boolean value for the shader definition. The corrected code snippet should be as follows: ```csharp // Assumi...
magicoder
csharp
You are tasked with implementing a Python class that represents a tree data structure. The tree should support adding branches for different types and checking if a given type is present in the tree. Additionally, the tree should be able to handle type dictionaries, where a type may be associated with another type in a...
```python class Tree: def __init__(self): self.tree = {} def add_type_branch(self, type, type_dict): if type in self.tree: return False else: if type in type_dict: self.tree[type] = type_dict[type] return True else: ...
magicoder
python
You are working on a project that involves processing audio data using a custom pipeline. As part of this pipeline, you need to implement a stage that applies a label to the processed audio data. The label is determined based on the input model and is selected from a predefined set of labels. Your task is to create a ...
```rust use std::collections::HashMap; struct Type { name: String, dimensions: Vec<usize>, } struct Value { // Assume implementation for Value struct } struct ProcBlockStage { proc_block: String, inputs: Vec<String>, outputs: Vec<Type>, args: HashMap<String, Value>, } fn get_label(proc_b...
magicoder
rust
You are tasked with creating a script to automate the deployment of a Docker image to a GitLab registry. The script should perform the following steps: 1. Log in to the GitLab registry using the provided credentials. 2. Build a Docker image tagged as `registry.gitlab.com/allawaabdat/haproxy`. 3. Push the built Docker ...
```bash #!/bin/bash # Log in to the GitLab registry docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY # Build the Docker image docker build -t registry.gitlab.com/allawaabdat/haproxy . # Push the Docker image to the GitLab registry docker push registry.gitlab.com/allawaabdat/haproxy ``` The provided she...
magicoder
shell
You are tasked with creating a script to automate the download of various software packages based on their availability. The script should use the `curl` command to download the packages only if they do not already exist in the specified locations. Given the provided code snippet, you need to extend the script to incl...
```bash #!/bin/bash # Function to handle download errors handle_download_error() { echo "Error: Failed to download $1. Exiting script." exit 1 } # Check if L4T driver package exists if [ ! -e "$L4T_DRIVER_PACKAGE" ]; then curl -LO "$L4T_DRIVER_PACKAGE_URL" || handle_download_error "$L4T_DRIVER_PACKAGE_URL" fi ...
magicoder
shell
You are tasked with implementing a timer system in a game engine. The timer should start counting when enabled and stop when a certain time threshold is reached. Additionally, the timer should trigger a flag when the specified time threshold is reached. You are provided with a code snippet that includes some variables ...
```csharp public class GameTimer { private float elapsedTime = 0f; private float thresholdTime = 10f; // Example threshold time in seconds private bool timerOn = false; private bool speedReached = false; public bool enableTimer; public void StartTimer() { timerOn = true; } ...
magicoder
csharp
You are tasked with creating a Bash script that searches for executable files within the directories listed in the PATH environment variable and counts the number of GitHub stars for each executable file's repository. The script should then display the top N repositories with the highest number of stars, where N is a u...
```bash #!/bin/bash # Check if the user provided the number of top repositories to display if [ -z "$1" ]; then echo "Usage: $0 <number_of_top_repositories>" exit 1 fi # Function to retrieve GitHub stars for a repository get_github_stars() { repo_name=$1 stars=$(curl -s "https://api.github.com/repos/$repo_nam...
magicoder
shell
You are tasked with implementing a singleton design pattern for a `PlanetEngine` class in C++. The given code snippet contains a destructor for the `PlanetEngine` class and a static method `Get()` which is intended to return the instance of the `PlanetEngine`. However, there is a comment indicating the intention to rem...
```cpp class PlanetEngine { public: static PlanetEngine* Get() { if (sEngine == nullptr) { sEngine = new PlanetEngine(); } return sEngine; } // Delete the copy constructor and assignment operator to prevent duplication PlanetEngine(const PlanetEngine&) = delete; ...
magicoder
cpp
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 balance. Additionally, the class should be able to generate a unique account number for each new account. Your task is to implement the `BankAccoun...
```python import uuid class BankAccount: def __init__(self): self._account_number = uuid.uuid4() self._balance = 0 @property def account_number(self): return str(self._account_number) def deposit(self, amount): self._balance += amount def withdraw(self, amount): ...
magicoder
python
You are tasked with implementing a graph data structure with weighted edges and a method to find the shortest path between two nodes using Dijkstra's algorithm. The graph is represented using a custom class `GrafoComPesos` which takes a dictionary of edges and their weights as input. The class has a method `dijkstra` w...
```python import heapq class GrafoComPesos: def __init__(self, edges): self.graph = edges def dijkstra(self, start, end): # Initialize distances with infinity for all nodes except the start node distances = {node: float('inf') for node in self.graph} distances[start] = 0 ...
magicoder
python
You are tasked with implementing a function that will generate all possible combinations of a given pattern. The pattern consists of placeholders represented by curly braces `{}` and non-placeholder characters. The function should replace each placeholder with all possible values from a set of options and return a list...
```python from typing import List def generate_combinations(pattern: str, options: List[str]) -> List[str]: def backtrack(combination, index): if index == len(placeholders): combinations.append(''.join(combination)) return for option in options: combination[place...
magicoder
python
You are tasked with implementing a digital-to-analog converter (DAC) top-level function in a hardware description language (HDL) for a digital signal processing (DSP) application. The function signature is as follows: ```c output_type dac_top(input_type in, bool valid); ``` Where: - `input_type` is the type of the in...
```verilog module dac_top( input input_type in, input bool valid, output reg output_type out ); always @ (posedge valid) begin if (valid) begin // Perform digital-to-analog conversion based on the input signal // and update the output signal out <= perform_dac_conversion(in); end en...
magicoder
verilog
You are tasked with implementing a Swift function that validates a given instance of `BuildAppEncryptionDeclarationLinkageRequest` based on certain criteria. The `BuildAppEncryptionDeclarationLinkageRequest` struct represents a request containing the ID of the related resource. It has a nested struct `Data` containing ...
```swift func validateRequest(_ request: BuildAppEncryptionDeclarationLinkageRequest) -> Bool { guard !request.data.id.isEmpty else { return false // The ID is empty, so the request is invalid } return true // The request is valid } ``` The `validateRequest` function takes a `BuildAppEncryptionDe...
magicoder
swift
You are tasked with implementing a memoization utility for caching the results of opening iModel databases. Memoization is a technique used to improve the performance of functions by caching the results of expensive function calls and returning the cached result when the same inputs occur again. Your goal is to impleme...
```typescript import { HubUtility } from "./HubUtility"; import { TestConfig } from "../TestConfig"; import { ActivityLoggingContext } from "@bentley/bentleyjs-core"; class OpenIModelDbMemoizer { private cache: Map<string, any>; constructor() { this.cache = new Map(); } memoizeOpenIModelDb(params: any, r...
magicoder
typescript
You are tasked with implementing a Python function to filter a list of dictionaries based on a specific condition. The function should take a list of dictionaries and a filter condition as input and return a new list containing only the dictionaries that satisfy the given condition. You are given the following code sn...
```python def filter_dicts(dict_list, condition): return [d for d in dict_list if condition(d)] ``` The `filter_dicts` function uses a list comprehension to iterate through each dictionary in `dict_list` and applies the `condition` function to filter the dictionaries based on the given condition. The filtered dict...
magicoder
python
You are tasked with creating a function that determines the script (writing system) of a given Unicode character. The script can be one of the following: Han, Latin, Common, or Any. The function should return the appropriate script based on the input character. Write a function `find_script` that takes a Unicode chara...
```rust #[derive(Debug, PartialEq)] enum Script { Han, Latin, Common, Any, } fn find_script(c: char) -> Script { match c { ' '..='~' => Script::Common, '一'..='鿋' | '豈'..='鶴' | '侮'..='龎' | 'ff'..='st' | 'ﬓ'..='ﬗ' | 'ﬠ'..='ﬦ' | 'ﬨ'..='שׁ' | 'ﷲ' => Script::Han, 'A'..='Z' | 'a'..='...
magicoder
rust
You are working on a project that involves image processing and perspective transformation. Your task is to implement a function that takes an input image and performs a perspective transformation on it. The function should also provide the option to reverse the transformation and display the original and transformed i...
```python import cv2 import numpy as np import matplotlib.pyplot as plt def perform_perspective_transform(input_image, src_points, dst_points, verbose=False): # Convert source and destination points to numpy arrays src = np.float32(src_points) dst = np.float32(dst_points) # Calculate the perspective t...
magicoder
python
You are tasked with implementing a simple stack data structure in Swift. A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. It has two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack. Your task is to creat...
```swift class Stack<T> { private var elements: [T] = [] func push(_ element: T) { elements.append(element) } func pop() -> T? { return elements.popLast() } func peek() -> T? { return elements.last } func isEmpty() -> Bool { return elements.isEmpty ...
magicoder
swift
You are tasked with implementing a caching mechanism for a function that evaluates leaf predicates in a tree structure. The function `leafpred(leaf)` takes a leaf object as input and returns a value based on some predicate evaluation. To optimize performance, a caching mechanism is introduced to store the results of pr...
```python def match_leaves(leafpred, leaves): leafcache = {} # Initialize an empty cache to store evaluated results result_mapping = {} # Initialize an empty dictionary to store leaf-predicate evaluation results for leaf in leaves: if leaf in leafcache: # If the leaf's result is already in the c...
magicoder
python
You are tasked with creating a secure file management system for a company. The system should allow users to upload files, access their own files, and delete files they have uploaded. To achieve this, you need to implement a secure file server with user authentication and file management capabilities. You have been pr...
```python import csv import socket import secrets import os class FileServer: def __init__(self, db_file): self.db_file = db_file self.users = {} # Store user tokens and their uploaded files def authenticate_user(self, user_token): return user_token in self.users def upload_file(...
magicoder
python
You are tasked with implementing a function that processes a list of integers and returns the maximum sum of a contiguous subarray within the list. The function should have the following signature: ```swift func maxSubarraySum(_ nums: [Int]) -> Int { // Your implementation here } ``` The function should take in a...
```swift func maxSubarraySum(_ nums: [Int]) -> Int { var maxSum = nums[0] var currentSum = nums[0] for i in 1..<nums.count { currentSum = max(nums[i], currentSum + nums[i]) maxSum = max(maxSum, currentSum) } return maxSum } ``` The solution uses Kadane's algorithm to efficiently f...
magicoder
swift
You are tasked with creating a Python function to determine whether a given integer is a palindrome. A palindrome is a number that reads the same backward as forward. For example, 121 is a palindrome, while 123 is not. Write a function `is_palindrome` that takes an integer `x` as input and returns `True` if `x` is a p...
```python def is_palindrome(x: int) -> bool: if x < 0 or (x % 10 == 0 and x != 0): return False # Negative numbers and numbers ending with 0 are not palindromes reverse_num = 0 original_num = x while x > 0: digit = x % 10 reverse_num = reverse_num * 10 + digit x = x //...
magicoder
python
You are tasked with implementing a thread-safe storage system for handling results of asynchronous operations. The provided code snippet includes a Swift class with a private condition lock and an atomic variable for storing results. Your task is to extend this class by implementing methods for setting and getting resu...
```swift import Foundation class ThreadSafeStorage { private let lck = SDConditionLock() private var storage = Atomic<Result?>(value: nil) private let queue: DispatchQueue private init(queue: DispatchQueue) { self.queue = queue } func setResult(result: Result) { queue.async { ...
magicoder
swift
You are tasked with implementing a simplified version of Python's `OrderedDict` data structure. An `OrderedDict` is a dictionary subclass that remembers the order in which its contents are added. When iterating over an ordered dictionary, the items are returned in the order they were inserted. Your task is to create a...
```python class OrderedDict: def __init__(self): self._order = [] # Maintain the order of keys self._data = {} # Store key-value pairs def __setitem__(self, key, value): if key in self._data: self._order.remove(key) # Remove the key from its current position self...
magicoder
python
You are tasked with creating a Python function that simulates a flight fare calculator using the requests library to send HTTP requests to a specific URL. The function should take in several parameters and return the calculated fare for a flight. The function should have the following signature: ```python def calcula...
```python import requests def calculate_flight_fare(airline: str, passenger_tier: str, from_location: str, to_location: str, fare_class: str) -> float: sess = requests.Session() sess.get("http://www.britishairways.com") params = { "eId": "199001", "marketingAirline": airline, ...
magicoder
python
You are tasked with creating a program to help a Jedi Padawan manage their equipment budget. The program should take the following inputs: - The amount of money the Padawan has (amountOfMoney). - The number of students in the Padawan's class (studentsCount). - The price of a lightsaber (priceOFLightsaber). - The price ...
```csharp namespace PadawanEquipment { class Program { static void Main(string[] args) { double amountOfMoney = double.Parse(Console.ReadLine()); int studentsCount = int.Parse(Console.ReadLine()); double priceOFLightsaber = double.Parse(Console.ReadLine()); ...
magicoder
csharp
You are tasked with implementing a function to process genomic data from a set of inputs and generate output files. The function takes a list of input samples, a list of background samples, and a working directory as input. The function processes each input sample to generate output files, including copy number ratio (...
```python import os import utils def _process_genomic_data(inputs, backgrounds, work_dir): def _bam_to_outbase(align_bam, raw_work_dir, cur_input): # Implementation of _bam_to_outbase function # This function processes the alignment BAM file and returns the output base name pass def _g...
magicoder
python
You are tasked with implementing a function that checks whether a given string matches a specific pattern. The pattern consists of letters and wildcards represented by asterisks (*). A wildcard can match any sequence of characters, including an empty sequence. The function should return true if the string matches the p...
```javascript function isMatch(pattern, str) { const dp = Array(pattern.length + 1).fill(false); dp[0] = true; for (let i = 0; i < pattern.length; i++) { if (pattern[i] === '*') { for (let j = 0; j <= str.length; j++) { dp[j + 1] = dp[j] || dp[j + 1]; } } else { for (let j = str...
magicoder
javascript
You are tasked with creating a program to analyze a given text corpus using natural language processing techniques. The program should perform the following tasks: 1. Preprocess the text data by removing punctuation and converting all words to lowercase. 2. Calculate the Term Frequency-Inverse Document Frequency (TF-I...
```python import string import warnings from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from textblob import TextBlob # Setup warnings.filterwarnings('ignore') # Ignore warning messages def preprocess_text(text): """ Preprocess the text data ...
magicoder
python
You are tasked with implementing a simple fee management system for a national park API. The provided code snippet is a part of the `Fee` class in the `ParksApi.Models` namespace. Your task is to complete the implementation of the `Fee` class by adding properties and methods to manage fees for different activities with...
```csharp using Newtonsoft.Json; namespace ParksApi.Models { public class Fee { public int FeeId { get; set; } public int ParkId { get; set; } public string ActivityName { get; set; } // Property to store the name of the activity public decimal Amount { get; set; } // Property t...
magicoder
csharp
You are tasked with implementing a function to calculate the distance between the centers of two objects represented by rectangles. The rectangles are defined by their top-left corner coordinates (x, y) and their width (w) and height (h). The distance between the centers of the rectangles is calculated using the Euclid...
```python import numpy as np import cv2 def calculate_distance(o1, o2): (x1, y1, w1, h1) = o1 (x2, y2, w2, h2) = o2 c1 = (x1 + w1 / 2, y1 + h1 / 2) c2 = (x2 + w2 / 2, y2 + h2 / 2) return np.hypot(c1[0] - c2[0], c1[1] - c2[1]) cv2.namedWindow("preview") cv2.namedWindow("preview2") ``` The `calcula...
magicoder
python
You are given a code snippet that contains a method. Your task is to identify the missing parts of the code and complete the method to achieve the desired functionality. The method is intended to check whether a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that ...
```java public static boolean isPalindrome(String str) { str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Remove non-alphanumeric characters and convert to lowercase int left = 0; int right = str.length() - 1; while (left < right) { if (str.charAt(left) != str.charAt(right)) { ...
magicoder
java
You are tasked with creating a Python script that simulates a simple text-based game. The game involves a player navigating through a series of rooms, each containing different challenges or rewards. The player must collect items and solve puzzles to progress through the game. Your task is to implement the logic for mo...
```python class Room: def __init__(self, room_id, description, items): self.room_id = room_id self.description = description self.items = items class Player: def __init__(self, current_room): self.current_room = current_room self.inventory = [] def move(self, direct...
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The system should be able to create and manage bank accounts, allowing users to deposit, withdraw, and check their balance. Additionally, the program should be able to transfer funds between accounts. Your task is to implement the `BankAcco...
```swift import Foundation class BankAccount { let accountNumber: String var balance: Double init(accountNumber: String, initialBalance: Double) { self.accountNumber = accountNumber self.balance = initialBalance } func deposit(amount: Double) { guard amount > 0 els...
magicoder
swift
You are given a list of integers representing the scores of a game. The game has a specific rule for calculating the final score. The rule is as follows: - If the score is even, it is added to the total score. - If the score is odd, it is subtracted from the total score. Write a function `calculate_final_score` that t...
```python from typing import List def calculate_final_score(scores: List[int]) -> int: final_score = 0 for score in scores: if score % 2 == 0: final_score += score else: final_score -= score return final_score ```
magicoder
python
You are tasked with creating a script to automate the process of checking and updating the Linux kernel version on a system. The script should retrieve the latest stable kernel version from a specified URL and compare it with the current kernel version installed on the system. If the latest version is different from th...
```bash #!/bin/bash checkAndUpdateKernel() { MainURL="$1" currentKernelVer="$2" tmpKernelVer="$(wget -qO- "$MainURL" | grep -o 'v[0-9]\+\.[0-9]\+\.[0-9]\+')" if [ -z "$tmpKernelVer" ]; then echo "Please input a valid kernel version! exp: v4.11.9." exit 1 fi if [ "$tmpKernelVe...
magicoder
shell
You are tasked with creating a script to automate the process of managing encrypted passwords using the `pass` command-line password manager. The script should handle the initialization of `pass` with a GPG key and the addition of new passwords to the password store. The script should also ensure that the GPG key is ge...
```bash #!/bin/bash # Generate a GPG key with specified parameters gpg --no-options --generate-key --batch /protonmail/gpgparams # Check if the GPG key generation was successful if [ $? -eq 0 ]; then echo "GPG key generated successfully" else echo "Error: Failed to generate GPG key" exit 1 fi # Initializ...
magicoder
shell
You are tasked with creating a custom validation function for a Django model in a web application. The function should ensure that a specific field in the model adheres to a certain format. To achieve this, you need to implement a custom validator using Django's validation framework. Your task is to create a custom va...
```python from django.core.exceptions import ValidationError from django.db import models from typing import TypeVar DjangoModelType = TypeVar('DjangoModelType', bound=models.Model) def custom_format_validator(value: str): """ Custom validator function to check if the input value matches a specific format. ...
magicoder
python
You are given the definition of a binary tree node and a function `is_same_tree` that takes in two binary trees `p` and `q` as input. The function is expected to return `True` if the two trees are structurally identical and the nodes have the same value at each position, and `False` otherwise. The function should handl...
```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_same_tree(p: TreeNode, q: TreeNode) -> bool: if not p and not q: return True if not p or not q: return False return p.val == q.va...
magicoder
python
You are tasked with implementing a function to calculate the molecular weight of a compound based on its chemical formula. The molecular weight of a compound is the sum of the atomic weights of all the atoms in the compound. You are given a code snippet that contains part of a function for reading the molecular weight ...
```cpp #include <iostream> #include <string> #include <map> #include <sstream> // Function to calculate the molecular weight of a compound double MolecularWeight(std::istream& is) { // Map to store atomic weights of elements std::map<std::string, double> atomicWeights = { {"H", 1.008}, {"C", 12.011}, {"O", 15....
magicoder
cpp
You are tasked with implementing a Python function that processes a given string to convert it into title case. Title case means that the first letter of each word in the string should be capitalized, while the rest of the letters should be in lowercase. However, there are exceptions to this rule, such as certain words...
```python def to_title_case(s): exceptions = ["and", "the", "of"] # Define the list of words to remain in lowercase words = s.lower().split() # Convert the input string to lowercase and split it into words title_case_words = [word.capitalize() if word not in exceptions or i == 0 else word for i, word in e...
magicoder
python
You are tasked with implementing a graph visualization tool that can display a graph in a graphical user interface (GUI). The graph is represented using an adjacency list. Each node in the graph is represented by a unique integer, and the edges are represented as pairs of integers denoting the connected nodes. You need...
```python import networkx as nx import matplotlib.pyplot as plt class GraphVisualizationTool: def __init__(self): self.graph_fig = plt.figure() self.ax = self.graph_fig.add_subplot(111) def showgraph(self, graph): G = nx.Graph() for node, neighbors in graph.items(): ...
magicoder
python
You are tasked with implementing a custom data transformer class in Python for preprocessing numerical and categorical features. The class should have methods for fitting the transformer to the data and transforming the data based on the fitted transformer. The transformer should scale the numerical features using Stan...
```python import numpy from sklearn.preprocessing import StandardScaler class CustomTransformer: def __init__(self, n_numeric, **params): # Initialize the StandardScaler with the given parameters self.scaler = StandardScaler(**params) # Store the number of numerical features self.n_...
magicoder
python
You are tasked with creating a Python program that performs DNS resolution and scanning for CDS (Child DS) records. The program should utilize multithreading to improve performance and handle potential delays in DNS resolution. Your program should have the following features: 1. Accept a list of domain names as input....
```python import json import threading from queue import Queue, Empty try: from queue import SimpleQueue except ImportError: # Python 3.6 lacks SimpleQueue SimpleQueue = Queue import click import dns.resolver import dns.inet from .dsscanner import do_cds_scan def resolve_dns_and_cds(domain): try: ...
magicoder
python
You are tasked with implementing a custom transformer class for feature engineering in a machine learning pipeline. The class, named `CustomTransformer`, has a method `fit` that takes in a DataFrame `df` and several optional parameters. The method performs some operations on the input DataFrame based on the provided pa...
```python import pandas as pd class CustomTransformer: def __init__(self): self.silence_cols = [] self.select_all = None self.max_num = None self.ops = [] def fit(self, df, degree=1, target=None, df_feature_type=None, silence_cols=[], select_all=True, max_num=None): ass...
magicoder
python
You are tasked with implementing a Python function that processes data from a weather station and calculates the average temperature for each month. The function should handle missing data and allow for customization of units and color maps for visualization. You are given a code snippet from the function that handles...
```python def calculate_average_temperature(data, var_units, color_maps, default_value): # Replace missing temperature data with default_value for month, temperature in data.items(): if temperature is None: data[month] = default_value # Calculate average temperature for each month a...
magicoder
python
You are given a list of weights representing the weights of items to be loaded onto a truck. The truck has a weight capacity of `capacity`. Your task is to implement a function `maximize_load(weights, capacity)` that maximizes the total weight of items that can be loaded onto the truck without exceeding its capacity. Y...
```python from typing import List def maximize_load(weights: List[int], capacity: int) -> int: n = len(weights) dp = [[0] * (capacity + 1) for _ in range(n + 1)] for i in range(1, n + 1): for w in range(1, capacity + 1): if weights[i - 1] > w: dp[i][w] = dp[i - 1][w] ...
magicoder
python
You are tasked with creating a Python script to interact with an RFID reader using the RFIDIOt library. The script should establish a connection with the RFID reader and perform read operations on RFID tags. The RFID reader is connected to the computer via the serial port /dev/ttyUSB0, and the script should communicate...
```python import subprocess # Command to run the Python script using xterm command = "xterm -T 'ACG port /dev/ttyUSB0' -e python ./multiselect.py -s 9600 -l /dev/ttyUSB0 -R RFIDIOt.rfidiot.READER_ACG &" # Execute the command using subprocess subprocess.call(command, shell=True) ``` The provided code snippet is a com...
magicoder
python
You are tasked with simulating the behavior of a simple neuron using the leaky integrate-and-fire (LIF) model. In this model, the membrane potential of the neuron is governed by a simple differential equation. When the membrane potential reaches a certain threshold, the neuron fires a spike and the potential is reset t...
```python from scipy.integrate import odeint def neuron_model(y, t, I): dVdt = (I - y/10) * (1/20) return dVdt def simulate_neuron(input_current, time_period): spike_times = [] V_rest = 10 V_threshold = 30 def spike_detector(y, t): if y[0] >= V_threshold: spike_times.appen...
magicoder
python
You are tasked with implementing a cross-entropy loss function and its gradient calculation using Python and NumPy. The cross-entropy loss function is commonly used in machine learning for classification tasks. The provided code snippet gives a hint about the structure of the functions to be implemented. Your task is ...
```python import numpy as np def cross_entropy(y, y_): assert isinstance(y, np.ndarray) and isinstance(y_, np.ndarray), "Input should be NumPy arrays" assert y.shape == y_.shape, "Input arrays should have the same shape" # Calculate cross-entropy loss loss = -np.sum(y_ * np.log(y)) return loss...
magicoder
python
You are tasked with creating a Python program that interacts with the Telegram messaging platform using the `telethon` library. Your program needs to implement a message retrieval function that operates in "past mode" and requires a user account to function. The "past mode" should handle all existing messages, and the ...
```python # Define the Telegram API credentials api_id = 'your_api_id' api_hash = 'your_api_hash' # Define the user account credentials phone_number = 'your_phone_number' username = 'your_telegram_username' # Initialize the Telegram client client = TelegramClient(username, api_id, api_hash) # Define the function to ...
magicoder
python
You are tasked with implementing a notification system for a social media platform that aggregates notifications from various sources and digests them for user consumption. The system should be able to handle notifications from Reddit, Stack Exchange, and credit card charges. To achieve this, you need to create a notif...
```python from digesters.reddit.reddit_notification_digester import RedditNotificationDigester from digesters.stackexchange.stack_exchange_notification_digester import StackExchangeNotificationDigester from digesters.charges.charge_card_digester import ChargeCardDigester # Initialize instances of the notification dige...
magicoder
python
You are tasked with implementing a custom virtual scrolling feature for a web application. Virtual scrolling is a technique used to efficiently render large lists by only rendering the items that are currently visible on the screen, thus improving performance and reducing memory consumption. Your task is to create a V...
```typescript import { Component, Input, Output, EventEmitter, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-virtual-scroll', template: ` <div class="viewport" (scroll)="onScroll($event)"> <div class="content" [style.transform]="'translateY(' + topPadding + 'px)...
magicoder
typescript
You are tasked with implementing a command-line utility for managing files and directories. The utility should provide various commands for file operations such as creating, deleting, and listing files and directories. Additionally, the utility should support the ability to disable the deletion functionality for specif...
```python class FileUtility: def __init__(self): self.files = [] def create_file(self, filename): self.files.append(filename) @staticmethod def no_delete(cmd): cmd._delete_ctx = False return cmd @no_delete def delete_file(self, filename): if filename in...
magicoder
python
You are tasked with creating a Django admin interface for managing employees in a company. The company already has a User model for authentication and wants to integrate the Employee model into the admin interface. The Employee model is defined in a separate file and needs to be registered with the Django admin. Your ...
```python # admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import Employee class EmployeeAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'department', 'designation', 'email') # Display thes...
magicoder
python
You are tasked with implementing a 1D burgers' equation solver using the finite volume method. The code snippet provided initializes the parameters for the solver. The burgers' equation is given by: ∂u/∂t + ∂(u^2)/∂x = ν * ∂^2u/∂x^2 Where u is the velocity field, t is time, x is the spatial coordinate, and ν is the k...
```python # The solution provided is a complete implementation of the Burgers1d class, including the solve and plot_solution methods. The solve method uses the explicit Euler method to perform time integration of the 1D Burgers' equation, while the plot_solution method visualizes the velocity field at a given time step...
magicoder
python
You are tasked with implementing a unit test for a module in an Intrusion Detection System (IDS) software. The code snippet provided is a part of the unit test for the module. The `ib_module_t` structure represents a module in the IDS software, and the test is validating various properties of this module. Your task is...
```cpp #include <string> #include <iostream> #include <cassert> // Definition of ib_module_t structure struct ib_module_t { std::string name; std::string filename; void* ib; // Assuming ib is a pointer to the Intrusion Detection Engine }; // Mock implementation of m_engine.ib() function namespace m_engin...
magicoder
cpp
You are tasked with creating a function to process and aggregate data from a collection of elements. The input data consists of an array of objects, each representing an element in a subsection. Each object contains properties such as `shortLabel`, `longLabel`, `dropdownLabel`, `dropdownSearchString`, and `dropdownValu...
```typescript function processAndAggregateData(elemsInSubSection: any[]): any[] { const perYearPerRibbonData: any[] = []; const firstElem = elemsInSubSection[0]; const { shortLabel, longLabel, dropdownLabel, dropdownSearchString, dropdownValue } = firstElem; const groupedByYear: Map<number, any[]> = new Map(); ...
magicoder
typescript
You are tasked with implementing a function that processes filter widget settings in a Redux Saga middleware. The function `unapplyFilterWidget()` takes an action object as input and is responsible for unapplying the filter widget settings based on the provided widget ID. The function uses the `sagaHelper` utility to t...
```javascript function* unapplyFilterWidget(action) { const { widgetId } = action.payload; const widgetSettings = yield select(getWidget, widgetId); // Process widgetSettings to unapply filter widget settings // Example: dispatch appropriate action to update the Redux store yield put(updateFilterWidgetSetting...
magicoder
javascript
You are tasked with creating a Discord bot that sends a scheduled message to a specific channel at a given time using Python and the `discord.py` library. The bot should use the `apscheduler` library to schedule the message sending. Your task is to implement the necessary code to achieve this functionality. You are pr...
```python import discord from apscheduler.schedulers.asyncio import AsyncIOScheduler from discord.ext import commands from pytz import utc import asyncio async def schedule_and_send_message(bot_token: str, channel_id: int, message: str, scheduled_time: str): bot = commands.Bot(command_prefix='!', help_command=None...
magicoder
python
You are tasked with creating a Rust program that involves parsing and processing JSON data using the Serde library. Your goal is to define a data structure and implement a function to extract specific information from the JSON data. You are given a JSON response from an API call, which represents a successful response...
```rust use serde_json::Value; #[derive(Debug, Deserialize, Serialize)] struct ChannelData { channel_type: String, name: String, } #[derive(Debug, Deserialize, Serialize)] struct OpenResponse { #[serde(flatten)] pub channel_data: ChannelData, // Other fields in the response } fn extract_channel_i...
magicoder
rust
You are tasked with implementing a function to calculate the Kullback-Leibler (KL) divergence for a variational autoencoder (VAE) model. The function should take in the parameters of two normal distributions and return the reconstruction loss and the total KL divergence. The function should be defined as follows: ```p...
```python def calculate_kl_divergence(ql_m, ql_v, local_l_mean, local_l_var, kl): # Calculate the KL divergence for the latent space kl_divergence_z = kl(Normal(ql_m, torch.sqrt(ql_v)), Normal(0, 1)).sum(dim=1) # Calculate the KL divergence for the local latent space kl_divergence_l = kl(Normal(ql_...
magicoder
python
You are tasked with creating a shell script that automates the process of converting a file written in the "svgbob" format to an SVG file using the "svgbob" CLI tool. The "svgbob" format is a simple textual representation of ASCII art diagrams, and the "svgbob" CLI tool is capable of converting these textual diagrams t...
```bash #!/bin/sh if [ $# -ne 1 ]; then echo "Usage: $0 <input_file>" exit 1 fi input_file=$1 output_file="${input_file%.*}.svg" cargo run --bin svgbob < "$input_file" > "$output_file" ``` In this solution, the shell script first checks if the correct number of command-line arguments is provided. If not, it disp...
magicoder
shell
You are tasked with creating a function that processes a given report aggregator state and returns a new object with the average values for each property. The report aggregator state is represented as an interface `IReportAggregator` with properties `weighted_score`, `time_allocated`, `time_taken`, and `weight`, each o...
```typescript interface IReportAggregator { weighted_score: string; time_allocated: string; time_taken: string; weight: string; } function calculateAverageReportAggregator(reportAggregator: IReportAggregator): IReportAggregator { const properties = Object.keys(reportAggregator); const averageValues: Partia...
magicoder
typescript
You are tasked with creating a program that utilizes a pre-trained clinical BERT model to predict the similarity between pairs of clinical sentences. The clinical BERT model is a specialized language representation model designed for clinical text. The model takes pairs of sentences as input and outputs a similarity sc...
```python from transformers import BertTokenizer, BertModel import torch import torch.nn.functional as F class ClinicalBertSimilarity: def __init__(self): self.tokenizer = BertTokenizer.from_pretrained('emilyalsentzer/Bio_ClinicalBERT') self.model = BertModel.from_pretrained('emilyalsentzer/Bio_Cli...
magicoder
python
You are tasked with creating a function that retrieves data from a database using Laravel's Eloquent ORM. The database contains two tables: `stock_entries` and `books`. The `stock_entries` table stores information about stock entries, including the ISBN of the book, while the `books` table contains details about the bo...
```php // Assuming the function is part of a Laravel application use App\Models\StockEntry; // Replace with the actual namespace and model name use Illuminate\Support\Facades\DB; function retrieveStockEntriesWithTitles() { $stockEntriesWithTitles = StockEntry::join('books', 'books.isbn', '=', 'stock_entries.isbn'...
magicoder
php
You are tasked with creating a Python function that utilizes the GPT (Generative Pre-trained Transformer) model to generate text based on a given prompt. The GPT model is loaded using the provided code snippet, and you need to implement a function that takes a prompt as input and generates a specified number of tokens ...
```python from gpt.src import encoder import gpt_2_simple as gpt2 def generate_text(prompt, num_tokens): model_name = "117M" # Model name used for loading the GPT model sess = gpt2.start_tf_sess() gpt2.load_gpt2(sess, model_name=model_name) enc = encoder.get_encoder(model_name) context_tokens = e...
magicoder
python
You are tasked with implementing a dependency resolution algorithm for a software build system. The build system uses a custom format to define dependencies between different actions. Each action can depend on one or more other actions, and the dependencies are specified in a specific format within the source code. Th...
```python from typing import List def resolve_dependencies(action_deps: dict) -> List[str]: # Create a dictionary to store the dependencies count for each action dependencies_count = {action: 0 for action in action_deps} # Populate the dependencies count based on the given dependencies for dependencie...
magicoder
python