text stringlengths 301 97.6k |
|---|
# -*- coding: utf-8 -*-
"""
AvailableTaskPCMatch Resource for assigning subtasks to available machines
based on status, labels, and preconditions in a QA automation system.
This module implements a Flask-RESTful resource that finds the next available
(subtask, machine) pair for execution, ensuring data consistency wit... |
"""
Module: word_classifier_repository.py
This module defines the `WordClassifierRepository` class, which is responsible for classifying a given word
based on its part of speech and associated linguistic properties (e.g., tense, number, gender) using a dictionary
data source. It leverages a repository pattern and inte... |
"""
Substitution Cipher Decoder
This script reads an encrypted text file and decodes it using a predefined substitution cipher.
The cipher swaps specific letters according to a fixed mapping (e.g., 's' ↔ 'z', 'a' ↔ 'e', 'r' ↔ 'b').
The script demonstrates file handling, string manipulation, and character-level process... |
from typing import Tuple
def get_three_integers(prompt: str = "Enter an integer") -> Tuple[int, int, int]:
"""
Prompts the user three times to input integers.
Args:
prompt (str): Base prompt message for input.
Returns:
Tuple[int, int, int]: Three integers entered by the user.
Ra... |
"""
Module: is_square.py
A robust implementation of a function to determine whether a given number
is a perfect square of a natural number (non-negative integer), demonstrating
defensive programming techniques.
This function handles:
- Negative numbers (returns False)
- Floating-point numbers (accepts but warns)
- No... |
"""
Regex Number Summation Tool
This script reads text files, extracts all numbers using regular expressions,
and computes their sum. It demonstrates file handling, regex pattern matching,
and robust data processing in Python.
The primary use case is solving problems where numbers are embedded in text,
such as log fi... |
"""
Reddit Top Video Creator
This script automates the creation of a YouTube-style video from the top weekly posts
on a specified Reddit subreddit (e.g., r/mildlyinteresting). It:
1. Fetches top posts with images
2. Downloads and resizes images to 1920x1080
3. Generates text-to-speech (TTS) narration for titles
4. Com... |
"""
Last Word Problem (Google Code Jam 2016 Qualification Round)
Given a string S, construct the "last word" by starting with the first letter,
then for each subsequent letter, placing it at the beginning or end of the current word
to maximize the lexicographical value.
Example:
Input: "CAB"
Step 1: word = "C... |
from math import ceil
from typing import List, Tuple
def is_balanced(num: int) -> bool:
"""
Check if a number is 'balanced'. A number is balanced if the sum of the digits in the first half
is equal to the sum of the digits in the second half. For odd-length numbers, the middle digit
is included in bot... |
"""
Graph Autoencoder for Heterogeneous Graph Representation Learning
This script implements a two-stage training pipeline for a graph autoencoder
that learns node embeddings from both execution and file dependency graphs.
The model uses an attention-based encoder and a deep neural network decoder
to reconstruct node ... |
"""
FizzBuzz 문제 해결 프로그램
이 프로그램은 1부터 주어진 수까지의 정수를 출력하되, 다음 규칙에 따라 값을 변환합니다:
- 3의 배수: "Fizz"
- 5의 배수: "Buzz"
- 3과 5의 공배수 (즉, 15의 배수): "FizzBuzz"
- 그 외: 숫자 자체
이 구현은 가독성, 유지보수성, 확장성을 고려하여 작성되었습니다.
"""
from typing import Generator, Union
def fizzbuzz_value(n: int) -> str:
"""
주어진 정수에 대한 FizzBuzz 값을 계산하여 문자열로 반환... |
#!/usr/bin/python3
"""
Ultimate Tic-Tac-Toe AI Agent using Alpha-Beta Pruning with Heuristic Evaluation
This agent plays Ultimate Tic-Tac-Toe (a 3x3 grid of 3x3 boards) against an opponent.
It uses an Alpha-Beta search algorithm with a custom heuristic to evaluate board states
and determine the best move within a time... |
"""
gPhoton Sky Mapping Script
This script demonstrates how to use the `gMap` function from the `gPhoton` package
to generate a sky map (image) from GALEX photon data. It creates both a time-resolved
count map and a co-added (total) count map for a specified region of the sky.
The script is structured to be reusable,... |
"""
Plagiarism Checker Tool (plag-check)
This script performs a basic plagiarism detection by:
1. Reading text line-by-line from an input file.
2. For each non-empty line, it searches for the top 3 relevant web URLs using a search query.
3. Fetches content from those URLs and compares them to the original line using f... |
"""
User Management Views for Django Application
This module defines class-based views and helper functions for handling user-related
functionality such as viewing, updating, and redirecting users based on their group membership.
It leverages Django's authentication system and class-based views for clean, reusable cod... |
"""
MS Stream Video Downloader CLI
This script provides a command-line interface to download videos from Microsoft Stream
using user credentials and a video URL. It leverages a custom `Downloader` class and
automatically cleans up temporary cookie files before initiating the download.
The script expects two required ... |
"""
diag_spec_generator.py
This script generates `.opb` (pseudo-Boolean optimization) and `.key` (variable mapping) files
for a digital circuit verification problem involving multiplication and comparison of two `n`-bit numbers.
The problem models:
- Two input bit vectors `x` and `y` of length `numBits`
- Their produ... |
"""
Traffic Analysis Tool for Detecting Reverse Meterpreter Sessions
=================================================================
This script analyzes live network traffic using `scapy` and `netfilterqueue` to detect potential
reverse Meterpreter sessions (both `reverse_https` and `reverse_tcp`) based on behavior... |
from typing import Optional, Any
class Node:
"""
A class representing a node in a singly linked list.
Each node contains data and a reference to the next node in the list.
"""
def __init__(self, data: Any):
"""
Initialize a node with the given data.
Args:
dat... |
"""
Program to count the number of zeros in a tuple.
This script demonstrates multiple approaches to count the occurrences of the value 0
in a given tuple. It includes error handling, type annotations, and is written in a
clean, Pythonic style for educational purposes.
"""
from typing import Tuple, Union
def count_... |
"""
Holonomic Constraint Dynamics Test: Simulating and Comparing Torque and State Derivatives
This script evaluates the dynamics of a robotic system under holonomic constraints (e.g., ground contact)
by comparing the predicted state derivative (from a dynamic model) with the actual observed change in state
during simu... |
"""
Dijkstra's Algorithm for Shortest Path in an Undirected Weighted Graph
This script solves a problem where we are given an undirected, weighted tree (a special case of a graph),
and we need to answer multiple queries about the sum of shortest distances from a fixed source node
to two given nodes. The solution uses ... |
"""
Gradient Descent Optimization Example
This script demonstrates the use of gradient descent to minimize a simple quadratic function.
It includes visualization of the optimization path and detailed logging.
Function: f(x) = x^2 - 4x + 6
Derivative: f'(x) = 2x - 4
Minimum occurs at x = 2, f(2) = 2
"""
import numpy ... |
"""
Module: stats.py
Description: A comprehensive statistics module to compute median, mode, and mean of a list of numbers.
Author: Assistant
Date: 2024
This module demonstrates proper Python practices including:
- Type hints
- Docstrings
- Error handling
- Immutability (avoiding in-place sorting)
- Code modularity an... |
"""
Sports App Views Module
This module contains the Django views for handling user authentication and navigation
in a sports management application. It includes login, logout, and home page logic,
with role-based redirection (athletes, coaches) after login.
The views use Django's authentication system and custom dec... |
"""
Logistic Regression with L1 and L2 Regularization
=================================================
This script implements logistic regression using gradient descent,
with optional L1 (Lasso) and L2 (Ridge) regularization for binary classification.
It evaluates performance using accuracy, precision, recall, and F1-... |
"""
Binary Search Tree (BST) Implementation with Full Functionality
This module provides a complete and robust implementation of a Binary Search Tree (BST),
including insertion, deletion, traversal (inorder, preorder, postorder), search, and utility functions.
The code follows Python best practices, includes type hint... |
"""
Django Application Configuration Module
This module defines the application configuration for the 'tests' app.
It uses Django's AppConfig to customize the behavior of the app when it's loaded.
The code is designed to be compatible with both modern and older versions of Django,
gracefully degrading when AppConfig i... |
"""
Setup script for the `pictools` package.
This script configures the `pictools` Python package, which provides command-line tools
for processing and analyzing image data. It uses `setuptools` to define package metadata,
dependencies, and console script entry points.
The package includes:
- Image manipulation utili... |
"""
Continuous Atmospheric Dispersion Model API
===========================================
This Flask-based service simulates the dispersion of pollutants in the atmosphere
using a continuous emission model. It calculates concentration peaks over time and
sends results to a remote endpoint.
The model supports:
- Tim... |
"""
UDP Server for Receiving and Displaying Messages
This script implements a simple UDP server that listens for incoming messages
on a specified port and prints them to the console. It uses the `socket` module
to create a connectionless UDP socket, binds it to a local address, and continuously
listens for client mess... |
"""
Django view for handling user signup with form validation and authentication.
This module defines a `signup` view that allows new users to register using a
`SignUpForm`. Upon successful registration, the user is automatically logged in
and redirected to the home page. The implementation follows Django best practic... |
"""
선형 회귀 모델을 TensorFlow 1.x 기반으로 구현한 예제입니다.
이 코드는 주어진 데이터(x_train, y_train)를 기반으로 y = 2x 형태의 선형 관계를 학습하고,
학습된 모델을 사용해 새로운 입력값에 대한 예측을 수행합니다.
주요 기능:
- TensorFlow를 사용한 선형 회귀 모델 정의 (W * x + b)
- 손실 함수: 평균 제곱 오차(MSE) 기반
- 최적화: 경사하강법(Gradient Descent)
- 텐서보드를 통한 학습 과정 시각화
- 모델 평가 및 예측 출력
주의: 이 코드는 TensorFlow 1.x 스타일이며, 세... |
"""
IPv7 Address Validator - ABBA Pattern Detection
This script processes IPv7 addresses to determine which support "TLS" (Tunnel Layer Snooping)
based on the presence of ABBA patterns (e.g., 'abba', 'xyyx') in non-hypernet sequences
and absence of such patterns in hypernet sequences (within square brackets).
An ABBA... |
"""
Weather App View Module
This module handles the main view for a weather dashboard that allows users to add cities
and view current weather data using the OpenWeatherMap API. It integrates Django forms
and models to persist city entries and display real-time weather information.
Key Features:
- Form handling for a... |
"""
Constants for the Trafikverket Weather integration.
This module defines constants used throughout the Home Assistant integration
for retrieving and processing weather data from Trafikverket (the Swedish
Transport Administration). These constants include configuration keys,
platform settings, sensor attributes, and... |
"""
SSH Management Views for Django Web Application
This module provides Django views to:
1. Upload and parse SSH configuration files (INI format)
2. Store SSH connection details in the database
3. Execute remote commands (e.g., 'date') across multiple servers
4. Display results in HTML templates
Dependencies:
- Djan... |
"""
Module for managing database file paths in the application.
This module provides a function to retrieve the path to the SQLite3 database file,
ensuring it's resolved relative to the project's local directory structure using
a utility function. It includes error handling and type annotations for robustness.
"""
fr... |
"""
Django AppConfig for the 'flock' application.
This module defines the configuration class for the 'flock' Django app.
It ensures that app-specific setup, such as signal registration, occurs only once
during the application's initialization phase, preventing duplicate executions
in development mode (e.g., when Djan... |
"""
Word Analogy Evaluation Module
This module evaluates word embedding models on analogy tasks (e.g., "king - man + woman = queen").
It supports both semantic and syntactic analogy categories and allows restricting predictions
to a predefined set of top frequent words.
The dataset format expected is:
: gram_adje... |
"""
Enhanced plotting of linear equations using SymPy.
This script demonstrates how to plot multiple linear functions with custom styling,
including different colors and a legend. It uses SymPy's plotting capabilities to
visualize the intersection and behavior of two lines: y = 2x + 3 and y = 3x + 1.
Key features:
- ... |
"""
Module: text_model.py
This module defines a Pydantic model for representing textual content, specifically an article.
Using Pydantic, we ensure data validation, type hints, and clear structure for incoming data,
which is especially useful in APIs (e.g., with FastAPI) or data processing pipelines.
The `Text` model... |
"""
ASGI Configuration for the Origani Django Project.
This module configures the Asynchronous Server Gateway Interface (ASGI) for the Origani project,
enabling support for asynchronous web protocols such as HTTP/2, WebSockets, and long-polling.
The `application` object defined here is the standard entry point for AS... |
"""
Speed Limit Sign Prediction Using a Pre-Trained Deep Learning Model
This script demonstrates how to load a pre-trained TensorFlow model and use it to predict
the speed limit class from an input image (PPM format). The implementation includes:
- Proper error handling
- Type annotations
- Modular design
- Clear docu... |
"""
Time Series Analysis of Wage Shares in Service vs Non-Service Industries
========================================================================
This script analyzes wage share trends in service and non-service industries
over time using data from 1997 to 2014. It performs data cleaning, descriptive
statistics, a... |
"""
LVM (Logical Volume Manager) Automation Tool
This script automates the creation of Physical Volumes (PV), Volume Groups (VG),
and Logical Volumes (LV) on Linux systems using LVM. It also formats the LV with
ext4 and mounts it to a specified directory.
The script uses the `subprocess` module to interact with syste... |
from typing import List, Set, Optional
def find_pair_sum(arr: List[int], target_sum: int) -> bool:
"""
Determine if there exists a pair of distinct elements in the array that add up to the target sum.
This function uses a set to store the complement (target_sum - current value) of each element
as it ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Rezeptionistin Bot - A Receptionist Bot for Managing Interactions
This script initializes and runs a bot named 'Rezeptionistin', designed to act as a
virtual receptionist. It handles user interactions, possibly in a chat or service environment.
The original code was w... |
#!/usr/bin/env python3
# encoding: utf-8
"""
Plasma Physics Initial Conditions Generator
This module provides classes to define and analyze initial conditions for plasma simulations,
including thermal equilibrium, double Harris sheet, and single current layer configurations.
It computes key plasma parameters such as D... |
"""
Sorting Algorithms Implementation and Comparison
This script demonstrates two classic sorting algorithms:
- Bubble Sort
- Selection Sort
It allows the user to input a list of integers, then applies both sorting algorithms
and displays the results. The code is structured to be educational, well-documented,
and fol... |
# -*- coding: utf-8 -*-
"""
HP OneView Task Manager Example
================================
This script demonstrates how to interact with the HP OneView API to retrieve and manage tasks
using the `hpOneView` Python SDK. It includes functionality to:
- Load configuration securely from a file or fallback to defaults.
-... |
"""
Demonstration of subprocess module usage in Python.
This script illustrates various ways to execute external commands and interact with them
using the `subprocess` module. It covers:
- Running shell commands with `subprocess.run()`
- Capturing output from processes
- Passing input to subprocesses
- Using both `run... |
"""
Stripe Payout and Bank Account Management Module
This module provides utilities to:
1. Create payouts to connected Stripe accounts (e.g., vendors/sellers).
2. Update or add bank account details for connected Stripe accounts.
It integrates with Django models via `apps.get_model`, uses Stripe API for financial oper... |
"""
Object Tracking with OpenCV and Imutils
=======================================
This script performs real-time object tracking using various OpenCV tracking algorithms.
It supports both webcam input and video files, and allows the user to select a region of interest (ROI)
to track using a keyboard command.
Key Fe... |
"""
Internal TensorFlow Types Module
This module defines types that are natively supported by TensorFlow operations.
These types are intended for internal use within TensorFlow and should not be
exported or relied upon by external code. The primary purpose is to allow
type-checking and dispatch logic within TensorFlow... |
"""
Batch HADD Script for ROOT Files
This script scans the current working directory for subdirectories and generates
`hadd` commands to merge all `.root` files within each subdirectory into a single
output file named after the directory.
The `hadd` command is commonly used in high-energy physics (HEP) to combine
ROO... |
"""
Análisis del problema:
Se desea comparar la suma de todos los elementos de dos matrices (m_1 y m_2),
ambas de dimensiones 8x10, conteniendo números reales en el rango [0, 100] con hasta dos decimales.
Se debe determinar si ambas sumas son iguales y mostrar un mensaje adecuado.
Preguntas de análisis:
a) ¿Qué entra... |
"""
Data Generator for a School Management System
This script generates synthetic data for a school database, including:
- Tutors (parents/guardians)
- Children (students)
- Allergies
- Financial dues (adeudos)
- Employment and contact information
The data is printed in SQL INSERT-ready format for easy integration.
... |
"""
Setup script for OpenTelemetry OTLP HTTP Proto Exporter.
This script reads the version information from a dynamically generated version file
and configures the package metadata accordingly. It follows best practices for
Python packaging, including error handling, type annotations, and modularity.
The package is l... |
"""
Program to find all divisors of a given number, print them, and count how many there are.
This script:
- Takes an integer input from the user.
- Finds all positive divisors of the number.
- Prints each divisor.
- Counts and displays the total number of divisors.
Note: The variable `fact` in the original code was ... |
"""
粉丝互动率计算工具
该程序计算用户的互动率(互动量 / 粉丝量),常用于社交媒体数据分析。
例如:评估内容创作者的内容吸引力或用户参与度。
"""
from typing import Union, Optional
def calculate_engagement_rate(interactions: int, followers: int) -> Optional[float]:
"""
计算互动率(Engagement Rate)
互动率 = 互动量 / 粉丝量
常用于衡量社交媒体账号的用户参与度。
Args:
interactions (int): ... |
"""
Thesis Crawler and Web Interface
This Flask application crawls XML-based thesis metadata from remote servers,
parses the data, stores it in a MySQL database, and provides a simple web interface
to view, crawl, and delete thesis records.
Key Features:
- Crawling multiple university servers for thesis metadata
- Pa... |
"""
File Extension Extractor
This program accepts a filename from the user and prints its extension.
It handles various edge cases such as:
- Files with no extension
- Hidden files (starting with a dot)
- Multiple dots in the filename
- Empty input
- Files with only an extension (e.g., .gitignore)
The solution uses P... |
from datetime import date
from typing import Union
def calcular_aumento_salarial_com_dobro_do_percentual(
ano_inicial: int, salario_inicial: float, percentual_inicial: float, ano_final: Union[int, None] = None
) -> dict:
"""
Calcula o aumento salarial anual com percentual dobrado a cada ano.
A função... |
"""
[구현] 주방장 도도새 - 주문 처리 시뮬레이션
문제 개요:
- 주방장은 순차적으로 주문을 처리하며, 각 주문은 일정한 조리 시간이 필요함.
- 근무 시간(T) 내에서 처리할 수 있는 최대 주문 수를 구해야 함.
- 주문은 리스트 형태로 주어지며, 앞에서부터 순서대로 처리함.
- 누적 조리 시간이 근무 시간을 초과하면 더 이상 주문을 받지 않음.
예시:
입력: N=5, T=10, orders=[3, 3, 3, 3, 3]
처리: 3 + 3 + 3 = 9 (<=10), 다음 3 더하면 12 (>10) → 출력: 3
"""
from typing import L... |
from typing import Optional
def is_palindrome(s: str) -> bool:
"""
Recursively determine if a given string is a palindrome.
A palindrome is a word, phrase, or sequence that reads the same backward as forward,
ignoring case, spaces, and punctuation.
Base cases:
- If the string has length 0 or... |
"""
Master-Worker Communication System
This module implements a `Master` class that coordinates communication with multiple worker processes
via a `Communicator` interface. The master distributes tasks, listens for responses, manages worker
lifecycle, and maintains state across stages of execution.
Key Features:
- Dy... |
from typing import Tuple
def compute_total_rectangle_area(rect1: Tuple[int, int, int, int], rect2: Tuple[int, int, int, int]) -> int:
"""
Compute the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom-left corner (x1, y1) and top-right corner (x2, y2).... |
"""
Stance Classification Using Gradient Boosting and Multiple Feature Sources
This script performs stance classification (e.g., agree, disagree, discuss, unrelated)
on news article headlines and bodies using a Gradient Boosting Classifier. It combines
three types of features:
1. TF-IDF-based cosine similarity between... |
"""
Flask API with SQLAlchemy ORM for managing tasks and roles.
This application demonstrates:
- RESTful API design using Flask
- Database operations with Flask-SQLAlchemy
- Input validation and error handling
- JSON request/response handling
- Modular structure and documentation
Note: Requires `flask`, `flask-sqlalc... |
"""
Автоматизированный тест регистрации на веб-сайте с использованием Selenium.
Этот скрипт демонстрирует:
- Использование Selenium WebDriver для автоматизации браузера.
- Поиск и заполнение полей формы.
- Отправку формы и проверку результата.
- Обработку успешных и неудачных сценариев.
- Использование современных мет... |
"""
Countdown Game - Word & Number Rounds
=====================================
This module simulates two classic rounds from the UK TV show "Countdown":
1. **Word Round**: Players pick vowels and consonants to form the longest word possible.
2. **Number Round**: Players use arithmetic operations on selected numbers t... |
"""
Chapter 10: File Handling in Python
===================================
This educational module demonstrates various aspects of file handling in Python,
including text and binary file operations, line-based I/O, random access, standard
I/O redirection, and object persistence using built-in modules.
Each section i... |
"""
Sistema de Cadastro e Consulta de Notas de Alunos
Este programa permite ao usuário cadastrar alunos com suas duas notas,
calcular a média, exibir um boletim com todos os alunos e consultar
as notas individuais de cada aluno.
"""
from typing import List, Union
def cadastrar_aluno() -> List[Union[str, List[float]... |
"""
URL Configuration for Teacher Management App
This module defines the URL routing for the teacher-related views in the application.
Each URL pattern maps a specific endpoint to a corresponding view function in the `views` module.
The patterns support operations such as listing, adding, editing, deleting, and managi... |
from typing import List
def clean_and_format_name(name: str) -> str:
"""
Clean and properly format a name by stripping whitespace and
capitalizing the first letter while making the rest lowercase.
Args:
name (str): The raw name string.
Returns:
str: The cleaned and properly capit... |
"""
Simulated Annealing Optimization for Assignment Problems
This module implements the Simulated Annealing (SA) metaheuristic algorithm to optimize
an assignment problem, likely in the context of energy cost minimization (e.g., task or
resource allocation). It starts from a greedy initial solution and explores neighb... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Sea Station Profile Parser
==========================
This script parses an XML file containing metadata about sea observation stations,
extracts relevant information, and loads it into a PostgreSQL database.
The input XML is expected to follow a specific structure w... |
#!/usr/bin/env python
"""
HDF5 File Viewer using Silx.
This script launches a Qt-based GUI application that displays one or more HDF5 files
in a tree view, allowing users to explore the hierarchical structure of HDF5 datasets
and groups. It uses the `silx` library, which is commonly used for scientific data
visualizat... |
"""
Twilio Notify User Management Script
This script demonstrates how to:
1. Authenticate with Twilio using Account SID and Auth Token.
2. Retrieve a list of users from a Twilio Notify service.
3. Print the unique identifiers (SIDs) of each user.
The script uses the Twilio Python helper library to interact with the T... |
"""
Neural Network Training and Evaluation for Binary and Multi-Output Classification
This script demonstrates the use of a multi-layer perceptron (MLP) for:
1. Binary classification (Breast Cancer dataset): Malignant (M) vs Benign (B)
2. Multi-output regression/classification (Exercise 2, commented out)
The data is ... |
def year_to_century(year: int) -> int:
"""
Convert a given year (AD/CE) to its corresponding century number.
Examples:
year_to_century(1) -> 1 (1st century)
year_to_century(100) -> 1 (1st century)
year_to_century(101) -> 2 (2nd century)
year_to_century(2000) -> 20 (2... |
from typing import List, Dict
def partition_labels(s: str) -> List[int]:
"""
Partition a string into as many parts as possible so that each letter appears in at most one part,
and return the sizes of these parts.
This function uses a greedy algorithm:
1. First, it records the last occurrence inde... |
"""
Benchmark script for measuring the performance of `json.loads()` on various JSON string structures.
This script serializes predefined Python objects (dict, tuple, nested dict group) into JSON strings,
then repeatedly deserializes them using `json.loads()` to benchmark performance. It's designed to
emulate realisti... |
from typing import List, Set, Tuple, Dict
class Solution:
"""
A solution class to find the number of unique pairs in an array that sum up to a target value.
This implementation ensures that:
- Each pair (a, b) is counted only once, even if duplicate values exist.
- The order of elements in the pa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Numerical Example: Sequential Monte Carlo Squared (SMC²) for Stochastic Volatility Models
This script demonstrates the SMC² algorithm applied to a stochastic volatility model with leverage,
comparing standard particle filtering (SMC) and its quasi-Monte Carlo variant ... |
"""
Menu-Based Tkinter Application with Proper Structure and Best Practices
This script demonstrates how to create a well-structured, maintainable, and educational
menu-driven GUI application using Python's built-in `tkinter` module. It includes:
- Proper use of type hints
- Modular function design
- Comprehensive err... |
import sys
from typing import List, Tuple
def read_input() -> List[str]:
"""
Read N lines of input from stdin, where N is the first line.
Returns:
A list of strings representing the serial numbers.
"""
try:
n = int(sys.stdin.readline().strip())
if n < 0:
raise ... |
"""
BeesBook Filtering Editor - Main Application Window
This module defines the main window of the BeesBook Filtering Editor application,
built using PyQt4. It manages navigation between two primary tabs:
- LoaderTab: For loading and managing detection datasets.
- EditorTab: For editing and filtering the loaded data.
... |
#!/usr/bin/env python
"""
Psumuxmon Health and Sensor Path Validation Test Suite
This script defines a set of unit tests to validate the health and sensor accessibility
of the `psumuxmon` service on a system, typically used in hardware monitoring contexts
(e.g., Facebook's Open Compute Project platforms).
The tests v... |
"""
ETF Data Scraper from etf.com
This script scrapes key information (ETF segment and index tracked) from etf.com
for a given ETF ticker symbol using web scraping techniques.
Features:
- Uses `requests` and `BeautifulSoup` for HTTP requests and HTML parsing
- Handles SSL verification warnings gracefully
- Includes e... |
"""
This script demonstrates advanced slicing and assignment operations on `bytearray` objects in Python.
It covers:
- Slice assignment with different ranges (positive and negative indices)
- Deletion via empty assignment
- Extending bytearrays using slice assignment
- Self-referential assignment (assigning a bytearray... |
#!/usr/bin/python3
"""
Test suite for the Dockerbeat charm using Amulet.
This module provides integration tests for the Dockerbeat Juju charm,
verifying deployment, configuration, and basic functionality within
a real or simulated Juju environment. The tests use the Amulet library
to deploy the charm, interact with th... |
import re
from typing import Optional, List, Tuple, Union
"""
正则表达式学习示例:从基础到进阶
本代码系统性地演示了 Python 中 `re` 模块的常见用法,包括:
- 单个字符匹配
- 多字符重复匹配
- 字符串边界控制
- 分组与引用
- 邮箱、手机号等实际应用
"""
# ==================== 工具函数定义 ====================
def safe_match(pattern: str, text: str, flags: int = 0) -> Optional[re.Match]:
"""
安... |
"""
Gestión de Productos y Proveedores - Sistema de Base de Datos
Este módulo proporciona funciones para gestionar productos en una base de datos,
incluyendo operaciones como inserción, consulta, control de stock, compras, ventas y reservas.
Está diseñado para ser educativo, mostrando buenas prácticas en Python como:
... |
"""
Reddit Bot with PRAW - A modular, robust, and educational implementation.
This script implements a Reddit bot using PRAW (Python Reddit API Wrapper) that:
- Monitors subreddits for keywords.
- Replies to matching comments.
- Handles replies to its own comments.
- Uses environment variables for secure configuration... |
"""
String Reversal Program
This script prompts the user to enter their name and then displays the reversed version
of the input string using Python slicing. It includes input validation, error handling,
and follows best practices for readability and maintainability.
"""
def get_user_name() -> str:
"""
Promp... |
"""
olympic_medals_zoich.py
This script fetches Olympic medal data from a public API and generates an HTML file
displaying the top 10 countries by medal count. The output is saved as 'res.html'.
Features:
- Fetches real-time Olympic medal data from a REST API.
- Generates a clean, valid HTML table with UTF-8 encoding... |
"""
Análise de Financiamento Imobiliário
Este programa avalia a viabilidade de um financiamento imobiliário com base no valor do imóvel,
salário do comprador e tempo de financiamento. O empréstimo é aprovado se a prestação mensal
não ultrapassar 30% do salário do comprador.
Autor: Assistente de Programação
Data: 2025... |
"""
This script demonstrates how to manage and display a list of students
enrolled in a course (e.g., FRI - Faculty of Informatics).
It includes best practices such as:
- Using proper variable naming
- Iterating over lists safely
- Adding error handling
- Including type hints and documentation
- Making the code reusabl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.