id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 52 7.08k |
|---|---|---|
01322ac1a7291e7b5ca5 | ```csharp
public class EventSuppressionManager
{
private bool isEventSuppressed;
public bool IsEventSuppressed
{
get { return isEventSuppressed; }
}
public void EnableEventSuppression()
{
isEventSuppressed = true;
}
public void DisableEventSuppression()
{
i... | |
0132c95202892aadb8d8 | ```java
public class DeviceUsageManager {
private int emulatorUsage;
private int simulatorUsage;
private static final int EMU_USAGE_LIMIT = 100;
private static final int SIM_USAGE_LIMIT = 50;
public DeviceUsageManager() {
this.emulatorUsage = 0;
this.simulatorUsage = 0;
}
p... | |
013432e9f0cffad417c6 | ```python
import numpy as np
def LinkProbability(A, D):
"""
Calculate the link probability based on the given inputs.
Args:
A: numpy array, matrix representing the links between points (expected to be in upper triangular form)
D: numpy array, matrix of distances between points
Returns:
p:... | |
01355df089b6edadda77 | ```python
class Book:
def __init__(self, title, author, genre, quantity):
self.title = title
self.author = author
self.genre = genre
self.quantity = quantity
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
for existing_book in se... | |
0136ee8a880177114a78 | ```java
public class APIResource {
private String baseUrl;
public APIResource(String baseUrl) {
this.baseUrl = baseUrl;
}
public APIResource push(String endpoint) {
// Implementation not shown
return this; // Placeholder return
}
public APIResource passwordRecovery() {
return new APIResou... | |
01377cdce4909915df81 | ```python
from typing import List, Tuple
def convert_coordinates(camera_data: List[Tuple[float, float, float]]) -> List[Tuple[float, float, float]]:
converted_coords = []
for coord in camera_data:
x, y, z = coord
converted_coords.append((x, -y, -z)) # Negate y and z to convert to standard form... | |
0137b53dacf8a2bec3eb | ```php
<?php
// Define the base repository interface
interface BaseRepository
{
// Define common repository methods
}
// Define the PostRepository interface that extends the BaseRepository
interface PostRepository extends BaseRepository
{
public function getListEmployer();
public function getListMember()... | |
01399d875d509a00781c | ```python
def get_host_info(connection):
host_name = connection["host"]
return {"name": host_name, "id": None}
```
The `get_host_info` function extracts the host name from the provided connection object and returns a dictionary with the host name and a `None` value for the ID. This solution correctly interacts... | |
013a53dbae90ee83acae | ```csharp
class Anbieter
{
private string providerName;
private int totalServicesProvided;
public Anbieter(string name)
{
providerName = name;
totalServicesProvided = 0;
}
public string ProvideService(string clientName)
{
totalServicesProvided++;
return $"Se... | |
013b7d4a6329bb0f1575 | ```rust
use std::num::ParseIntError;
fn hex_to_rgb(hex: &str) -> Result<(u8, u8, u8), ParseIntError> {
if hex.len() != 6 {
return Err(ParseIntError { kind: std::num::IntErrorKind::InvalidDigit });
}
let r = u8::from_str_radix(&hex[0..2], 16)?;
let g = u8::from_str_radix(&hex[2..4], 16)?;
l... | |
013cf3fa4bda04fb6148 | ```python
import os
import pandas as pd
from custom_modules import msgbox, fdd
def configsectionmap(filename, section):
# Function to read configuration file sections
# Implementation not provided
def find_files(directory, pattern):
# Function to find files matching the pattern in the directory
# Impl... | |
013d4ef0a3393655b1df | ```bash
#!/bin/sh
# Change directory to the project build directory
cd /Users/lbajo/ros2_mod_ws/build/rosidl_generator_objc
# Execute the make command to build all components
make -f /Users/lbajo/ros2_mod_ws/build/rosidl_generator_objc/CMakeScripts/install_postBuildPhase.make$CONFIGURATION all
```
The provided shell... | |
013ecdbcbcdf1ed9528b | ```cpp
bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
// Assuming SSL information is available from the socket implementation
// Populate the SSLInfo object with relevant SSL information
// For example:
ssl_info->protocol_version = "TLSv1.2";
ssl_info->cipher_suite = "AES256-SHA";
ssl_info->certi... | |
013fdd7669a34bf463bd | ```nextflow
process createSymbolicLink {
// Define input parameter
input:
file get_genome
// Define output parameter
output:
file "{sample}.dna.fa" into RAW
// Define shell command to create symbolic link
script:
"""
ln --symbolic $(readlink --canonicalize ${get_genome}) ${RAW... | |
0140a420f27598bdfc6f | ```python
def get_model_attribute(attribute_name: str):
try:
from . import models # Import the models module
model_module = models # Assign the imported module to a variable
if hasattr(model_module, attribute_name): # Check if the attribute exists
return getattr(model_module, ... | |
0141fc12115d64a42750 | The given code snippet represents a shellcode that performs the following actions:
1. Set the eax register to 0: "\x31\xc0"
2. Push the value of eax onto the stack: "\x50"
3. Push the string "//sh" onto the stack: "\x68""//sh"
4. Push the string "/bin" onto the stack: "\x68""/bin"
5. Move the value of ebx to the value... | |
01423cec99d45a9d47a4 | ```cpp
#include <gen/gen.h>
void SortServerHandler::sort(
vector<int32_t>& _return,
const vector<int32_t>& values) {
// Perform sorting using the gen library's sorting capabilities
_return = gen::from(values) | gen::order | gen::as<vector>();
}
```
The `SortServerHandler::sort` function utilizes the `gen` ... | |
01431e876c4e60a9cf43 | ```typescript
class UserAuthenticator {
private authService: AuthenticationService;
constructor(authService: AuthenticationService) {
this.authService = authService;
}
async login(signInModel: SignInModel): Promise<string> {
try {
const isAuthenticated = await this.authService.authenticate(signI... | |
01449642b8507569dac7 | ```javascript
// Define the SignalR hub connection
var chat = $.connection.chatHub;
// Start the connection
$.connection.hub.start().done(function () {
// Event handler for the send button click
$('#sendButton').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displa... | |
01456a3d8ea503cb6322 | ```python
def update_cookies(c, name, cookies):
if name in c:
c[name] += cookies
else:
c[name] = cookies
return c
```
The `update_cookies` function first checks if the given `name` already exists in the dictionary `c`. If it does, the number of cookies for that person is updated by adding t... | |
01462b988e606a4a0fbe | ```python
class PythonInterpreter:
def __init__(self):
self.output = ""
def execute(self, code: str) -> str:
try:
exec(code)
return self.output
except Exception as e:
return f"Error: {str(e)}"
def clear_output(self) -> None:
self.output =... | |
01476af910c3948bb2a6 | ```python
import re
def parse_dockerfile(dockerfile_content: str) -> str:
from_pattern = r'^FROM\s+(.+)$'
match = re.search(from_pattern, dockerfile_content, re.MULTILINE)
if match:
return match.group(1).strip()
else:
return "Base image not found in the Dockerfile"
```
The `parse_docke... | |
0148dd906659a3abe7fa | ```java
package com.mtcarpenter.mall.portal.repository;
import com.mtcarpenter.mall.portal.domain.MemberBrandAttention;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface MemberBrandAttentio... | |
014901ad001d9aba24b3 | ```python
class CustomUser:
def __init__(self, username):
self.USERNAME_FIELD = "username"
self.username_value = username
@property
def username_dict(self):
return {self.USERNAME_FIELD: self.username_value}
def __str__(self):
return f"User Model: {self.USERNAME_FIELD} -... | |
01494c7e04490fe08762 | ```php
use Illuminate\Support\ServiceProvider;
class ParcelamentoServiceProvider extends ServiceProvider
{
public function boot()
{
$this->app->bind('parcelamento', function () {
return new Parcelamento();
});
}
public function register()
{
//
}
}
class Par... | |
0149fca07c9a497ec43a | ```python
class CustomClass:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"
# Example usage
obj = CustomClass("Alice", 25)
print(obj) # Output: Name: Alice, Age: 25
``` | |
014af76eea04636b91dc | ```python
def process_schema(schema: dict, lg: dict) -> None:
for o in schema['all']['opt'] + schema.get('prov_name', {'opt': []})['opt']:
lg[o] = val(o)
```
The `process_schema` function iterates through the optional fields in the 'all' section and the provider-specific section (if it exists) of the schem... | |
014b042f0896ac326cd9 | ```swift
func isFunction(object: Any?, functionName: String, completion: @escaping (Bool) -> Void) {
// Implement the logic to check if the function exists within the object
// For example, if the object is a class instance, you can use reflection to check for the existence of the function
// Placehold... | |
014cfd3f1bed62547c67 | ```cpp
#include <iostream>
#include <vector>
#include <cmath>
struct Point {
int x;
int y;
};
std::vector<double> calculateDistances(const Point& point, const std::vector<std::pair<int, int>>& projections) {
std::vector<double> distances;
for (const auto& proj : projections) {
double dx = std:... | |
014dd8c0aa19d2c5995d | ```python
import numpy as np
def shuffle_data_labels(image_data, labels):
idx = np.random.permutation(len(image_data)) # Generate a shuffled index
shuffled_image_data = [image_data[i] for i in idx] # Shuffle image data using the index
shuffled_labels = [labels[i] for i in idx] # Shuffle labels using the... | |
014ef7445b2faa7b2f01 | ```csharp
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static List<string> ExtractComments(string code)
{
List<string> comments = new List<string>();
bool inSingleLineComment = false;
bool inMultiLineComment = false;
StringBuilder currentCom... | |
014f50863dafbc008956 | ```python
from typing import List, Set
import re
def get_web_targets(urls: List[str]) -> Set[str]:
web_targets = set()
for url in urls:
matches = re.findall(r'\{([^}]*)\}', url) # Find all strings enclosed within curly braces
for match in matches:
targets = [t.strip() for t in matc... | |
015016c35ffd457a7d63 | ```python
import datetime
class Record:
def __init__(self):
self.updated_ts = datetime.datetime.now()
def update_record(self):
self.updated_ts = datetime.datetime.now()
# Example usage
record1 = Record()
print(record1.updated_ts) # Output: current timestamp
record1.update_record()
print(reco... | |
01503a2a239a2a2a59b9 | ```csharp
public class ItemUpdater : IItemUpdater
{
public void UpdateQuality(ExtendedItem item)
{
if (item.Name != "Sulfuras")
{
item.SellIn--;
if (item.Name != "Aged Brie" && item.Name != "Backstage passes")
{
if (item.Quality > 0)
... | |
015073976ca18bbe20a0 | ```python
def visite_node(node, current_path):
current_path.append(node) # Add the current node to the current path
if not node.neighbours: # If the current node has no neighbours, the current path is complete
paths.append(current_path.copy()) # Add a copy of the current path to the paths list
e... | |
01508c9c9f642102caae | ```python
def generate_log_pattern(level, datetime, transaction, project_name, class_name, function_name, message):
_message = message
_title_pattern: str = f"[{level}][{datetime}] - {transaction} - "
_name_pattern: str = f"{project_name}.{class_name}.{function_name} - "
_loggger_pattern = f"{_title_pat... | |
01519d700d9989ccaf68 | ```csharp
public class PersonInfo
{
public string LastName { get; set; }
public int? OrganizationId { get; set; }
public string OrganizationName { get; set; }
public string GetPersonInfo()
{
if (OrganizationId.HasValue)
{
return $"Last Name: {LastName}, Organization: {Or... | |
01539bd84b80f407c5e8 | ```javascript
function canAcceptOffer(address buyer, uint256 offerId, uint256 amount) external view returns (bool) {
// Check if the buyer has sufficient balance to make the purchase
uint256 buyerBalance = item1155.balanceOf(buyer, 0);
if (buyerBalance < amount) {
return false;
}
// Get off... | |
0153d5eeeab2222f8ed0 | ```python
def validate_MS_password(entered_password):
correct_password = "MS@P@55w0rd"
if entered_password == correct_password:
return "Password validated successfully"
else:
return "Incorrect password. Access denied."
```
The `validate_MS_password` function compares the entered password wi... | |
0154a99a2121bec83652 | The provided Python class `CurveSimulator` initializes with parameters `a` and `curve_func`. It has a method `calculate` that takes a numerical argument `sgn` and returns a dictionary with keys `'curve'` and `'diff'`, representing the result of applying the `curve_func` and its differential to a modified value of `a`. ... | |
0154fb0a862619d21730 | ```python
# Import necessary libraries for image processing
import numpy as np
from PIL import Image
def png_to_xpm(name):
# Implement the conversion of PNG to XPM format
# Use appropriate libraries to read the PNG image and convert it to XPM format
# Save the XPM file with the specified name
def xpm_to_p... | |
015558a465cc4f0845e4 | ```python
class workflow_IngestAcceptedSubmission:
def __init__(self, settings, logger, param1, param2, param3, param4):
self.settings = settings
self.logger = logger
self.param1 = param1
self.param2 = param2
self.param3 = param3
self.param4 = param4
self.name... | |
0158d2a935eacdef8760 | ```java
import java.util.Set;
public class User {
private Set<User> friendList;
// Other class members and methods are not shown for brevity
public Set<User> getFriendList() {
return friendList;
}
}
```
The solution is already provided in the code snippet. The `getFriendList` method simply r... | |
01591382e514cea5fee1 | ```python
class TestFunction:
def f(self, x):
# Placeholder implementation for the function
return x**2 + 2*x + 1
```
In this solution, the `f` method of the `TestFunction` class is implemented to calculate the value of the function at the given input `x`. The specific implementation provided here i... | |
01592125c2cb4525cd76 | ```python
import heapq
import hashlib
def generate_shingles(document: str, k: int) -> set:
shingles = set()
min_heap = []
for i in range(len(document) - k + 1):
shingle = document[i:i + k]
shingle_hash = hashlib.md5(shingle.encode()).hexdigest()
heapq.heappush(min_heap, shingle_hash... | |
0159e0d399586788e73d | ```python
import VL53L0X
import RPi.GPIO as GPIO
import time
class VL53L0XManager:
def __init__(self, sensor1_address, sensor2_address, sensor1_shutdown_pin, sensor2_shutdown_pin):
self.tof1 = VL53L0X.VL53L0X(address=sensor1_address)
self.tof2 = VL53L0X.VL53L0X(address=sensor2_address)
self... | |
015b5ffaeabb7d375e28 | ```python
def navigate_grid(grid, start, destination):
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def is_valid_move(row, col):
return 0 <= row < rows and 0 <= col < cols and grid[row][col] == 0
def dfs(row, col):
if (row, col) == destination:
... | |
015b93b3f56763d4f2e1 | ```rust
struct Paginator<T> {
items: Vec<T>,
limit: usize,
}
impl<T> Paginator<T> {
fn new(items: Vec<T>) -> Self {
Paginator { items, limit: 10 } // Default limit set to 10
}
fn limit(&mut self, limit: usize) -> &mut Self {
self.limit = limit;
self
}
fn page(&self... | |
015c1883d29115474bb9 | ```python
from flask import Flask, request, jsonify
import json
import os
app = Flask(__name__)
data_file = 'books.json'
def load_books():
if os.path.exists(data_file):
with open(data_file, 'r') as file:
return json.load(file)
else:
return {"books": []}
def save_books(books):
... | |
015d231911b859afa8f9 | ```rust
// Define the Request and Response structs
struct Request {
// Define the request properties
}
struct Response {
// Define the response properties
}
// Define the Middleware trait
trait Middleware {
fn handle(&self, req: Request) -> Response;
}
// Implement the listener module
mod listener {
... | |
016062d103e1972e3ab7 | ```csharp
// Assuming obj is the user object retrieved from the authentication process
if (obj != null)
{
// Assuming emailaddress is the user's email address
HttpContext.Session.SetString("emailaddress", emailaddress);
return View("Welcome");
}
else
{
return View("Index");
}
```
In the solution, the co... | |
01609730ff9a5e3fa82d | ```python
from typing import List, Dict
def count_algorithm_categories(categories: List[str]) -> Dict[str, int]:
category_counts = {
'general': 0,
'hard_example_mining': 0,
'aggregation': 0,
'multi_task_learning': 0,
'unseen_task_detect': 0
}
for category in categor... | |
016285f105a28d462c3b | ```python
import logging
import threading
class Logger:
def __init__(self):
self.__reader = None
def setup_logging(self, filename, format, datefmt, verbosity):
level = logging.INFO
if verbosity:
level = logging.DEBUG
logging.basicConfig(filename=filename, filemode='... | |
01652982b67f97439922 | The given code snippet has a couple of issues:
1. The first line is commented out, so it does not have any effect on the program.
2. The second line is also commented out, so it does not have any effect on the program.
3. The print statement inside the loop is missing a separator to separate the numbers being printed.
... | |
01658ad5a5c15e9ab569 | ```java
private void performActionDown(MotionEvent ev) {
// Store the x and y coordinates of the touch event
mDownX = (int) ev.getX();
mDownY = (int) ev.getY();
// Check if the delete option is currently displayed
if (isDeleteShow) {
// Obtain the ViewGroup corresponding to the item at the ... | |
0166989984479ba13787 | ```python
def autodiscover_admins(modules: list) -> dict:
result = {}
for module in modules:
module_name = module.__name__
for attr_name in dir(module):
attr = getattr(module, attr_name)
if hasattr(attr, '__module__') and attr.__module__ == module_name and attr_name.start... | |
016741c8aae72a58b250 | ```typescript
function testOmitted(fn: (a?: number, b?: number) => number): number {
return fn(1, 2);
}
// Test cases
assert(testOmitted((a, b) => a + b) == 3);
assert(testOmitted(a => a) == 1);
assert(testOmitted(() => 42) == 42);
```
The `testOmitted` function takes a single argument `fn`, which is a function tha... | |
0167bca48c656aa6a45f | ```python
def calculate_precision(predictions, ground_truth) -> float:
true_positives = sum(1 for p, gt in zip(predictions, ground_truth) if p >= 0.5 and gt == 1)
false_positives = sum(1 for p, gt in zip(predictions, ground_truth) if p >= 0.5 and gt == 0)
precision = true_positives / (true_positives + false... | |
0167f5d7bd61020f5c2d | ```python
import typing
class Args(typing.NamedTuple):
global_flag: bool
python: bool
r: bool
java: bool
scala: bool
def execute(args: Args):
if args.python:
# Perform software-specific initialization for Python
print("Initializing software-specific settings for Python...")
... | |
016a0065390099455976 | ```rust
// Define the Sim struct to represent the memory simulation
struct Sim {
memory: Vec<u8>,
}
impl Sim {
// Implement the new method to create a new instance of the simulation
fn new(memory: Vec<u8>) -> Sim {
Sim { memory }
}
// Implement the start method to initiate the memory simul... | |
016a550769a9e41e388a | ```python
class Collection:
def __init__(self, data):
self.data = data
@classmethod
def from_array(cls, arr):
return cls(arr)
class SumReoccurringDataPoints:
def transform(self, collection):
seen = set()
recurring_sum = 0
for data_point in collection.data:
... | |
016bc2fd0864b6fadffa | ```php
/**
* Retrieves references for the given list item IDs.
*
* @param string[] $listItemIds An array of item IDs for which references need to be retrieved.
* @return string[] An array of references corresponding to the input item IDs.
*/
public function retrieveReferences(array $listItemIds) {
// Simulatin... | |
016c716c5672e6c0a07b | ```python
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
# Function to split the dataset into training and development testing sets
def split_dataset(dataset, test_... | |
016d47efeb111f93ba1f | ```javascript
class FindAllTodoItemUseCase {
constructor(todoDataSource) {
this.todoDataSource = todoDataSource;
}
execute() {
return this.todoDataSource.getAllTodoItems();
}
}
export { FindAllTodoItemUseCase };
```
In the solution, the FindAllTodoItemUseCase class is modified to accept a todoDataSou... | |
016f0ba7fdbab0137f08 | ```python
def generate_complaint_paths(tender_id, cancellation_id, complaint_id):
collection_path = f"/tenders/{tender_id}/cancellations/{cancellation_id}/complaints"
specific_complaint_path = f"{collection_path}/{complaint_id}"
return collection_path, specific_complaint_path
# Test the function
tender_id ... | |
016fc542db5b23d964da | ```python
# Calculate the aggregates per client
client_aggregates = tff.federated_map(tff_count_by_key, tff_client_dataset)
# Start to build the aggregation function
@tff.tf_computation()
def build_zeros():
key_size = len(key_list_t)
return tf.zeros([key_size], tf.int32)
@tff.federated_computation(tf.int32, tf.i... | |
01732c7cc6581b2855cd | ```php
function connect_denglu_update() {
global $wptm_basic;
@ini_set("max_execution_time", 300); // Set the maximum execution time to 300 seconds
// Retrieve user data from the session variable or call the function to obtain the user data
$userdata = ($_SESSION['connect_denglu_update_data']) ? $_SESS... | |
01755d71cd15a890ff8a | ```python
import random
def deal_cards(players, num_cards):
suits = ['H', 'D', 'C', 'S']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
deck = [rank + suit for suit in suits for rank in ranks] # Create a standard deck of cards
random.shuffle(deck) # Shuffle the deck
... | |
017805d0bf5e98613c71 | ```javascript
import React, { useState, useEffect } from 'react';
import Alert from '../../../../components/AlertConfirm';
import CheckBoxGroup from './CheckBoxGroup';
import Input from '../../../../components/Input';
import { sentimentos } from './mock';
import { useNavigation } from '@react-navigation/native';
import... | |
0179d9c1b9f80aa064a5 | ```python
from typing import List, Dict, Union, Optional
class OrderManager:
def __init__(self):
self.orders = {}
def create_order(self, customer_name: str, items: List[str]) -> str:
order_id = str(len(self.orders) + 1)
self.orders[order_id] = {'customer_name': customer_name, 'items': ... | |
017ab1b5ff92f7b77aee | ```python
class Job:
def __init__(self, job_id):
self.job_id = job_id
def run(self):
print(f"Job {self.job_id} is running")
class Workflow:
def __init__(self, workflow_id, definition=None):
self.workflow_id = workflow_id
self.definition = definition if definition is not No... | |
017ba340f7fae1529784 | ```cpp
void Scoreboard::clearInstDests(MinorDynInstPtr inst, bool clear_unpredictable) {
// Iterate through the destinations of the instruction
for (auto& dest : inst->getDestinations()) {
if (clear_unpredictable || !dest.isUnpredictable()) {
// Clear the destination if either clear_unpredic... | |
017c9af37a776185ac97 | ```python
from datetime import datetime
class Payment:
def __init__(self, time, entity, amount, source, is_donation, notes=None, bank_reference=None, pending=False):
self.time = time # Date & time the payment occurred
self.entity = entity
self.amount = amount
self.source = source
... | |
017cb50b445a123ca403 | ```python
class LocationCache:
def __init__(self):
self.location_id_to_location = {}
def get_location(self, location_id):
if location_id in self.location_id_to_location:
return self.location_id_to_location[location_id]
location = SQLLocation.by_location_id(location_id)
... | |
017ebe4504963d7b55ea | ```java
public PsiElement findTargetElement(StructureViewTreeElement root, PsiElement target) {
if (root == null || target == null) {
return null;
}
if (root.contains(target)) {
return target;
}
if (root.getChildren() != null) {
for (StructureViewTreeElement child : root.ge... | |
017fff817dd85ca782a1 | ```python
def is_valid_html(html: str) -> bool:
stack = []
i = 0
while i < len(html):
if html[i] == "<":
if html[i + 1] == "/":
if not stack or stack[-1] != html[i + 2 : html.find(">", i + 2)]:
return False
stack.pop()
i... | |
01804fcb796cab33f303 | ```c
double calculateAverageFPS(int* frameTimes, int numFrames) {
double totalFPS = 0.0;
for (int i = 0; i < numFrames; i++) {
totalFPS += 1000.0 / frameTimes[i]; // Convert time interval to FPS
}
return totalFPS / numFrames; // Calculate average FPS
}
``` | |
0181036ef90114ac611e | ```typescript
export interface ApiKeyInput {
/**
* The name you will use to describe this API Key.
*/
name: string;
/**
* The individual permissions that you are giving to this API Key.
*/
permissions: string[]; // Define the type for permissions, e.g., string array or specific enum
}
```
In the sol... | |
0181d2573cc07691097e | ```rust
fn path_join(base_path: &str, sub_path: &str) -> String {
if base_path.ends_with('/') {
format!("{}{}", base_path, sub_path)
} else {
format!("{}/{}", base_path, sub_path)
}
}
``` | |
0181e9408479fd341f6a | ```csharp
using System.Linq;
using System.Threading.Tasks;
using TheBall;
namespace ProBroz.OnlineTraining
{
public class GetOrInitiateDefaultGymImplementation
{
public async Task<Gym> GetOrInitiateDefaultGym()
{
// Check if default gym exists in the database
var existin... | |
01840c23d0075537fbef | ```python
from rest_registration.settings import registration_settings
from rest_registration.utils.signers import URLParamsSigner
class RegisterEmailSigner(URLParamsSigner):
SALT_BASE = 'register-email'
USE_TIMESTAMP = True
def get_base_url(self):
return registration_settings.REGISTER_EMAIL_VERIF... | |
01864dac77c33cb1223f | ```typescript
class KeyValueStore {
private store: Record<string, any>;
constructor() {
this.store = {};
}
add(key: string, value: any): void {
this.store[key] = value;
}
get(key: string): any {
return this.store[key];
}
remove(key: string): void {
delete this.store[key];
}
getA... | |
018d2aba09d096bdc5a6 | ```python
def process_data_representations(data_representations):
total_data_representations = len(data_representations)
total_resolution = sum(rep["Resolution"] for rep in data_representations)
average_resolution = total_resolution / total_data_representations
highest_x_source = max(data_representatio... | |
018d667432bb176e52ce | ```python
import re
def extract_and_manipulate_env_vars(env_vars, keyword):
extracted_values = []
for env_var in env_vars:
match = re.match(r'export\s+{}\s*=\s*"([^"]+)"'.format(keyword), env_var)
if match:
extracted_values.append(match.group(1))
if keyword == "PWD":
lo... | |
018eb15ef50d56906a93 | ```java
import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
public class Hg {
private String package_name;
private int drawable;
private int extraId;
// Constructor to initialize package name, drawable resource ID, and extra resource ID
public Hg(String packageName, @Drawable... | |
018ff8c168af0e8d4e92 | ```python
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
from typing import Union
def check_extension_support(extension_name: str) -> Union[int, str]:
if extensions.has_extension(extension_name):
constant_value = glget.GLint()
glget.glGetIntegerv(extensions.GL_DEPTH_COMPONE... | |
0194b233fc2e3b45fbc2 | ```bash
#!/bin/bash
get_git_revision() {
local srcdir="$1"
local revision=""
# Extract revision from Git log if not provided
if [ -z "$revision" ]; then
revision=$(cd "$srcdir" && git log -1 --pretty=format:"git-%cd-%h" --date=short 2> /dev/null)
fi
# Extract revision from directory name if still not... | |
0195aa55b8cd363cb1fd | ```python
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve, auc
from sklearn import neighbors
from sklearn.datasets import fetch_openml
# Load the MNIST dataset
mnist = fetch_openml('mnist_784', version=1)
X... | |
0195f67857dc5e2c7793 | ```python
from dataclasses import dataclass
from typing import List
import numpy as np
@dataclass
class ItemText:
color: str = None
roi: List[int] = None
data: np.ndarray = None
ocr_result: OcrResult = None
clean_img: np.ndarray = None
valid: bool = False
def __getitem__(self, key):
... | |
01972009bb664cdc8981 | ```java
public Unbatch<T> batch(List<T> data, int batchSize) {
List<List<T>> batches = new ArrayList<>();
for (int i = 0; i < data.size(); i += batchSize) {
int end = Math.min(i + batchSize, data.size());
batches.add(data.subList(i, end));
}
return new Unbatch<>(batches);
}
```
The `batch` method takes... | |
019963f07ea120022c50 | ```php
class CurrencyConverter
{
private $exchangeRates;
public function __construct($exchangeRates)
{
$this->exchangeRates = $exchangeRates;
}
/**
* Retrieve the exchange rate for converting from one currency to another.
*
* @param string $fromCurrency The currency to conve... | |
0199f097def7e4ed5839 | ```typescript
function calculateTotalDistance(scrollPositions: { x: number, y: number }[]): number {
let totalDistance = 0;
for (let i = 1; i < scrollPositions.length; i++) {
const distance = Math.sqrt(
Math.pow(scrollPositions[i].x - scrollPositions[i - 1].x, 2) +
Math.pow(scrol... | |
019a36eeb2837e9795a3 | ```python
# Custom error handling in Django web application
# Import necessary modules
from django.shortcuts import render
from django.template import RequestContext
from django.conf import settings
# Custom view function to handle 500 errors
def server_error(request):
return render(request, '500.html', status=50... | |
019c42b64554dc3fd8de | ```typescript
export class RhdJustification extends Struct {
performConsensusOperation(values: any[]): any {
const frequencyMap = new Map();
let maxFrequency = 0;
let mostFrequentValue = null;
for (const value of values) {
const frequency = (frequencyMap.get(value) || 0) + 1;
frequencyMap... | |
019d10c2dffc0e1c4a41 | ```cpp
class ContextBuffers {
private:
bool _allocated;
int _deviceId;
void* _execStream;
void* _specialStream;
public:
// Constructor to initialize the ContextBuffers object with the device ID and allocate necessary resources
ContextBuffers(int deviceId) : _deviceId(deviceId), _allocated(true)... | |
019d161c50935f143c3e | ```python
import multiprocessing as MP
def square_sum(nums):
return sum(x**2 for x in nums)
if __name__ == "__main__":
input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pool_size = MP.cpu_count() * 2
print('Pool count', pool_size)
with MP.Pool(pool_size) as pool:
chunk_size = len(input_lis... | |
019ec904358192b37653 | ```cpp
#include <Print.h>
class Logger {
private:
Print *stream;
bool infoEnabled;
bool warningEnabled;
bool errorEnabled;
public:
Logger(Print *printer) : stream(printer), infoEnabled(true), warningEnabled(true), errorEnabled(true) {}
void enableInfoLogging() { infoEnabled = true; }
void disableInfoLo... | |
019fe8710f51b3c35891 | ```python
import socket
import queue
from typing import NamedTuple
class DiscoverySource(NamedTuple):
interface_name: str
src_address: str
dst_address: str
dst_is_broadcast: bool
def receiver(sock: socket.socket, max_discovery_secs: float,
response_queue: queue.Queue) -> None:
start_t... | |
01a114b9948ccfbbbcbf | ```php
function organizeItems(array $items): array {
$hierarchicalStructure = [];
foreach ($items as $item) {
$code = $item->kode;
foreach (array_keys($hierarchicalStructure) as $prefix) {
if (str_starts_with($code, $prefix)) {
$hierarchicalStructure[$prefix][] = $it... | |
01a36b9860fb66b8d02c | ```bash
#!/bin/bash
# Function to verify the number of arguments
bfl::verify_arg_count() {
local arg_count="$1"
local expected_count="$2"
local error_code="${3:-1}" # Default error code is 1
if [ "$arg_count" -ne "$expected_count" ]; then
echo "Error: Expected $expected_count argument(s), but received $a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.