query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function to find the best motifs in a set of DNA sequences. Motifs are short, recurring sequences that are presumed to have biological significance. The function should utilize a scoring system to evaluate the quality of motifs and then return the best motifs based on this scoring. Y...
```python def score(motifs): # This function calculates the score of a set of motifs based on a specific scoring system. # The lower the score, the better the motifs. score = 0 for i in range(len(motifs[0])): column = [motif[i] for motif in motifs] most_common = max(set(column), key=colu...
magicoder
python
You are tasked with implementing a Python function that calculates the total number of valid IP addresses that can be formed using a given string of digits. An IP address consists of four numbers (each ranging from 0 to 255) separated by periods. The input string can contain any number of digits, and the function shoul...
```python def count_valid_ip_addresses(s: str) -> int: def is_valid_segment(segment): return 0 <= int(segment) <= 255 and (len(segment) == 1 or segment[0] != '0') def backtrack(start, parts): if parts == 4: return start == len(s) for i in range(1, 4): if start + ...
magicoder
python
You are given a string `string` containing only uppercase and lowercase English letters. Your task is to write a function or program to count the occurrences of each letter in the string and print the count for each letter in the format: "Letter is Count times". The count should be case-insensitive, meaning that 'A' an...
```python def count_letters(string): counts = {} for char in string: if char.isalpha(): char = char.lower() if char in counts: counts[char] += 1 else: counts[char] = 1 for letter, count in counts.items(): print(f"{letter} i...
magicoder
python
You are tasked with implementing a JavaScript function executor class in C++. The JavaScriptFunctionExecutor class is responsible for executing JavaScript functions within a C++ environment. The class should be able to load and execute JavaScript functions, passing arguments to them and retrieving their return values. ...
```cpp #include <iostream> #include <fstream> #include <string> #include <vector> #include <duktape.h> class JavaScriptFunctionExecutor { public: JavaScriptFunctionExecutor(const std::string& scriptPath) : scriptPath_(scriptPath) { ctx_ = duk_create_heap_default(); } ~JavaScriptFunctionExecutor() ...
magicoder
cpp
You are tasked with implementing a custom Django template filter that converts a given numerical value into a percentage format with a specified number of significant digits. The filter function `to_percent` takes two parameters: `obj`, the numerical value to be converted, and `significant_digits`, the number of signif...
```python @register.filter def to_percent(obj, significant_digits): if obj is None: return "" try: value = float(obj) * 100 # Convert to percentage format_str = "{:.%df}%%" % significant_digits # Create format string with specified significant digits return format_str.format(va...
magicoder
python
You are tasked with implementing a data encoding and decoding process using JavaScript. The provided code snippet demonstrates the usage of encoding and decoding functions, along with assertions to validate the decoded data. Your task is to create a JavaScript function that performs the encoding process and another fu...
```javascript // Solution for the encoding and decoding functions const Enum = { One: 1, Two: 2 }; // Example Enum definition function encode(inputObject) { // Encoding logic const encodedData = { Enums: inputObject.Enums.map(enumVal => enumVal), Strings: inputObject.Strings.map(str => str), ...
magicoder
javascript
You are tasked with creating a Python program that utilizes the Tcam and Gst libraries to capture video from a camera and save it to a file. The Tcam library provides access to industrial cameras, while the Gst library is used for handling multimedia data flow. Your program should initialize the camera, set its propert...
```python import sys import gi gi.require_version("Tcam", "0.1") gi.require_version("Gst", "1.0") from gi.repository import Tcam, Gst def main(): # Initialize Tcam camera camera = Tcam.Camera.new("camera-serial-number") # Replace with actual camera serial number camera.set_property("videoformat", "RGBx"...
magicoder
python
You are tasked with implementing a Python function that processes and analyzes the output of a machine learning model during training. The function will take a string containing the output log of the model and extract specific information from it. The log contains lines of text that include various pieces of informatio...
```python import re def parse_model_output(log: str) -> dict: pattern = r"##-- dev results on epoch iter (\d+) (\d+) (\w+)\s+([\d.]+) \(best f1\) ([\d.]+)\s+([a-zA-Z]+\s[a-zA-Z]+\s\d+\s\d+:\d+:\d+\s\d+) ([\d.]+) ([\d.]+) ([\d.]+)" match = re.match(pattern, log) if match: epoch, iteration, training_...
magicoder
python
You are tasked with implementing a custom sorting web component in JavaScript using the Custom Elements API. The custom element should be defined as "outline-sort-span" and should provide a user interface for sorting a list of items. Your task is to create a custom web component called "outline-sort-span" that allows ...
```javascript class SortSpan extends HTMLElement { connectedCallback() { this.render(); } render() { const items = ['Apple', 'Banana', 'Cherry', 'Date']; // Example list of items items.forEach((item, index) => { const span = document.createElement('span'); span.textContent = item; c...
magicoder
javascript
You are tasked with implementing a performance counter system for a software application. The application has a set of flags that can be passed as command-line arguments, and based on these flags, different functionalities are triggered. Additionally, the application can either read input from a file or generate it int...
```cpp #include <iostream> #include <chrono> #include <map> class PerfCounter { private: static std::map<std::string, std::chrono::high_resolution_clock::time_point> startTimes; public: static void initialize() { startTimes.clear(); } static void startTiming(const std::string& sectionName) { ...
magicoder
cpp
You are tasked with creating a Python class to manage patch sets for a version control system. Your class should include a method to resolve rejected hunks during the patch application process. The code snippet provided is a part of the `Resolve` method within the class. Your task is to implement the `Resolve` method ...
```python import os import bb.data import bb.msg import oe.process class PatchSet: def __init__(self, patchset_dir): self.dir = patchset_dir def Resolve(self): olddir = os.path.abspath(os.curdir) os.chdir(self.dir) try: self.Push(False) except oe.process.Cmd...
magicoder
python
You are given a list of integers `num`. Your task is to write a function that finds the index of the first element in the list such that the element is less than the element immediately to its right. If no such element exists, the function should return -1. Write a function `find_index` that takes in the list `num` as...
```python def find_index(num): i = len(num) - 2 while i >= 0: if num[i] < num[i + 1]: return i i -= 1 return -1 ``` The `find_index` function iterates through the list `num` from the second last element to the first element. It checks if the current element is less than the elem...
magicoder
python
You are tasked with implementing a Python function that processes data and generates a histogram plot using the `matplotlib` library. The function should take in the data, color information, weights, and file name, and produce a histogram plot with specific visual attributes. Write a Python function `generate_histogra...
```python import matplotlib.pyplot as plt def generate_histogram_plot(data, colorbins, wts, file_name, bins): # Transpose the data transposed_data = data.transpose() # Generate the histogram plot n, bins, patches = plt.hist(transposed_data, alpha=0.5, color=colorbins, stacked=True, weights=wts, bi...
magicoder
python
You are tasked with implementing a height calculation feature for a web view using promises. The code snippet provided uses a fictional promise library and a WKWebView instance to demonstrate the usage of promises for asynchronous height calculation. Your task is to create a function that calculates the height of the w...
```swift import PromiseKit extension WKWebView { func calculateHeight() -> Promise<CGFloat> { return Promise { seal in self.evaluateJavaScript("document.body.scrollHeight") { result, error in if let error = error { seal.reject(error) } else if...
magicoder
swift
You are tasked with implementing a function that rotates a given 3D point around the x, y, and z axes by specified angles. The function should take the initial 3D point coordinates and the rotation angles as input and return the new coordinates after the rotation. The function signature should be: ```python def rotate...
```python import math def rotate_3d_point(point, alpha, beta, gamma): x, y, z = point alpha_rad = math.radians(alpha) beta_rad = math.radians(beta) gamma_rad = math.radians(gamma) # Rotation around x-axis new_y = y * math.cos(alpha_rad) - z * math.sin(alpha_rad) new_z = y * math.sin(alpha_...
magicoder
python
You are tasked with implementing a role-based access control system for a web application. The provided code snippet is a part of the access control logic in Python using the Flask-Security library. The code snippet demonstrates how permissions are assigned based on the roles of users. Your task is to create a functio...
```python from flask_principal import Permission, RoleNeed def get_permission_for_role(role: str) -> Permission: if role == 'admin': return Permission(RoleNeed('admin')) elif role == 'employee': return Permission(RoleNeed('employee')) elif role == 'employeer': return Permission(Role...
magicoder
python
You are tasked with creating a photo management system for a photography application. The system should allow users to add, display, and save photo data. Your task is to implement the functionality to display a photo caption and to exit the application, ensuring that the photo data is saved before exiting. You are pro...
```java import javafx.application.Application; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; public class PhotoManagementSystem extends Application { @FXML private Label displayPhotoText; // Method to display the photo c...
magicoder
java
You are tasked with implementing a Python function to perform eigenvalue decomposition and validation for a symmetric matrix. Eigenvalue decomposition is a fundamental concept in linear algebra and has numerous applications in various fields such as physics, engineering, and computer science. You are given the followi...
```python import numpy as np from typing import Tuple from numpy.linalg import eigh, norm def eigen_decomposition(matrix: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Perform eigenvalue decomposition of a symmetric matrix.""" eigenvalues, eigenvectors = eigh(matrix) return eigenvalues, eigenvectors de...
magicoder
python
You are tasked with creating a Python program that processes command-line arguments and generates an HTML file based on a given graph file. The program should handle exceptions and print the result to the standard output. Your task is to implement the `html_exporter` function, which takes two parameters: `graph_file_p...
```python import sys import os import networkx as nx import matplotlib.pyplot as plt def html_exporter(graph_file_path, new_file_path): try: # Read graph data from the input file with open(graph_file_path, 'r') as file: edges = [line.split() for line in file.readlines()] # Crea...
magicoder
python
You are tasked with implementing a function that processes a series of masks and returns the areas of the contours within each mask. The masks are represented as 2D arrays, where each element is either 0 or 1. The contours are defined by the 1s in the array, and the area of a contour is the number of connected 1s withi...
```python from typing import List, Tuple def process_masks(masks: List[List[List[int]]]) -> Tuple[List[int], List[<some_type>]]: def cont2area(mask): def dfs(i, j): if 0 <= i < len(mask) and 0 <= j < len(mask[0]) and mask[i][j] == 1: mask[i][j] = 0 return 1 + sum...
magicoder
python
You are tasked with creating a Python script that simulates a simple banking system. The script should allow users to create accounts, deposit funds, withdraw funds, and check their balance. To achieve this, you will need to implement a class called `BankAccount` with appropriate methods and attributes. The `BankAccou...
```python class BankAccount: def __init__(self, account_number, account_holder, balance): self.account_number = account_number self.account_holder = account_holder self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): i...
magicoder
python
You are tasked with implementing a simple banking system that supports account withdrawals. The provided code snippet is a part of a Rust program that defines a method for withdrawing funds from a bank account. Your task is to complete the implementation of the `withdrawal` method and handle various scenarios related t...
```rust pub struct Account { balance: f64, max_withdrawal: f64, } pub struct Withdrawal { amount: f64, timestamp: u64, } impl Account { pub fn withdrawal(&self, amount: f64, timestamp: u64) -> Option<Withdrawal> { if amount > self.balance { return None; // Insufficient funds ...
magicoder
rust
You are tasked with creating a Python function to read light intensity from a sensor and publish the data to an MQTT broker. The sensor is connected to the Raspberry Pi via the I2C bus. The sensor supports different measurement modes, including continuous high-resolution mode 1, continuous high-resolution mode 2, one-t...
```python import smbus import paho.mqtt.publish as publish def read_light(mode, sensor_address, bus, broker, port, topic): # Set the measurement mode if mode == CONTINUOUS_HIGH_RES_MODE_1 or mode == CONTINUOUS_HIGH_RES_MODE_2 or mode == ONE_TIME_HIGH_RES_MODE_1 or mode == ONE_TIME_HIGH_RES_MODE_2 or mode == ON...
magicoder
python
You are tasked with implementing a test execution monitoring system for a software testing framework. The system should calculate the total time taken for test execution and notify a listener when all tests have been completed. You are provided with a code snippet from the existing system, which includes a method `endT...
```java import java.util.List; public class TestExecutionMonitor { private ListenerSupport listenerSupport; private Interpreter interpreter; public TestExecutionMonitor(ListenerSupport listenerSupport, Interpreter interpreter) { this.listenerSupport = listenerSupport; this.interpreter = in...
magicoder
java
You are tasked with creating a module loader for a JavaScript application. The module loader should be able to import and export modules using the ES6 module syntax. Your task is to implement a function that can parse and load the modules based on the provided code snippet. You are given a code snippet that demonstrat...
```javascript const loadModules = (codeSnippet) => { const modules = {}; const moduleRegex = /export \* as (\w+) from "([^"]+)";/g; let match; while ((match = moduleRegex.exec(codeSnippet)) !== null) { const [, moduleName, modulePath] = match; const module = require(modulePath); modules[moduleName]...
magicoder
javascript
You are tasked with creating a program that processes and displays images using Python's OpenCV and Matplotlib libraries. The program should read an image file, convert it to grayscale, and display the grayscale image using the appropriate library based on user input. Your program should have the following functionali...
```python import cv2 import matplotlib.pyplot as plt def display_image(image_path): # Read the image using OpenCV image = cv2.imread(image_path) # Convert the image to grayscale grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Prompt the user to choose the display method display_ch...
magicoder
python
You are tasked with implementing a function to count the instances of specific patterns in a set of files. The function should take in the files to be analyzed, a set of expressions to base the counting on, and the patterns of strings to search for within the files. Your task is to write a function that returns a map o...
```javascript function countInstances(files, expressions, patterns) { const fs = require('fs'); const patternCounts = new Map(); for (const pattern of patterns) { patternCounts.set(pattern, 0); } for (const file of files) { const fileContent = fs.readFileSync(file, 'utf8'); for (const expression...
magicoder
javascript
You are tasked with creating a Python function that simulates the behavior of the `async_init` method in the context of Home Assistant's configuration flow. The `async_init` method is used to initialize a configuration flow for a specific domain in Home Assistant, and it returns a result that contains information about...
```python import asyncio async def simulate_async_init(domain: str, source: str, data: dict) -> dict: # Simulate the behavior of async_init method if domain == "DOMAIN" and source == "SOURCE_USER": # Simulate the initialization result for the specified domain and source result = { "...
magicoder
python
You are given a Python function `size_of_state(x, k, window_size)` that takes in three parameters: - `x`: a list of numerical values representing a time series data. - `k`: a positive integer representing a scaling factor. - `window_size`: a positive integer representing the size of the sliding window. The function ca...
```python import numpy as np def find_min_state_size(x, k, window_size): sos_temp = [] for i in range(1 + len(x) - window_size): subarray = x[i : i + window_size] std_dev = np.std(subarray, ddof=1) sos_temp.append(std_dev) if not sos_temp: return 0 else: return m...
magicoder
python
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the average score of the game, excluding the lowest and highest scores. Write a function `calculateAverage(scores)` that takes in a list of integers `scores` (2 <= len(scores) <= 100) and returns the av...
```python def calculateAverage(scores): if len(scores) < 3: return "At least 3 scores are required to calculate the average." sorted_scores = sorted(scores) trimmed_scores = sorted_scores[1:-1] # Exclude the lowest and highest scores average = sum(trimmed_scores) / len(trimmed_scores) retu...
magicoder
python
You are tasked with creating a Python module for managing a distributed storage system. The module will be used to perform various operations on the storage nodes, such as adding new nodes, removing existing nodes, and modifying storage configurations. Your task is to implement the logic for the module's main function,...
```python import requests def manage_storage_node(state, api_user, api_host, api_password, validate_certs, node, storage, timeout): api_url = f"https://{api_host}/storage/nodes" headers = {'Content-Type': 'application/json'} auth = (api_user, api_password) verify_cert = validate_certs if state ==...
magicoder
python
You are tasked with creating a Python function that validates and processes input data for a module using the given code snippet as a reference. Your function should perform the following tasks: 1. Validate the input arguments based on the provided specifications. 2. Process the input data to ensure it adheres to the ...
```python def process_module_data(mod_yaml, name, stream, version, context, arch, summary, description, module_licenses, content_licenses, rpms_nevras): # Validate input arguments if not isinstance(mod_yaml, str) or not mod_yaml: raise ValueError("mod_yaml must be a non-empty string") if not isinsta...
magicoder
python
You are tasked with creating a Java class that represents a form in a web application using Selenium. The form has various fields, and you need to define the form fields and their corresponding locators. Your task is to create a class called `MarketplaceForm` that extends the `BaseMarketplaceForm` class and implements...
```java import diaceutics.selenium.enums.pageFields.FormFieldInterface; import diaceutics.selenium.pageobject.BaseMarketplaceForm; import org.openqa.selenium.By; public class MarketplaceForm extends BaseMarketplaceForm implements FormFieldInterface { public By firstName = By.id("firstNameLocator"); public By l...
magicoder
java
You are tasked with implementing a custom macro in Rust that modifies the behavior of a given function. The macro, `with_method!`, takes a function as an argument and generates a new function that includes additional functionality. The additional functionality is determined by the provided documentation comment, which ...
```rust macro_rules! with_method { ( $(#[$attr:meta])* fn $func:ident ( $($arg:ident : $arg_type:ty),* ) -> $ret_type:ty $body:block ) => { $(#[$attr])* fn $func ( $($arg : $arg_type),* ) -> $ret_type { $body } }; ( $(#[$attr:meta])* fn...
magicoder
rust
You are tasked with designing a photo management system for a social media platform. The system should allow users to upload photos, add captions, and generate thumbnails for display. You are provided with a code snippet from the existing photo interface implementation in Rust. Your task is to extend the functionality ...
```rust // Define the ImageBitmap struct struct ImageBitmap { // Define the properties of the ImageBitmap width: u32, height: u32, // Other properties as needed } // Define the utility module for photo operations mod photo_utility { use super::ImageBitmap; // Define the function to generate a ...
magicoder
rust
You are tasked with implementing a Python class that aggregates batches of data. The class should have the ability to inherit from a base class and provide specific functionality for different types of data. Your task is to create a class called `DataBatch` that inherits from a base class called `Batch`. The `DataBatch...
```python class Batch: def __init__(self, common=None): self._common = common def flush(self): raise NotImplementedError("flush method must be implemented in subclasses") class DataBatch(Batch): pass class SpanBatch(DataBatch): def __init__(self, tags=None, common=None): sup...
magicoder
python
You are tasked with creating a function that processes a given HTML template and extracts all the unique URLs present in the `img` tags. The function should return a list of these unique URLs. For example, given the following HTML template: ```html <div class="logo pull-left"> <a href="{{ url('/') }}"><img src="{{...
```python from bs4 import BeautifulSoup from typing import List def extract_img_urls(html: str) -> List[str]: soup = BeautifulSoup(html, 'html.parser') img_tags = soup.find_all('img') img_urls = [tag['src'] for tag in img_tags if 'src' in tag.attrs] return list(set(img_urls)) ``` The `extract_img_urls...
magicoder
python
You are tasked with creating a Python script that processes video files based on metadata provided in a separate file. The script should take in command-line arguments to specify the metadata file and the target directory for the processed video files. The metadata file contains information about the video files to be...
```python import argparse import subprocess import os def get_formatted_time(seconds): return '{:02d}:{:02d}:{:02.2f}'.format(int(seconds // 3600), int((seconds % 3600) // 60), seconds % 60) def process_video(metadata_file, target_dir): with open(metadata_file, 'r') as file: for line in file: ...
magicoder
python
You are tasked with creating a Rust program that utilizes traits and asynchronous programming. Your goal is to implement a trait for making API requests and then use it to define a specific request type. Your task is to complete the implementation of the `PandoraApiRequest` trait and create a struct that represents a ...
```rust use async_trait::async_trait; use serde::Serialize; use serde::de::DeserializeOwned; #[async_trait] pub trait PandoraApiRequest: Serialize { type Response: DeserializeOwned; async fn make_request(&self) -> Result<Self::Response, reqwest::Error>; } pub struct SpecificApiRequest { // Include any ne...
magicoder
rust
You are tasked with implementing a file usage quota system for users in a file management application. The provided code snippet outlines the structure of the file usage quota system. The `UserFileUsageQuota` struct contains a field `kind` of type `UserFileUsageQuotaKind`, which is an enum defining two variants: `Unlim...
```rust // Define the UserFileUsageQuotaKind enum enum UserFileUsageQuotaKind { Unlimited, LimitedNumberOfBytes(u64), } // Define the UserFileUsageQuota struct struct UserFileUsageQuota { kind: UserFileUsageQuotaKind, } impl UserFileUsageQuota { // Constructor method to create a new UserFileUsageQuota...
magicoder
rust
You are tasked with implementing a custom file management system for a deep learning model training process. The system should handle the storage and retrieval of model weights at different epochs. The code snippet provided is a part of a class that manages the storage and retrieval of model weights in PyTorch. The `DO...
```python import torch # Example usage of the ModelFileManager class if __name__ == "__main__": # Create an instance of ModelFileManager model_file_manager = ModelFileManager() # Example usage of saving and loading model weights train_dir = "path/to/train_dir" epoch = 10 model = YourModelClass...
magicoder
python
You are given a code snippet that involves a Just-In-Time (JIT) compiler for a simple function. Your task is to write a program that simulates the execution of the given code snippet and computes the result of the function call. The code snippet involves the creation of a JIT function, addition of two parameters, and ...
```rust fn jit_function_execution(x: i32, y: i32) -> i32 { let ctx = jit_context_create(); let sig = jit_type_create_signature( jit_abi_cdecl, jit_type_int, vec![jit_type_int, jit_type_int] ); let func = jit_function_create(ctx, sig); let x_param = jit_value_get_param(func...
magicoder
rust
You are tasked with implementing a simple server management system. The system should allow for starting a server, serving requests indefinitely, and gracefully shutting down the server when requested. You are provided with a code snippet that partially implements this functionality using Python. Your task is to comple...
```python import argparse import http.server import socketserver import signal class CustomHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write(b'Hello, World!') def please_exit(signum, frame): print("Shutting down...
magicoder
python
You are tasked with implementing a custom deserialization feature for a data class in Python. The data class is designed to accept input in various date and time formats and convert them into the appropriate Python objects using the Pendulum library for date and time manipulation. Your task is to create a `DataClass` ...
```python from dataclasses import dataclass, field from datetime import datetime, date, timezone import pendulum class DataClassDictMixin: @classmethod def from_dict(cls, data): fields = cls.__dataclass_fields__ kwargs = {name: pendulum.parse(data[name], **fields[name].metadata.get('deserialize...
magicoder
python
You are tasked with creating a token management system for a web application. The system should include a requirement checker to determine if a token check is required for a specific route and a token manager to retrieve the token for the route. You are given a code snippet that sets up mock objects for the requirement...
```php class TokenManager { private $requirementChecker; private $tokenManager; public function __construct(TokenRequirementChecker $requirementChecker, RoutingTokenManager $tokenManager) { $this->requirementChecker = $requirementChecker; $this->tokenManager = $tokenManager; } ...
magicoder
php
You are given a dataset containing two sets of performance metrics: precision and recall. Your task is to visualize these metrics using box plots and swarm plots. The dataset is represented by two DataFrames, `df_prec` for precision and `df_rec` for recall. Each DataFrame contains multiple columns, each representing a ...
The `visualize_metrics` function takes in the precision and recall DataFrames and creates a side-by-side visualization of the metrics using box plots and swarm plots. It uses the `matplotlib` and `seaborn` libraries to achieve this. The function returns the created figure and axes for further customization if needed.
magicoder
python
You are tasked with creating a program that analyzes a given source code file and identifies potential formatting issues based on a set of specified code style rules. The code snippet provided is a command for the `indent` tool, which is commonly used to automatically format source code according to a defined style gui...
```python import re def check_code_style(file_path): issues = [] with open(file_path, 'r') as file: lines = file.readlines() for i, line in enumerate(lines): # Check for tabs used for indentation if '\t' in line: issues.append(f"Tab used for indentation o...
magicoder
python
You are given a list of integers representing the scores of a game. The game has a rule that a player's score is the sum of the scores of the last two turns. However, if the last two scores are the same, the player's score is doubled. Your task is to write a function that calculates the total score for the given list o...
```python def calculate_total_score(scores): total_score = 0 prev_score = 0 prev_prev_score = 0 for score in scores: if score == prev_score: total_score += 2 * score else: total_score += score prev_prev_score = prev_score prev_score = score ret...
magicoder
python
You are tasked with creating a script to automate the versioning of iOS projects. The script needs to update the CFBundleVersion and CFBundleShortVersionString in the Info.plist file of an iOS project. The CFBundleVersion should be set to the provided $VERSION, and the CFBundleShortVersionString should be set to the fi...
```bash #!/bin/bash # Extract the first component of the version V1=`echo $VERSION|cut -d. -f1` # Update CFBundleVersion in Info.plist /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $VERSION" "$IOS_PROJECT_PATH/platforms/ios/$PROJECT_NAME/$PROJECT_NAME-Info.plist" # Update or add CFBundleShortVersionString in Info...
magicoder
shell
You are tasked with implementing a Python class that simulates a village populated with villagers. The village is represented by a grid, and each villager is placed at a specific coordinate on the grid. Your task is to complete the `populate()` method of the `Village` class, which iterates over the number of villagers ...
```python def populate(self): global bad_file # Assuming bad_file is a global variable used within the class for i in range(self.population): # Assuming villagers are represented as tuples of (x, y) coordinates villager_x = # generate or retrieve the x coordinate for the villager villa...
magicoder
python
You are tasked with creating a Python function that parses a SQL query and extracts the table names mentioned in the query. The SQL query may contain multiple table names and may include various SQL syntax elements such as joins, subqueries, and aliases. Write a function `extract_table_names(sql_query: str) -> List[st...
```python import re from typing import List def extract_table_names(sql_query: str) -> List[str]: table_names = set() # Regular expression to match table names after keywords FROM, JOIN, and ON pattern = r'(?:FROM|JOIN|INNER JOIN|LEFT JOIN|RIGHT JOIN|FULL JOIN|CROSS JOIN|NATURAL JOIN|ON)\s+([\w.]+)(?:\s+AS...
magicoder
python
You are tasked with implementing a Sounding data structure in Rust to store atmospheric data from weather stations. The Sounding structure should allow for the storage of various atmospheric parameters such as source description, station information, valid time, pressure profile, height profile, temperature profile, de...
```rust struct Sounding { source_description: String, station_info: Option<StationInfo>, valid_time: Option<ValidTime>, pressure_profile: Vec<f64>, height_profile: Vec<f64>, temperature_profile: Vec<f64>, dew_point_profile: Vec<f64>, theta_e_profile: Vec<f64>, wind_profile: Vec<WindD...
magicoder
rust
You are tasked with implementing a cipher storage factory that can generate instances of different types of ciphers. The factory should support the creation of instances for various types of ciphers, such as Caesar cipher, Vigenère cipher, and Substitution cipher. Each cipher instance should be capable of both encrypti...
```java import java.util.HashMap; import java.util.Map; public final class CipherStorageFactory { private Map<String, Cipher> ciphers; public CipherStorageFactory() { ciphers = new HashMap<>(); // Initialize the factory with instances of different ciphers ciphers.put("caesar", new Caes...
magicoder
java
You are given a Python class `Calculation` with the following methods: ```python class Calculation: def __init__(self, abs_calc, obs, calc): self.abs_calc = abs_calc self.obs = obs self.calc = calc def calculate(self, ac): if ac == 0: if self.obs == 0: ...
```python class Calculation: def __init__(self, abs_calc, obs, calc): self.abs_calc = abs_calc self.obs = obs self.calc = calc def calculate(self, ac): if ac == 0: if self.obs == 0: return 2 return -1.e160 return 2 - (2 * self.calc...
magicoder
python
You are tasked with implementing a custom hook in React that will conditionally execute an effect only when the code is running in a browser environment. The custom hook should mimic the behavior of the built-in `useEffect` hook, but it should only run when the code is executed in a browser environment. You are provid...
```javascript import { useEffect } from 'react'; export const useInBrowser = (effect, deps) => { if (typeof window !== "undefined") { useEffect(effect, deps); } } ``` The solution involves using the `useEffect` hook from the React library within the `useInBrowser` custom hook. The `typeof window !== "...
magicoder
javascript
You are tasked with implementing a command-line utility for slicing media files. The utility should accept a specified number of slices and a list of input files, and then proceed to cut each input file into the specified number of slices. Your task is to complete the implementation of the `main` function, which parse...
```python import sys import getopt helptext = """ Cuts a media file into multiple slices usage: schneider.py -n slices files... """ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hn:") if not opts and not args: print("No command-line arguments provided. Use -h for help.") ...
magicoder
python
You are tasked with designing a URL shortening service using Python and MongoDB. The code snippet provided is a part of the data model for the shortened URLs. The `shortUrl` field stores the shortened URL, `date_submitted` records the date and time when the URL was submitted, and `usage` keeps track of the number of ti...
```python import random import string import datetime class URLShortener: def __init__(self, db): self.db = db def shorten_url(self, long_url): short_url = self.generate_short_url() self.db.ShortenedURLs.insert_one({ 'shortUrl': short_url, 'longUrl': long_url, ...
magicoder
python
You are tasked with implementing a function that calculates the average of a list of floating-point numbers, excluding any outliers. An outlier is defined as a value that differs significantly from the rest of the data. In this case, a value is considered an outlier if it is not "close" to the average of the other valu...
```rust pub fn calculate_average_without_outliers(data: &[f32], precision: f32) -> f32 { let mut sum = 0.0; let mut count = 0; for &value in data { let mut is_outlier = false; for &other_value in data { if value != other_value && !close(value, other_value, precision) { ...
magicoder
rust
You are tasked with creating a program that generates a 3D plot using a given dataset and specific plot settings. The program should take the dataset and plot settings as input and produce a PNG image of the 3D plot as output. The input will consist of the following: - A dataset, represented as an array of numerical v...
```javascript const gnuplot = require('gnuplot'); // Assuming the use of gnuplot library for generating plots function generate3DPlot(dataset, title, outfile) { const script = ` set term png size 1770, 325 set output "${outfile}.png" set title "${title .split(" ") .map(s => s.charAt(0).toUppe...
magicoder
javascript
You are tasked with creating a Python function that processes file paths based on a given module name. The function should generate an ordered list of paths to look for the module in, considering various file extensions and package structures. Write a Python function `generate_module_paths` that takes in two parameter...
```python import os def generate_module_paths(fullname, sys_path): package_prefix = fullname.split('.')[0] + '.' # Extract package prefix from fullname real_path = os.path.join(*fullname[len(package_prefix):].split('.')) # Generate real path for the module paths = [] # Initialize list to store generate...
magicoder
python
You are given a list of coordinate sets, where each coordinate set is represented as a list of tuples. Your task is to write a function to stack these coordinate sets in sequence vertically (row-wise) to create a 2D array. The length of each coordinate set varies, and the resulting 2D array should accommodate the maxim...
```python from typing import List, Tuple def stack_coordinate_sets(coord_sets: List[List[Tuple[int, int]]]) -> List[List[int]]: max_length = max(len(coord_set) for coord_set in coord_sets) # Find the maximum length among all coordinate sets stacked_array = [] for coord_set in coord_sets: padded_c...
magicoder
python
You are tasked with simulating a motion detection system using Python. The system will utilize a motion sensor to detect movement and count the number of times motion is detected. You are provided with a code snippet that initializes a motion sensor, waits for 30 seconds to allow the sensor to learn the environment, an...
```python import time class MotionSensor: def __init__(self, pin: int): self.pin = pin def wait_for_motion(self): # Simulate motion detection pass def simulate_motion_detection(iterations: int) -> int: num = 0 pir = MotionSensor(4) print("Waiting 30s while motion detector ...
magicoder
python
You are tasked with implementing a function that processes a given array of strings and returns the longest common prefix among all the strings. The longest common prefix is the longest string that is a prefix of all the strings in the array. If there is no common prefix, an empty string should be returned. You are gi...
```python from typing import List def longestCommonPrefix(strs: List[str]) -> str: if not strs: return "" # Sort the array to ensure that the shortest string is at the beginning and the longest at the end strs.sort() # Compare the first and last strings to find the common prefix first = s...
magicoder
python
You are tasked with implementing a function to parse and extract data from an HTML table. The function should take an HTML string containing a table and return the data in a structured format. You are given the following HTML snippet as an example: ```html <table> <thead> <tr> <th>Name</th> <th>Age<...
```javascript function parseHTMLTable(html) { const tableData = []; const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table'); const headers = Array.from(table.querySelectorAll('th')).map(th => th.textContent); table.querySelectorAll('tbody tr').forEach(row => { const rowData ...
magicoder
javascript
You are given a string representing a series of parentheses. Your task is to determine if the parentheses are balanced. A string of parentheses is considered balanced if every opening parenthesis has a corresponding closing parenthesis and they are properly nested. Write a function `isBalancedParentheses` that takes a...
```javascript function isBalancedParentheses(str) { const stack = []; const opening = '('; const closing = ')'; for (let char of str) { if (char === opening) { stack.push(char); } else if (char === closing) { if (stack.length === 0) { return false; // More closing parentheses than...
magicoder
javascript
You are tasked with creating a Python function that processes a list of database migration operations and extracts specific information from it. The function should identify the names of the models being created and the dependencies they have on other models. You are given a list of migration operations, where each op...
```python def extract_migration_info(operations): model_dependencies = {} for op in operations: if op["operation"] == "CreateModel": model_dependencies[op["name"]] = op["dependencies"] elif op["operation"] in ["AddField", "AlterField"]: model_name = op["name"] ...
magicoder
python
You are tasked with implementing a Python function that processes a given list of strings and returns a new list containing only unique strings in the original list. However, the given code snippet contains a bug that prevents the function from working as intended. Your task is to identify and fix the bug in the code s...
The bug in the code snippet is the indentation of the `return` statement. It should be aligned with the function definition. After fixing the bug, the corrected code snippet is as follows: ```python def get_unique_strings(input_list: List[str]) -> List[str]: unique_strings = [] for string in input_list: ...
magicoder
python
You are given a Python class `MyClass` with a method `enum()` that returns an iterator over a sequence of elements. Your task is to implement a custom iterator that iterates over the elements returned by `MyClass.enum()` and returns the elements in reverse order. Your custom iterator class `ReverseIterator` should hav...
```python class ReverseIterator: def __init__(self, my_class_instance): self.elements = list(my_class_instance.enum())[::-1] self.index = 0 def __iter__(self): return self def __next__(self): if self.index < len(self.elements): element = self.elements[self.index...
magicoder
python
You are tasked with implementing a statistical calculation for a given probability distribution. The cumulative probability of a continuous random variable is the probability that the variable takes a value less than or equal to a given number. Your task is to create a program that calculates the cumulative probability...
```java import org.apache.commons.math.MathException; import org.apache.commons.math.distribution.NormalDistributionImpl; public class CumulativeProbabilityCalculator { public static void main(String[] args) { double lowerBound = -1.96; double upperBound = 1.96; double expectedCumulativePro...
magicoder
java
You are tasked with implementing a Python decorator that validates the input arguments of a method in a class. The decorator should ensure that the method's input arguments are of a specific type and raise an error if the input does not match the expected type. Your task is to complete the implementation of the `input...
```python class DataProcessor: def __init__(self): pass def input_type_validator(expected_type): def decorator(func): def wrapper(self, *args, **kwargs): input_arg = args[0] if not isinstance(input_arg, expected_type): raise TypeEr...
magicoder
python
You are tasked with implementing a class that represents a resizable and rotatable element on a canvas. The class should have properties for position, width, height, rotation, minimum width, and minimum height. Additionally, it should provide a method to convert its properties to a model representation. Your task is t...
```swift func toModel() -> CanvasElementProperties { return CanvasElementProperties(position: position, width: width, height: height, rotation: rotation, minimumWidth: minimumWidth, minimumHeight: minimumHeight) } ``` In the solution, the `toModel` method simply creates a new `CanvasElementProperties` object using...
magicoder
swift
You are tasked with creating a program that analyzes a given C++ code snippet to identify and extract specific information. The code snippet provided is part of a larger program and contains comments and function calls. Your task is to write a program that can extract the following information from the code snippet: 1....
```cpp #include <iostream> #include <string> int main() { std::string codeSnippet = R"( } else { DPRINTF(OzoneLSQ,"D-Cache: Write Hit on idx:%i !\n", inst->sqIdx); // DPRINTF(Activity, "Active st accessing mem hit [sn:%lli]\n", // ...
magicoder
cpp
You are tasked with implementing a word guessing game. The game involves a function to process the user's input and another function to match the input with a hidden word and update the game state. You need to implement the following functions: 1. `process_input(input_guess: str) -> str`: This function takes a user's...
```python def process_input(input_guess: str) -> str: """ Process the user's input guess by converting it to uppercase and prompting for a valid input if the format is incorrect. :param input_guess: str, the user's input guess. :return: str, the processed input guess in uppercase. """ while True...
magicoder
python
You are tasked with implementing a function to set up NAT port mapping using UPnP (Universal Plug and Play) protocol. The function should attempt to set up port mapping on multiple UPnP devices and handle any failures gracefully. You are given a code snippet that attempts to set up port mapping on UPnP devices. The sn...
```python import logging class PortMapFailed(Exception): pass def setup_port_mapping(devices): logger = logging.getLogger(__name__) for upnp_dev in devices: try: # Attempt to set up port mapping using the UPnP device's location # If successful, return without attempting on ...
magicoder
python
You are working on a natural language processing (NLP) project and need to create a program to preprocess and classify movie reviews. The goal is to build a machine learning model that can accurately classify movie reviews as positive or negative based on their content. To achieve this, you need to preprocess the raw t...
```python import re from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import SVC from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score def get_clean_review(raw_review): # Function to clean the raw mov...
magicoder
python
You are given a string `stream` and its reverse `reverse`. Your task is to write a function to determine the length of the longest prefix of `stream` that is also a suffix of `reverse`. If there is no such prefix, the function should return -1. Write a function `longest_prefix_suffix(stream: str, reverse: str) -> int`...
```python def longest_prefix_suffix(stream: str, reverse: str) -> int: if stream == reverse: return len(stream) elif stream[1:] != reverse[:-1]: return len(stream) - 1 else: return -1 ``` The function `longest_prefix_suffix` first checks if the `stream` is equal to `reverse`. If they...
magicoder
python
You are tasked with creating a function that generates a random username for a new user. The username should consist of a combination of the user's first name and a random string of characters. The random string of characters should be of a specified length and can include uppercase letters, lowercase letters, and digi...
```python import random import string def generate_username(first_name, random_length): random_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(random_length)) padded_first_name = first_name.ljust(random_length, random.choice(string.ascii_letters + string.digits)) return ...
magicoder
python
You are tasked with creating a program that allows users to search for a specific name within a list of names. The program should repeatedly prompt the user to enter a name until the user decides to quit by entering a blank name. The program should then search for the entered name within a predefined list of names and ...
```python def search_name(name_list, target_name): return target_name.casefold() in [name.casefold() for name in name_list] def main(): names = ["alice", "bob", "charlie", "david", "emma"] while True: print("Enter a name: (blank to quit)") name = input().strip() if name == "": ...
magicoder
python
You are tasked with creating a Python script that monitors a directory for changes and automatically reloads a web application when any HTML files in the directory are modified. You should implement a function that takes the directory path as input and continuously monitors it for changes. When an HTML file is added, r...
```python import os import time from web import app from glob import glob def monitor_directory(directory_path: str) -> None: # Get the initial set of HTML files in the directory initial_files = set(glob(os.path.join(directory_path, '*.html'))) while True: # Get the current set of HTML files in th...
magicoder
python
You are tasked with implementing a function to decode an image from a file in a C++ program. The function `DecodeImageFromFile` takes three parameters: the file path of the image, the width, and the height. The function should read the image file and decode it into the specified dimensions. However, the provided code s...
```cpp #include <iostream> #include <stdexcept> void DecodeImageFromFile(const std::string& filePath, int width, int height) { // Check if the file is a valid image file (pseudo-code for demonstration purposes) if (!IsImageFile(filePath)) { throw std::runtime_error("Invalid image file: " + filePath); ...
magicoder
cpp
You are tasked with implementing a hash grid data structure that supports encoding and decoding of key-value pairs. The `HashEncoder` class provides methods for encoding and decoding data using a hash grid. The hash grid is a two-dimensional grid where each cell can store multiple key-value pairs. The `HashEncoder` cla...
```python class HashEncoder: def __init__(self, grid_size): self.grid = [[{} for _ in range(grid_size)] for _ in range(grid_size)] def encode(self, key, value): hash_val = hash(key) x, y = hash_val % len(self.grid), hash_val // len(self.grid) self.grid[x][y][key] = value de...
magicoder
python
You are tasked with implementing a download service for a wallpaper application called EarthWallpaper. The download service should be able to asynchronously download images from the internet and save them to the local storage. The provided code snippet outlines the beginning of the `DownloadService` class, which is exp...
```csharp using System; using System.IO; using System.Net; using System.Threading.Tasks; namespace EarthWallpaper { public class DownloadService : IDownloadService { public async Task DownloadImageAsync(string imageUrl, string destinationPath) { try { usi...
magicoder
csharp
You are working for a cybersecurity company that is developing a tool to recover corrupted files. Your task is to implement a function that takes a user's credentials and a password and returns a command line to execute a recovery process. You are given the following code snippet as a starting point: ```python def fi...
```python from typing import Tuple, Callable class CommandLine: def __init__(self, command: str): self.command = command def recover_files(directory: str) -> None: # Implement the file recovery logic based on the input directory pass def password(user: str, password: str) -> Tuple[CommandLine, Ca...
magicoder
python
You are tasked with implementing a function that determines whether a given React component is being rendered on the server or the client. The function should return `true` if the component is being rendered on the server (i.e., when `window` is not defined), and `false` if it is being rendered on the client (i.e., whe...
```javascript const isServerRender = (component) => { // Check if the window object is defined return typeof window === 'undefined'; }; ``` The `isServerRender` function simply checks whether the `window` object is defined. If it is not defined, the function returns `true`, indicating that the component is being r...
magicoder
javascript
You are tasked with creating a function that parses a given HTML code snippet and extracts the attributes of the anchor (`<a>`) tag. The function should return a dictionary containing the attributes and their corresponding values. The HTML code snippet to be parsed is as follows: ```html <div class="kt-subheader__tool...
```python from bs4 import BeautifulSoup def parse_anchor_tag_attributes(html_code: str) -> dict: # Parse the HTML code using BeautifulSoup soup = BeautifulSoup(html_code, 'html.parser') # Find the anchor tag and extract its attributes anchor_tag = soup.find('a') attributes = dict(anchor_tag.at...
magicoder
python
You are working on a project that involves implementing a neural network generator using PyTorch. The given code snippet shows a class `Generator` that inherits from `BaseGenerator` and contains an `__init__` method. The `__init__` method initializes the generator with a series of layer configurations. Each configurati...
```python import torch import torch.nn as nn class GeneratorModel(nn.Module): def __init__(self, layer_configs): super(GeneratorModel, self).__init__() layers = [] for i in range(len(layer_configs)): if i == 0: in_channels, out_channels, kernel_size, stride, padd...
magicoder
python
You are tasked with implementing a function that will parse a given HTML snippet and count the number of nested `<div>` elements within it. The function should return the total count of nested `<div>` elements. You are given the following HTML snippet as an example: ```html <div> <div> <div> </...
```python def countNestedDivs(html_snippet): stack = [] count = 0 i = 0 while i < len(html_snippet): if html_snippet[i:i+4] == "<div": stack.append("<div") i += 4 elif html_snippet[i:i+6] == "</div>": if stack and stack[-1] == "<div": s...
magicoder
python
You are tasked with implementing a Python function that processes a list of strings and returns a dictionary containing the frequency of each word in the list. The function should ignore case sensitivity and consider only alphanumeric characters when counting the frequency of words. Additionally, the function should ex...
```python import re from collections import Counter from typing import List, Dict def word_frequency_counter(words: List[str]) -> Dict[str, int]: stop_words = {"the", "and", "of", "in", "to", "a", "is", "that"} # Common English stop words word_count = Counter(word.lower() for word in words if word.lower() not...
magicoder
python
You are tasked with creating a program that simulates a simple game of rock-paper-scissors. The program should allow a user to input their choice (rock, paper, or scissors), generate a random choice for the computer, determine the winner based on the choices, and display the result. Your program should consist of the ...
```python import random def generate_computer_choice(): choices = ['rock', 'paper', 'scissors'] return random.choice(choices) def determine_winner(user_choice, computer_choice): if user_choice == computer_choice: return "It's a tie!" elif (user_choice == 'rock' and computer_choice == 'scissors...
magicoder
python
You are tasked with implementing a function `takeRightWhile` that takes an array and a predicate function as input and returns a new array containing the elements from the end of the original array until the predicate function returns false. The original array should not be modified. If the predicate function is not pr...
```javascript function takeRightWhile(arr, predicate) { if (!predicate) return []; let result = []; let index = arr.length - 1; while (index >= 0 && predicate(arr[index])) { result.unshift(arr[index]); index--; } return result; } ```
magicoder
javascript
You are tasked with implementing a function to parse and save information from a dictionary into a specific string format. The function should take a dictionary as input and return a string containing the key-value pairs in the format "[key1]value1|[key2]value2|...". However, the provided code snippet seems to have som...
```python def save_information_str(note_dict: dict) -> str: strr = "" for key, value in note_dict.items(): strr = strr + "[{0}]{1}|".format(key, value) return strr[:-1] # Remove the extra '|' at the end ``` The provided solution defines the function `save_information_str` that takes a dictionary `...
magicoder
python
You are tasked with creating a Python program to scrape job listings from the StackOverflow Job site and save the results to a CSV file. The code snippet provided initializes the output file and begins the scraping process. Your task is to complete the program by implementing the scraping logic and writing the job deta...
```python import os from datetime import datetime import requests from bs4 import BeautifulSoup import csv def scrape_for_jobs(response): job_details = [] soup = BeautifulSoup(response.text, 'html.parser') job_listings = soup.find_all('div', class_='js-result') for job in job_listings: tit...
magicoder
python
You are tasked with creating a Python function that manages the creation of directories for machine learning model storage. The function should take in the name of the model and create a new directory for that model within the specified directory. If a directory with the same name already exists, the function should ap...
```python import os def create_model_directory(name_dir: str) -> str: base_dir = settings.MODELS_DIR # Assuming settings.MODELS_DIR is the base directory for model storage model_dir = name_dir model_path = os.path.join(base_dir, model_dir) if not os.path.exists(model_path): os.mkdir(model_pat...
magicoder
python
You are tasked with creating a TypeScript class that simulates a simple repository for managing "Like" entities. The provided code snippet is a starting point for the repository class. Your task is to extend this class and implement additional functionality to manage the "Like" entities. Your task is to implement the ...
```typescript import { EntityRepository, Repository } from 'typeorm'; import { LikeEntity } from './LikeEntity'; @EntityRepository(LikeEntity) export class LikeRepository extends Repository<LikeEntity> { async createLike(userId: number, postId: number): Promise<LikeEntity> { const newLike = this.create({ userId,...
magicoder
typescript
You are tasked with creating a Python Flask application that interacts with an external API to retrieve and display data. Your application should have a route that accepts a user's input, makes a request to an external API, processes the response, and returns the data to the user in JSON format. Your Flask application...
```python from flask import Flask, jsonify, request import requests app = Flask(__name__) @app.route('/get_data', methods=['GET']) def get_data(): user_input = request.args.get('input') if user_input: api_url = 'https://api.example.com/data' params = {'query': user_input} response = re...
magicoder
python
You are tasked with simulating the behavior of an Enigma machine rotor in a Python program. The Enigma machine was a cipher device used during World War II for encryption and decryption of secret messages. Each rotor in the machine had a specific wiring configuration, a ring setting, a starting position, and turnover p...
```python class Rotor: def __init__(self, wiring, ring_setting, position, turnover_positions): self.wiring = wiring self.ring_setting = ring_setting self.position = position self.turnover_positions = turnover_positions def advance(self): if self.position in self.turnover...
magicoder
python
You are tasked with designing a system that integrates Amazon Web Services (AWS) Simple Queue Service (SQS) with AWS Lambda functions and Lambda destinations. Your goal is to create a system that efficiently processes messages from an SQS queue and routes the results to different destinations based on specific criteria...
To solve this problem, you can use the following AWS CloudFormation template to define the architecture and integrate SQS, Lambda, and Lambda destinations: ```yaml Resources: MyQueue: Type: AWS::SQS::Queue Properties: QueueName: myQueue MyLambdaFunction: Type: AWS::Lambda::Function Propertie...
magicoder
yaml
You are tasked with implementing a virtual machine (VM) that can execute a set of instructions. The VM is responsible for interpreting and executing the instructions provided to it. The instructions are represented as a sequence of opcodes and operands. Each opcode represents a specific operation, and the operands prov...
```cpp #include "vm.hpp" #include <pomagma/atlas/vm_impl.hpp> void executeInstruction(Opcode opcode, Operand* operands) { switch (opcode) { case LOAD: { // Load value from memory into a register int memoryAddress = operands[0]; int registerIndex = operands[1]; ...
magicoder
cpp
You are working on a system that handles frequency inversion for a signal processing application. The code snippet provided is a part of a method in a class that manipulates an array representing the frequency inversion. The method `setUIntElement` is used to set a specific element in the array to a given value. The pa...
```python class FrequencyInversionHandler: def __init__(self): self.invFrequency = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # Initialize the frequency inversion array def offsetBits_val(self, n): return 2 ** n # Calculate the offset value as 2^n def setUIntElement(self, offset, index, value): ...
magicoder
python
You are tasked with creating a Python function that processes messages from an Amazon Simple Queue Service (SQS) and updates a DynamoDB table with the message data. The function should extract the message body from the SQS event, parse it as JSON, and then update the DynamoDB table with the extracted data. Write a Pyt...
```python import json def process_sqs_event(event, dynamodb): DYNAMODB_TABLE = "your_dynamodb_table_name" # Replace with the actual DynamoDB table name records_table = dynamodb.Table(DYNAMODB_TABLE) for sqs_record in event["Records"]: message_body = json.loads(sqs_record["body"]) message...
magicoder
python