id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
52
7.08k
01a36cab626129b819d3
```python # Function to rotate the matrix using extra space def rotate_matrix(matrix): n = len(matrix) new_matrix = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): for j in range(n): new_matrix[j][n - 1 - i] = matrix[i][j] return new_matrix # In-place solution def rotat...
01a3e2a6323f8222cef2
```rust // Define the trait TrialDivisionTreeLeaf with associated type Output trait TrialDivisionTreeLeaf<D, B> { type Output; } // Define the Reduce trait trait Reduce<D> { // Define the associated type ReduceOut type ReduceOut; } // Define the IsNonZero trait trait IsNonZero {} // Define the associated...
01a60735854f81017a26
```python import requests class Scraper: def __init__(self, start, end, max_iter, scraper_instance): self.start = start self.end = end self.max_iter = max_iter self.scraper_instance = scraper_instance def scrape_letterboxd(self): movie_data = [] for movie_id in ...
01a6e64598cc1396f88f
```python from typing import List def manipulate_list(nums: List[int]) -> List[int]: # Remove all even numbers from the list nums = [x for x in nums if x % 2 != 0] # Double the value of each remaining number nums = [x * 2 for x in nums] # Sort the list in ascending order nums.sort() ...
01a7ece09c676fce8ca8
```python def process_config_args(args, rc_config): sequence_parameters = {'param1': 'description1', 'param2': 'description2'} # Replace with actual sequence parameters for arg, prepend in zip((args.prepend, args.append), (True, False)): for key, item in arg: if key == 'channels' and key n...
01a809da2ab2b307a74e
```python class Session: def __init__(self, name, id): self.name = name self.id = id # Example usage session1 = Session("user1", 1) session2 = Session("user2", 2) manager = SessionManager() manager.AddSession(session1) manager.AddSession(session2) # Retrieving sessions retrieved_session1 = manage...
01a8a844540fd978f59d
To solve this problem, you would need to create an ASP.NET Core web application and integrate the EligereVS library to manage and display the voting data. Here's a high-level overview of the steps involved in the solution: 1. Set up an ASP.NET Core web application project. 2. Install the EligereVS library as a depende...
01a9c58cbe5f8d6221a9
```java import net.i2p.crypto.eddsa.EdDSAPrivateKey; import net.i2p.crypto.eddsa.EdDSAPublicKey; import net.i2p.crypto.eddsa.KeyPairGenerator; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.security.KeyFactory; import java.security.Signature; public class EdDS...
01abfc13554416da0437
```swift func validateProfile(email: String?, bio: String?) -> Bool { if let email = email, email.contains("@"), let bio = bio, bio.count <= 100 { return true } return false } ```
01acd028cc45cdf1214a
```php public function insertAndJoinTables($data, $sourceTable) { // Insert data into "simkopsis_simpanan" table $insertResult = parent::insert_with_status('simkopsis_simpanan', $data); // Establish a join operation with "simkopsis_anggota" table $destinationTable = array( 'table' => array('sim...
01ad40bdf22bf8533b3c
```php public function updateFriendship(Request $request, $id) { $friendship = Friendship::find($id); if ($request->friendship_status == '00') { $friendship->forceDelete(); $response = ["status" => '00']; return response()->json($response); } else { $friendship->update(["stat...
01ade2f6f850ceca4937
```python import soundfile as sf def embed_stego(cover_path: str, stego_path: str, inplace: bool) -> None: # Read cover and stego audio files cover, fs_cover = sf.read(cover_path) stego, fs_stego = sf.read(stego_path) # Ensure both audio files have the same sample rate if fs_cover != fs_stego: ...
01ae093a5ad54ec73689
```java public class Solution { public int maxUncrossedLines(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; int[][] dp = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (num...
01ae902214c4829759a0
```python def adjust_learning_rate(optimizer, warmup_epoch, epoch, args, nums_batches): if args.lr_mode == 'step': if epoch in args.lr_step_epochs: new_lr = args.lr * (args.lr_decay_factor ** (epoch // args.lr_step_epochs)) for param_group in optimizer.param_groups: p...
01af87143b39ae00970c
```cpp class GLErrorRenderer : public DefaultRenderer { private: // Add any necessary member variables here public: GLErrorRenderer(/* Add any necessary parameters for the constructor */) { // Implement constructor as needed } void initialize(const G3MContext* context) override { // Im...
01b0ad7148ba7360c8ab
```rust struct Stack<T> { data: Vec<T>, } impl<T> Stack<T> { // Create a new empty stack fn new() -> Self { Stack { data: Vec::new() } } // Add an item to the top of the stack fn push(&mut self, item: T) { self.data.push(item); } // Remove and return the item at the to...
01b113ba02b676ef420a
```swift import Foundation import GoogleAnalytics // Assuming Google Analytics SDK is imported class Analytics { static let shared = Analytics() private init() { // Initialize Google Analytics SDK GAI.sharedInstance().tracker(withTrackingId: "YOUR_TRACKING_ID") } // Track screen view...
01b1ef1ecabec6f49a2d
```python import numpy as np from scipy.stats import poisson def calculate_log_likelihood(data): # Initialize the Poisson distribution with parameter 5 poisson_dist = poisson(mu=5) # Calculate the log-likelihood for the given data log_likelihood = np.sum(poisson_dist.logpmf(data)) return ...
01b4a9e58efe836ce540
```javascript function calculateContentMargin(properties) { const { gutter = 0 } = properties; let { border } = properties; if (!border) return `margin-left:-${gutter}rpx; margin-top:-${gutter}rpx`; if (typeof border !== 'object') return `margin-left:-${gutter}rpx; margin-top:-${gutter}rpx`; // Calculate con...
01b7186f628cb83f4a4e
```python import datetime def format_time(seconds): # Round to the nearest second. elapsed_rounded = int(round(seconds)) # Format as hh:mm:ss return str(datetime.timedelta(seconds=elapsed_rounded)) # Test cases print(format_time(3661)) # Output: "01:01:01" print(format_time(7200)) # Output: "02:00:...
01b7b5931fe153c55d91
```java import com.android.volley.Response; import com.android.volley.VolleyError; public class CustomErrorListener implements Response.ErrorListener { @Override public void onErrorResponse(VolleyError error) { handleError(error); } public void handleError(VolleyError error) { if (err...
01b816284bdb56d77b63
```python def determine_execution_order(functions): graph = {f: set(deps) for f, deps in functions} execution_order = [] def dfs(node, visited, stack): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: dfs(neighbor, visited, stack) ...
01b9a032af49b1e55be6
```java @Override protected String createAddSQL(String tableName, int userID, String name, String email, String subject, String feedbackText) { String sql = "INSERT INTO " + tableName + " (UserID, FeedbackTimestamp, Name, Email, Subject, FeedbackText) VALUES (" + userID + ", CURRENT_TIMESTAMP, " + ...
01b9bf774445210393aa
```python from typing import Union class Bank: def __init__(self): self.accounts = {} def create_account(self, name: str, initial_deposit: float) -> int: account_number = len(self.accounts) + 1 self.accounts[account_number] = {'name': name, 'balance': initial_deposit} return ac...
01bc53e5b8f64683a296
```python from typing import List def word_lengths(words: List[str]) -> List[int]: return [len(word) for word in words] ``` The `word_lengths` function takes a list of words as input and uses a list comprehension to iterate through each word, calculating its length using the `len` function. The resulting list of w...
01bca90d0f5b77f33aa5
```python import re def count_word_occurrences(comment_block): words = re.findall(r'\b\w+\b', comment_block.lower()) word_count = {} for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 return word_count ``` The `count_word_...
01bd4278ee9240688304
```swift func localizeDate(date: Date, option: DateOption) -> String { let dateFormater = DateFormatter() dateFormater.dateFormat = "yyyy-MM-dd" let weekdayFormater = DateFormatter() weekdayFormater.dateFormat = "EEEE" switch option { case .today: return l("date_today", dateFor...
01be1abef4d3328c8635
```csharp public interface IOriginFilterable { int? Id { get; set; } string? Name { get; set; } } public class OriginObject : IOriginFilterable { public int? Id { get; set; } public string? Name { get; set; } } public class FilterableCollection<T> where T : IOriginFilterable { private List<T> coll...
01be3d079cedebb13ee0
```python from selenium import webdriver from selenium.common.exceptions import NoSuchElementException def click_element_by_link_text(driver, link_text): try: element = driver.find_element_by_link_text(link_text) element.click() except NoSuchElementException: print(f"Element with link t...
01be4b10b7e2f464132f
```typescript function addPrefixAndRemoveDuplicates(classes: string[], prefix: string): string { const prefixedClasses = classes.map(className => `${prefix}${className}`); const uniquePrefixedClasses = [...new Set(prefixedClasses)]; // Using Set to remove duplicates return uniquePrefixedClasses.join(' '); } ```
01c086677a713cd80156
```php function processTemplate($template): string { $processedContent = $template; $processedContent = str_replace('@section(\'content\')', '<div id="content">', $processedContent); $processedContent = str_replace('@endsection', '</div>', $processedContent); $processedContent = str_replace('@include(\'...
01c167f0443b2ba4a291
```python import requests def fetch_repo_info(repo_name, package_name): # Fetching GitHub repository info github_url = f"https://api.github.com/repos/{repo_name}" github_response = requests.get(github_url) github_data = github_response.json() stars_count = github_data['stargazers_count'] # Fet...
01c4729577043c1f7f5c
```python import base64 import requests from datetime import datetime, timedelta def retrieve_deanslist_data(base_url: str, end_points: dict) -> dict: # Encode the base URL using base64 encoding encoded_base_url = base64.b64encode(base_url.encode('utf-8')).decode('utf-8') # Calculate the date for 30 days ...
01c5b4c275819aa8bd49
```python from typing import List def count_button_presses(button_states: List[bool]) -> int: count = 0 for state in button_states: if state: count += 1 return count ``` The `count_button_presses` function iterates through the list of button states and increments the count whenever the...
01c9a1865d6050a7baf6
```python from django.http import HttpResponseForbidden from django.shortcuts import get_object_or_404 from .models import tcdMessage, User def process_message(request, value, object_id): user = get_object_or_404(User, username=value) if user != request.user: return "Unauthorized" message_list = t...
01ca6fdb1b6a143e577b
```javascript // Middleware function to check if user is authenticated function isAuthenticated(req, res, next) { // Check if user is authenticated based on session or token if (req.isAuthenticated()) { // Assuming req.isAuthenticated() is a function that checks user authentication // User is authenticated, all...
01caaf2dbe6c64023287
```python from typing import List def maxTotal(triangle: List[List[int]]) -> int: n = len(triangle) # Start from the second bottom row and work upwards for i in range(n - 2, -1, -1): for j in range(i + 1): # For each position, choose the maximum adjacent number from the row below a...
01cab9ae311d69817c74
```cpp int Client::handle_output(ACE_HANDLE) { ACE_Message_Block *mb; ACE_Time_Value nowait(ACE_OS::gettimeofday()); while (-1 != this->getq(mb, &nowait)) { ssize_t send_cnt = this->peer().send(mb->rd_ptr(), mb->length()); if (send_cnt == -1) { ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) %p\n"), ...
01cb2fee335d89b3d652
```bash #!/bin/bash # Input URL read -p "Enter the URL: " URL # Extract protocol from URL PROTOCOL=$(echo "$URL" | grep -o "^\w\+://") # Convert protocol to lowercase PROTOCOL=$(echo "$PROTOCOL" | tr '[:upper:]' '[:lower:]') # Check if the protocol is valid if [[ "$PROTOCOL" == "http://" ]] || [[ "$PROTOCOL" == "ht...
01cc493d1b8eb618e783
```python def update_build_info(response: dict, done: bool) -> dict: if done: response['json']['last_build_info']['success'] = True response['json']['last_build_info']['stop_time'] = 1.0 return response ``` The `update_build_info` function takes in the `response` dictionary and the `done` flag ...
01ce72ecbb5f70958a1f
```cpp #include <iostream> #include <fstream> #include <map> #include <string> #include <cctype> #include <algorithm> int main() { std::ifstream file("input.txt"); std::map<std::string, int> wordCount; if (file.is_open()) { std::string word; while (file >> word) { // Remove pun...
01cfa3f51649031e296d
```javascript const sqlite3 = require('sqlite3'); class CliDatabase { constructor(sqliteModule, dbPath, errorCallback) { this.db = new sqliteModule.Database(dbPath, (err) => { if (err) { errorCallback(err); } }); } insert(tableName, data) { r...
01d0bb8493c2c9a6d742
```python import unittest from unittest.mock import patch, Mock from windlass import charts, generic class TestWindlassUpload(unittest.TestCase): @patch('windlass.charts.Chart.export_stream', new=Mock()) @patch('windlass.generic.Generic.upload', new=Mock()) def test_upload_function_with_patches(self, mock_...
01d14e3b6d001af74f32
```python from os import walk def analyze_site_files(post_folder): site_categories = [] for root, directories, files in walk(post_folder): for f in files: site_categories.append(f.split(".")[1]) site_categories = set(site_categories) return site_categories # Example usage print(ana...
01d1995b68fe0ac460ed
```python import os import subprocess # Set the environment variables os.environ["ASTRA_DEVICE_ID_UP"] = "..." os.environ["ASTRA_DEVICE_ID_DOWN"] = "..." # Launch the minimal.launch file subprocess.call(["roslaunch", "turtlebot_bringup", "minimal.launch"]) # Launch the gmapping_demo.launch file subprocess.call(["ros...
01d2257ee8140755b774
```java import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class MailRegistryTest { @Test public void shouldReturnStorageFromMainRegistry() { // Create a mock mail registry MailRegistry mail...
01d3285beddbf3bfd8dc
```python def count_unique_labels(model_settings: dict) -> int: label_count = model_settings['label_count'] # Extract the value associated with the 'label_count' key unique_labels = set(label_count) # Convert the list of labels to a set to get unique labels return len(unique_labels) # Return the count of...
01d3da42107d72faaf97
```java public String extractSubstring(String desc, int s) { String processedSubstring = desc.substring(0, s).trim(); return processedSubstring; } ``` The `extractSubstring` function takes the input string `desc` and the integer `s`. It then uses the `substring` method to extract the first `s` characters from ...
01d46fe38eda9e45c9d7
```python import PySimpleGUI as sg def preview(killingfield_eqn, viewer, filename, euler, dvioptions): # Function to preview the killingfield_eqn using specified parameters pass # Placeholder for actual implementation def resize_killing_image4d(image_type): # Function to resize the killing field image ba...
01da41e2ba27aaec92b2
```python def main(app, network_type, augment_data, is_training, is_predicting): """ Entry point for a machine learning application. Args: app (str): The name of the application. network_type (str): The type of neural network to be used. augment_data (bool): Indicates whether data augmentation ...
01dad42cfc8f52d810a3
```bash #!/bin/bash colors_file="colors.txt" case "$1" in --add) if [ -z "$2" ] || [ -z "$3" ]; then echo "Usage: color-config.sh --add <color_name> <color_code>" exit 1 fi echo "$2=$3" >> "$colors_file" echo "Color configuration added: $2=$3" ;; ...
01db0a3b82ce1888970a
```python def average_dimensions(infrastructure_elements): dimensions_sum = {} count = {} for element in infrastructure_elements: infrastructure_type, _, length, width, height = element if infrastructure_type not in dimensions_sum: dimensions_sum[infrastructure_type] = [leng...
01db1c65f374432b7a90
```python class Image(SXBase): SXClass = SXImage def load_image(self, file_path): # Implementation to load image from file_path # Example: self.data = self.SXClass.load(file_path) pass def resize_image(self, width, height): # Implementation to resize the loaded image to the...
01dbce864e09eb64fe44
```python from django.contrib.auth.models import User from faker import Faker class UserAuthenticator: def __init__(self): self.client = Client() self.fake = Faker() self.new_user = None def create_user(self, username: str) -> None: self.new_user = User.objects.create(username=...
01dc8a356cfa95c6a081
```python import re import requests from .baseclient import BaseClient class FishCClient(BaseClient): def __init__(self, reload_history=True, **kwargs): super(FishCClient, self).__init__(website_name='fishc', reload_history=reload_history, **kwargs) def checksessionstatus(self, session, infos_return):...
01dc943e01e4d7150c7f
```java public enum Chemical { Oxygen("Oxygen"), Carbon_Dioxide("CarbonDioxide"), Sulphur_Dioxide("SulphurDioxide"), Ammonia("Ammonia"), Methane("Methane"), Nitrogen("Nitrogen"), Hydrogen("Hydrogen"), Helium("Helium"), Neon("Neon"), Argon("Argon"), Silicates("Silicates"), ...
01dcf6442b0d0846404b
```bash #!/bin/bash # Check if the local domain is provided as an argument if [ -z "$1" ]; then echo "Usage: $0 <local_domain>" exit 1 fi local_domain=$1 openssl_cnf="/path/to/openssl.cnf" # Replace with the actual path to your openssl.cnf file # Generate the SSL certificate with SAN extension openssl req -x509...
01dcfa288cbb1f345a0b
```python def handle_error(exception): if isinstance(exception, XMLError): self.log.error(u'Erro ao ler o XML da requisição.') return self.response_error(3, exception) elif isinstance(exception, EquipamentoNotFoundError): return self.response_error(117, id_equipamento) elif isinstanc...
01dd043cd81a38998ab1
```python from typing import List, Tuple, Dict, Union, Any def process_field_configurations(field_configurations: List[Tuple[str, Dict[str, Union[str, Any]]]]) -> Dict[str, List[str]]: result = {} for group, fields_dict in field_configurations: result[group] = list(fields_dict.values())[0] return r...
01dd2d0be4df75a1ed26
```cpp class fusion_priority_t { public: char *name; int num_pred; int meta_size; fusion_priority_t(char * const arg_name, const int arg_num_pred, const int arg_meta_size) { name = arg_name; num_pred = arg_num_pred; meta_size = arg_meta_size; } }; ``` In the solution, the `...
01df3c65ac2d45dcb574
```javascript // MixinComponent.js class MixinComponent { constructor() { this.mixins = {}; } registerMixin(name, mixin) { if (this.mixins[name]) { throw new Error(`Mixin with name ${name} is already registered`); } this.mixins[name] = mixin; } applyMixins(targetClass) { for (const...
01e4de257f5f621510f9
```python from datetime import datetime from enum import Enum class MemoActivity(Enum): Obsolete = 1 # Add other memo activities here class User: # Assume necessary attributes and methods for user representation class Memo: def __init__(self): self.obsolete_date = None def obsolete(self,...
01e55eca41dcc279a760
```swift // MARK: setter @objc var item: NSString! { didSet { if let priceLabel = self.priceLabel { priceLabel.removeFromSuperview() } let priceLabel = UILabel() priceLabel.text = "Price: \(item)" priceLabel.textAlignment = .center priceLabel.tran...
01e9599ec655ef2fa6e0
```c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> char* playRockPaperScissors(char* userChoice) { const char* choices[] = {"rock", "paper", "scissors"}; int computerChoice = rand() % 3; // Generate a random choice for the computer if (strcmp(userChoice, choices[computerCho...
01e9a009c1d04bc4f065
```python def generateRadioButtonCSS(size, colorPalette, checked): css_code = f"width: {size}px;\nheight: {size}px;\nborder: 3px solid palette({colorPalette});\nborder-radius: 7px;\n}}\n\nQRadioButton::indicator:checked {{\n /* Indicator style for checked state */\n}}" return css_code ``` The `generateRadioBu...
01eea2e29e3cf179cd80
```java public class TextProcessor { private String text; public void setText(String text) { this.text = text; } public void setCurCharPropertyValue(int position, String value) { if (text != null && position >= 0 && position < text.length()) { if (value.isEmpty()) { ...
01ef438a2902aab06e4d
```python from collections import Counter from typing import List def find_string_anagrams(input_str: str, pattern: str) -> List[int]: result = [] if not pattern or not input_str or len(pattern) > len(input_str): return result # Return empty list for edge cases window_start, matched = 0, 0 ch...
01f19412004e9db57098
```python import os import ctypes import keras from keras.preprocessing.text import one_hot from numpy import array import numpy as np def load_and_predict_text_model(text_data): # Perform one-hot encoding on the input text data vocab_size = 10000 # Example vocabulary size encoded_text = [one_hot(text, vo...
01f2e6fc267e5785dea9
```java import com.vaadin.v7.ui.TextField; public class LimitedTextField extends TextField { private int maxLength; public LimitedTextField(String caption, int maxLength) { super(caption); this.maxLength = maxLength; addTextChangeListener(event -> { String text = event.getT...
01f5c18c21ec7477bc10
```python import multitail2 class MultiTail: def __init__(self, spoolglob, progresses=None, shutdown=None): self.progresses = progresses or {} self.shutdown_e = shutdown self.data_reader = multitail2.MultiTail(spoolglob, skip_to_end=False, ...
01f771c73932d886fec4
```php function validateFormInput($input, $rules) { $errors = []; foreach ($rules as $field => $rule) { $rulesArray = explode('|', $rule); foreach ($rulesArray as $singleRule) { if ($singleRule === 'required' && empty($input[$field])) { $errors[$field][] = "The $fiel...
01f820f5844752e63586
```csharp using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using System.Threading.Tasks; [ApiController] [Route("api/cart")] [Authorize(Roles = Role.Customer)] public class CartController : ControllerBase { private readonly ICustomerService _customerService; public CartController(ICus...
01f899db70d8163f962d
```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_LENGTH 100 #define MAX_WORDS 1000 typedef struct { char word[MAX_WORD_LENGTH]; int count; } WordCount; int compare(const void *a, const void *b) { return ((WordCount *)b)->count - ((WordCount *)a)->count; } int main() { ...
01f97938e16aa5753c95
The issue in the code is that it is attempting to set the element array buffer using the Index Buffer Object (IBO) instead of accessing the Vertex Array Object (VAO) as intended. To fix this, the code should be modified to access the VAO and set the element array buffer accordingly. Corrected code snippet: ```cpp ...
01f9ae4182ba4b1e46be
```cpp #include <iostream> class LinearSegmentParameter { private: unsigned short _segmentLength; unsigned short _segmentWidth; public: // Constructor to initialize segment length and width LinearSegmentParameter(unsigned short length, unsigned short width) { _segmentLength = length; _...
01fabe28c05abc4919e5
```python import os def generate_detection_annotation(imgf, box, label_t, opts, out_path, threshold): if opts.visualize: visualize(imgf, box, label_t, out_file=out_path) box = box[box[:, -1] >= 1e-2] detection_annotation = { 'image_filename': os.path.basename(imgf), 'detection_thre...
01fb27d867161fe6245f
```python class MyPluginHandler: def __init__(self): self._meta = {'interface': 'plugin', 'label': 'my_plugin_handler'} @property def _meta(self): return self._meta @_meta.setter def _meta(self, value): if 'interface' in value and 'label' in value: self._meta = ...
01fce9ab2508db8c217a
To optimize the given query for retrieving transportation service information based on geographical proximity, we can utilize the PostgreSQL extension `cube` and `earthdistance` to efficiently calculate distances and improve query performance. The optimized query can be rewritten as follows: ```sql SELECT sfs.id, sfs...
01fdbcc0c3b6b5134e1c
```python import numpy as np def generate_grid_coordinates(nz, nx): zz, xx = np.mgrid[:nz, :nx] return zz, xx ``` The `generate_grid_coordinates` function uses NumPy's `mgrid` to create a mesh grid of coordinates for the given `nz` and `nx` values. It returns the z and x coordinates as separate NumPy arrays, ...
01fdee7359826a8133d7
```python from setuptools import setup setup( name='iqualitpy', version='1.0.0', description='Python iQuality API library', license='MIT', packages=['iqualitpy'], author='<Your Name>', author_email='<Your Email>', keywords=['iquality', 'api', 'library', 'timetracking'], url='https:/...
01fdef35367c3cd7c61b
```python def fit_peaks(fit_npeaks, peaks): fit_peaks = 'fit_peaks' if fit_npeaks < 3: return peaks, -1, fit_peaks else: return peaks, 0, fit_peaks ``` The `fit_peaks` function takes the input parameters `fit_npeaks` and `peaks` and returns a tuple based on the conditions specified in the pr...
01fecdb3e3c85c51bbf8
```python # Define the User class class User: def __init__(self, username, email): self.username = username self.email = email # Define the Registry class class Registry: def __init__(self): self.users = [] def add_user(self, user): self.users.append(user) def get_user...
0201df38e4368e006e3d
```java public class TextFormatter { private static boolean active = false; private static final String ANSI_RESET = "\u001B[0m"; public static void toggleFormatting() { active = !active; } public static String bold(String string) { if (active) { return "\u001B[1m" + st...
02030d6c6f70d0b90d6f
```python class ErrorMessageHandler: def __init__(self, exc_type, error): self._exc_type = exc_type self.error = error def _get_name(self, exc_type): return exc_type.__name__ def _format_message(self, name, error): return f"{name}: {error}" def get_formatted_error_mess...
02048ee04deaf180a3c1
```swift func mergeOverlappingIntervals(_ intervals: [AudioTimeInterval]) -> [AudioTimeInterval] { guard !intervals.isEmpty else { return [] } var sortedIntervals = intervals.sorted { $0.start < $1.start } var mergedIntervals = [AudioTimeInterval]() var currentInterval = sortedIntervals[0] ...
0204d8fe27a0a24d31a5
```c void updateRegion(Region* region, int left, int bottom, int width, int height) { bool update = false; if (left != region->left || bottom != region->bottom || width != region->width || height != region->height) { update = true; } region->left = left; region->bottom = bottom; region...
0206b0840e0d4f47ea83
```python import importlib def get_core_plugins(module_name): try: module = importlib.import_module(module_name) core_plugins = [name for name, obj in module.__dict__.items() if isinstance(obj, type)] return core_plugins except (ModuleNotFoundError, AttributeError): return [] #...
02082c5254a9a096cf11
```javascript function validateForm(amount, remarks) { const errors = []; if (isNaN(amount) || amount <= 0) { errors.push("Top Up Amount must be greater than 0"); } if (remarks.trim() === "") { errors.push("Remark cannot be empty"); } return { isValid: errors.length === 0, errors: errors ...
020914c7781b0f6fa7f4
```swift class CustomAnnotationView: MKPinAnnotationView { var title: String = "" // Property to store the title for the annotation view override init(annotation: MKAnnotation?, reuseIdentifier: String?) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) displayPriority = .r...
020974731c9c8cf508ea
```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class GitHubInfoParser { public static GitHubInfo parseGitHubInfo(String codeSnippet) { Pattern pattern = Pattern.compile("<reponame>(\\w+)/(\\w+)<gh_stars>(\\d+)"); Matcher matcher = pattern.matcher(codeSnippet); ...
020a7eceebc35e6c8059
```python import json def convert_to_pretty_json(dct, indent): """ Converts the given dictionary to a JSON string with the specified indentation level. Args: dct: dict - The dictionary to be converted to JSON. indent: int - The number of spaces to use for indentation. Returns: str: The JS...
020b6474acc889b208eb
```python import asyncio class AsyncServer: def __init__(self): self.writer = None async def send_messages(self): i = 0 while True: i += 1 message = f'hello {i}\n'.encode('utf-8') if self.writer: self.writer.write(message) ...
020cea4b44fd7552dc3f
```java private static void addAdditionalServicePointProperties(JsonObject request, ServicePoint servicePoint) { if (servicePoint == null) { String msg = "Unable to add servicepoint properties to request {}, servicepoint is null"; log.info(msg, request.getString("id")); return; } Jso...
020f603b74090fe3458b
```bash deployDistribution() { local RELEASE=$1 local UBUNTU=("xenial" "bionic" "focal") # Array of Ubuntu release versions local DEBIAN_PATH="/path/to/debian" # Replace with the actual path if [[ " ${UBUNTU[*]} " =~ " $RELEASE " ]]; then DISTRO="ubuntu" else DISTRO="debian" f...
020fef7737ebb9aae9a5
```cpp QString formatSizeList(const QList<QSize> &sList) { QString rep; foreach(const QSize &s, sList) { rep += QString::number(s.width()) + "x" + QString::number(s.height()) + ";"; } return rep; } ``` In the solution, the function iterates through the input list of QSize objects using a foreac...
0210f1a124725d19d152
```python import re def parse_dependencies(config_file): dependencies = {} pattern = re.compile(r'(\w+)\(\s*name\s*=\s*"(.*?)",\s*urls\s*=\s*(\[.*?\]),?\s*sha256\s*=\s*"(.*?)",?\s*importpath\s*=\s*"(.*?)",?\s*sum\s*=\s*"(.*?)"?\s*\)') matches = pattern.findall(config_file) for match in matches: ...
0211cce54a03e82543de
```python def convertToHEXForChar(inputString): convertedCharList = [hex(ord(char)) for char in inputString] return convertedCharList def displayChar(line, *args): concatedList = [] for argItem in args: concatedList.extend(argItem) print(len(concatedList)) for message in concatedList: ...
0213012fbcd678db4b71
```typescript import * as fs from 'fs'; import * as path from 'path'; function extractExchangeClients(modulePath: string): string[] { const moduleExports = require(modulePath); const clientNames = Object.keys(moduleExports) .filter(key => key.endsWith('Client') && key !== 'OkexClient') // Exclude OkexClient as...
021377c6f8232bb8d4fb
```c #include <stddef.h> #include <sys/atomics.h> #include <bionic_futex.h> #include <bionic_atomic_inline.h> typedef struct { int volatile flag; } spinlock; void spinlock_init(spinlock* lock) { lock->flag = 0; } void spinlock_lock(spinlock* lock) { while (__atomic_cmpxchg(0, 1, &lock->flag) != 0) { ...
0213a4d697e959781f52
```typescript class DescriptorsService { static API_URI = 'https://example.com'; // Replace with the actual API URI trsUrl(organization: string, toolName: string, version: string): string { const encodedOrganization = encodeURIComponent(organization); const encodedToolName = encodeURIComponent(toolName); ...