text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
from typing import List
def read_int(prompt: str) -> int:
"""Read a valid integer from the user."""
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter a whole number.")
def counting_sort(values: List[int]) -> List[int]:
"""Return a s... | kai9987kai/Python-Examples | Counting-sort.py | .py | 56f77dadc46848a1 | 7.15 | 1 |
#!/usr/bin/env python3
"""
ftp_tool.py
List, upload, download, and manage files on FTP or explicit FTPS servers.
Examples:
python ftp_tool.py list ftp.example.com
python ftp_tool.py list ftp.example.com --user myuser
python ftp_tool.py download ftp.example.com /remote/report.pdf ./report.pdf
python ft... | kai9987kai/Python-Examples | FTP.py | .py | 31eeb9293d3a56d1 | 7.15 | 1 |
"""
Code to directly use in file to
create directory in home location
Note:- I Have used python package so if you want
to create in the main directory of your project use
pardir+"\\"+name in functions
All the folder operations are done on home
project directory.
"""
from shutil import copytree
from shutil import mov... | kai9987kai/Python-Examples | Google_Image_Downloader/create_dir.py | .py | fc44e67b211a7266 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Script Name : Google_News.py
Description : Fetches and displays news headlines from Google News RSS feeds
using only Python's standard library (no BS4 or lxml required!).
"""
import ssl
import sys
import urllib.request
import urllib.error
import xml.etree.ElementTre... | kai9987kai/Python-Examples | Google_News.py | .py | fd0dd99ac31ac11d | 7.15 | 1 |
import simplegui
import random
# Game settings
CARD_COUNT = 16
PAIR_COUNT = 8
CARD_WIDTH = 50
CARD_HEIGHT = 100
WIDTH = CARD_COUNT * CARD_WIDTH
HEIGHT = CARD_HEIGHT
cards = []
exposed = []
selected = []
turns = 0
game_complete = False
def update_label(message=None):
"""Refresh the score/status label."""
if ... | kai9987kai/Python-Examples | Memory_game.py | .py | cd909d9e2f66c6de | 7.15 | 1 |
from typing import List
def merge(left: List[int], right: List[int]) -> List[int]:
"""Merge two already-sorted lists into one sorted list."""
merged = []
i = j = 0
while i < len(left) and j < len(right):
# <= keeps the sort stable when values are equal.
if left[i] <= right[j]:
... | kai9987kai/Python-Examples | Merge-sort.py | .py | 7649a97479d34e57 | 7.15 | 1 |
"""
Advanced Multiplication Table Generator
"""
def get_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Please enter a valid number.")
def format_number(number):
"""Remove unnecessary .0 from whole numbers."""
retu... | kai9987kai/Python-Examples | MultiplicationTable.py | .py | cd860e77447d4771 | 7.15 | 1 |
#!/usr/bin/python3
"""
Script Name : Organise.py
Description : Organises files in a directory into folders by type (e.g. Video, Images, etc.).
"""
import sys
import shutil
from pathlib import Path
EXT_VIDEO_LIST = ['FLV', 'WMV', 'MOV', 'MP4', 'MPEG', '3GP', 'MKV', 'AVI']
EXT_IMAGE_LIST = ['JPG', 'JPEG', 'GIF',... | kai9987kai/Python-Examples | Organise.py | .py | 78200043626af29f | 7.15 | 1 |
# Pong Game — improved CodeSkulptor version
import simplegui
import random
# Canvas
WIDTH = 600
HEIGHT = 400
# Ball
BALL_RADIUS = 12
BALL_MAX_SPEED = 10
# Paddles
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
PADDLE_SPEED = 6
# Directions
LEFT = -1
RIGHT = 1
# Game ... | kai9987kai/Python-Examples | PONG_GAME.py | .py | 4ca5aacfe61b5469 | 7.15 | 1 |
"""
Advanced Palindrome Checker
Checks phrases while ignoring spaces, punctuation, case, and accents.
"""
from __future__ import annotations
import re
import unicodedata
from dataclasses import dataclass
SAMPLE_PHRASE = "A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!"
@dataclass
class Palindrom... | kai9987kai/Python-Examples | Palindrome_Checker.py | .py | 6e0858faa47c85d1 | 7.15 | 1 |
# Interactive Polyline Drawer - CodeSkulptor / SimpleGUI
import simplegui
# Canvas settings
WIDTH = 700
HEIGHT = 450
# Drawing state
polyline = []
mouse_pos = None
closed_shape = False
line_width = 3
# Colours
BACKGROUND = "Black"
LINE_COLOUR = "Aqua"
POINT_COLOUR = "Yellow"
PREVIEW_COLOUR = "Gray"
TEXT_COLOUR = "W... | kai9987kai/Python-Examples | Polyline.py | .py | 91446b55c2e8654b | 7.15 | 1 |
# Even Number Generator
def get_non_negative_integer(prompt):
"""Keep asking until the user enters a valid non-negative whole number."""
while True:
try:
value = int(input(prompt))
if value < 0:
print("Please enter 0 or a positive whole number.")
... | kai9987kai/Python-Examples | Print_List_of_Even_Numbers.py | .py | 9ac90aa9e55cf810 | 7.15 | 1 |
"""
Advanced Polynomial Sequence Solver
Supports constant, linear, and quadratic sequences.
Examples:
6 13 22 33
1, 4, 9, 16
3/2 3 9/2 6
0.5 2 4.5 8
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
from fractions import Fraction
from typing impo... | kai9987kai/Python-Examples | QuadraticCalc.py | .py | c247559aab256615 | 7.15 | 1 |
"""
Advanced Tic-Tac-Toe
Python 3 terminal edition
"""
import random
EMPTY = " "
PLAYER = "player"
COMPUTER = "computer"
def draw_board(board):
"""Display the board. Empty spaces show their move number."""
def cell(index):
return board[index] if board[index] != EMPTY else str(index + 1)
print("... | kai9987kai/Python-Examples | TicTacToe.py | .py | 62508895a76894f2 | 7.15 | 1 |
"""
Wikipedia Explorer
Modern Python 3 command-line Wikipedia search tool.
Created from an older Python 2 script and improved with:
- Safe input validation
- Search and random article modes
- Disambiguation handling
- Summary or full article display
- Optional article saving
- Configurable Wikipedia language
"""
from... | kai9987kai/Python-Examples | WikipediaModule.py | .py | 3abf196521f8eea7 | 7.15 | 1 |
# batch_file_rename.py
# Created: 6th August 2012
# Modified: June 2026
"""
This will batch rename a group of files in a given directory,
once you pass the current and new extensions.
"""
__author__ = 'Craig Richards'
__version__ = '2.0'
import os
import argparse
import sys
def batch_rename(work_d... | kai9987kai/Python-Examples | batch_file_rename.py | .py | 38106985f80d9189 | 7.15 | 1 |
from math import comb
def pascal_triangle(rows: int) -> list[list[int]]:
"""Return Pascal's triangle with the requested number of rows."""
if not isinstance(rows, int) or rows < 1:
raise ValueError("rows must be a positive integer.")
triangle = []
for row_index in range(rows):
row = ... | kai9987kai/Python-Examples | binary-coefficients.py | .py | cd78afea50f727be | 7.15 | 1 |
"""
Chaotic Behaviour Demonstrator
Uses the logistic map: x(n+1) = r * x(n) * (1 - x(n))
"""
def get_float(prompt, minimum=None, maximum=None):
"""Read and validate a floating-point number from the user."""
while True:
try:
value = float(input(prompt))
if minimum is not None an... | kai9987kai/Python-Examples | chaos.py | .py | e7c1dba5a3c06b20 | 7.15 | 1 |
import asyncio
import datetime as dt
import json
from pathlib import Path
from typing import Any, NamedTuple
import httpx
from dateutil.parser import parse
from httpx import HTTPError
from rich.console import Console
from rich.table import Table
console = Console()
class BuildRow(NamedTuple):
"""Store build dat... | browniebroke/netlify-builds | src/netlify_builds/cli.py | .py | 06f921a8d8df4b7d | 7.15 | 1 |
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import io
import logging
import os
from ruamel.yaml import YAML
import smtplib
from sls_api.endpoints.generics import FRONTEND_EXTERNAL_URL
logger = logging.getLogger("sls_api.email")
email_config_path = os.path.join("sls_api", "confi... | slsfi/digital_edition_api | sls_api/email.py | .py | 0f92be81977d3bb2 | 7 | 0 |
import datetime
from flask import Blueprint, jsonify, request
from flask_jwt_extended import create_access_token, create_refresh_token, get_jwt_identity, jwt_required
import logging
from sls_api import rate_limiter
from sls_api.email import send_address_verification_email, send_password_reset_email
from sls_api.endpoin... | slsfi/digital_edition_api | sls_api/endpoints/auth.py | .py | 30ae8b994b60b1cb | 7 | 0 |
from flask import Blueprint, jsonify, Response, request, send_file
import logging
import sqlalchemy
from werkzeug.security import safe_join
from sls_api.endpoints.generics import db_engine, get_project_config, reader_auth_required
songs = Blueprint('songs', __name__, url_prefix="/digitaledition")
logger = logging.get... | slsfi/digital_edition_api | sls_api/endpoints/songs.py | .py | 6125a97f90d512bf | 7 | 0 |
from flask import Blueprint, jsonify, request
import logging
import os
import sqlalchemy
import subprocess
from werkzeug.security import safe_join
from werkzeug.utils import secure_filename
from sls_api.endpoints.generics import ALLOWED_EXTENSIONS_FOR_FACSIMILE_UPLOAD, allowed_facsimile, db_engine, \
FACSIMILE_IMA... | slsfi/digital_edition_api | sls_api/endpoints/tools/facsimiles.py | .py | 3880dfd87c816ca3 | 7 | 0 |
from flask import Blueprint, jsonify, request
from sqlalchemy import select
from sls_api.endpoints.generics import cms_required, db_engine, get_table, int_or_none
group_tools = Blueprint("group_tools", __name__, url_prefix="/digitaledition")
@group_tools.route("/<project>/publication_groups/")
@cms_required()
def l... | slsfi/digital_edition_api | sls_api/endpoints/tools/groups.py | .py | 350f896a788fcb50 | 7 | 0 |
import logging
class WarningErrorFlagHandler(logging.Handler):
"""
A logging.Handler that flips boolean flags when warnings/errors occur.
Attaching this handler to a logger sets:
- had_warning: True if at least one WARNING was logged
(excludes ERROR/CRITICAL).
- had_error: True if at least ... | slsfi/digital_edition_api | sls_api/logging_handlers.py | .py | 8358e6a06c90c0b1 | 7 | 0 |
from collections import OrderedDict
import logging
import os
from typing import Any, List, Mapping, Optional
from urllib.parse import urlsplit, urlunsplit
logger = logging.getLogger("sls_api.security_headers")
def normalize_csp_frame_ancestor_source(source: str) -> str:
"""
Normalize absolute URL sources to ... | slsfi/digital_edition_api | sls_api/security_headers.py | .py | 7ffa461452a7d51e | 7 | 0 |
"""Test Terraform installation of new_account_trust_policy.
Verifies the Terraform configuration by:
- verifying the init/plan and apply are successful,
- verifying the Terraform output,
- verifying a "dry run" of the lambda is successful,
- executing the lambda to verify the libraries are installed.
"... | plus3it/terraform-aws-org-new-account-trust-policy | tests/test_terraform_install.py | .py | 3e79d5beec36fb9a | 7.74 | 2 |
from math import floor
from statistics import mean
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
def weighted_mean(values: List[Union[float, int]], weights: List[Union[int, float]] = []) -> Optional[float]:
"""
This will generate a mean value for the list of provided `values`, where eac... | ilfrich/python-basic-utils | pbu/datascience_util.py | .py | 04d372863908f7f7 | 7.24 | 2 |
from datetime import date, datetime, time
from typing import Optional, Union
from pytz import BaseTzInfo, timezone, utc
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
DATE_FORMAT = "%Y-%m-%d"
def to_timezone(localized_datetime: datetime, target_timezone: Union[BaseTzInfo, str]) -> datetime:
"""
Translates a localize... | ilfrich/python-basic-utils | pbu/date_time.py | .py | d222b12819139301 | 7.24 | 2 |
from typing import Any, Callable, Iterable, List, Optional
def default_options(default: dict = {}, override: dict = None, allow_unknown_keys: bool = True) -> dict:
"""
Combines the dictionaries provided as parameters into one, where keys in override will replace keys in default.
The inputs are not mutated... | ilfrich/python-basic-utils | pbu/default_options.py | .py | 1fad41ac864a172e | 7.24 | 2 |
import json
import os
from typing import List, Optional, Union
from pbu.default_options import default_options, not_none
def write_json(data: Union[dict, list], path: str):
"""
Writes an object to a json file. This function will take care of opening and closing the file.
:param data: a list of dictionary... | ilfrich/python-basic-utils | pbu/files.py | .py | f57289fb385d5819 | 7.24 | 2 |
class JSON(dict):
"""
Dictionary extension to allow using the "dot-notation" to traverse and manipulate dictionaries in the same fashion
as in Javascript, thus avoiding the square brackets and string key handling.
Usage example:
>>> from pbu import JSON
>>> my_obj = JSON({"initial": "content"... | ilfrich/python-basic-utils | pbu/json_wrapper.py | .py | 80e2ea675ec735d6 | 7.24 | 2 |
import os
import requests
import logging
import sys
import traceback
import inspect
from logging import handlers
# store log files in this folder, if configured
CONFIG_KEY_LOG_FOLDER = "PBU_LOG_FOLDER"
# send log records to this server, if configured
CONFIG_KEY_LOG_SERVER = "PBU_LOG_SERVER"
CONFIG_KEY_LOG_SERVER_AUTH... | ilfrich/python-basic-utils | pbu/logger.py | .py | 295e5553ac5e437b | 7.24 | 2 |
import os
import sys
from abc import ABC, abstractmethod
from math import ceil
from random import randint
from time import sleep
from typing import Any, List, Optional
from pbu.debug_object import DebugObject, get_coverage_string
from pbu.files import read_json, write_json
from pbu.logger import Logger
from pbu.perfor... | ilfrich/python-basic-utils | pbu/parallel_exec.py | .py | e5100ee2d52df56e | 7.24 | 2 |
from collections import defaultdict
import yaml
import os
def parse_preserving_duplicates(src):
# We deliberately define a fresh class inside the function,
# because add_constructor is a class method and we don't want to
# mutate pyyaml classes.
class PreserveDuplicatesLoader(yaml.loader.Loader):
... | kazstat/sdg-data-kazstat | scripts/find_duplicate_translations.py | .py | 5f87929f972cb19c | 7 | 0 |
#!/usr/bin/python3
import argparse
import logging
import tkinter as tk
from . import start_logging
from .app import APP_DESC, ControlFrame
logger = logging.getLogger(__loader__.name)
CLI_APP_EPILOG = """\
Pycryptor is licensed under MIT license.
"""
def start_logging_with_flags():
"""Add logging capability wit... | arunanshub/pycryptor | pycryptor/__main__.py | .py | a1c33240cf2fc865 | 7.35 | 4 |
import itertools
import logging
import os
from concurrent import futures
from functools import partial
from pyflocker.ciphers import AES, exc
from pyflocker.ciphers.backends import Backends
from pyflocker.locker import locker
SUCCESS = 1 << 1
FAILURE = 1 << 2
INVALID = 1 << 3
FILE_NOT_FOUND = 1 << 4
FILE_EXISTS = 1 <... | arunanshub/pycryptor | pycryptor/parallel.py | .py | 7931c4e37da248e6 | 7.35 | 4 |
"""Context object."""
from __future__ import annotations
from functools import cached_property
from typing import TYPE_CHECKING
from rich.console import Console
from .constants import CONFIG_DIR, SYSTEM_INFO
if TYPE_CHECKING:
from pathlib import Path
from f_lib import SystemInfo
class Context:
"""f-... | finleyfamily/f-cli | f_cli/context.py | .py | 46943a28758c367a | 7.15 | 1 |
"""Pytest configuration, fixtures, and plugins."""
from __future__ import annotations
import os
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from .factories import cli_runner_factory
if TYPE_CHECKING:
from collections.abc import Iterator
from _pytest.fixtures import SubRequest
... | finleyfamily/f-cli | tests/conftest.py | .py | b376b3a93ee8ef91 | 7.65 | 1 |
"""Simple ELO ranking implementation."""
class EloRank:
"""Simple ELO ranking system."""
def __init__(self, k_factor: int = 32):
"""Initialize ELO ranking system.
Args:
k_factor: K-factor for ELO calculation (default: 32)
"""
self.k_factor = k_factor
def get_... | asmundg/shopr | shopr/elo.py | .py | b2986fc69c5509d8 | 7 | 0 |
"""Main shopr application logic."""
import asyncio
import json
import logging
import re
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any
import snowballstemmer
from .elo import EloRank
from .trello import (
Checklist,
ChecklistItem,
TrelloClient,
)
# Config... | asmundg/shopr | shopr/main.py | .py | 5ce8c9c955bba8d2 | 7 | 0 |
"""Trello API client for shopr."""
import logging
from typing import Any
import httpx
from pydantic import BaseModel, ConfigDict
logger = logging.getLogger("shopr:trello")
ROOT = "https://api.trello.com"
class Card(BaseModel):
"""Trello card representation.
Only includes fields actually used by the appl... | asmundg/shopr | shopr/trello.py | .py | f09f76cfc2bbf885 | 7 | 0 |
"""
autovision CLI — scrape, train, predict.
Examples
--------
# Download images for 3 categories and train a classifier
python cli.py train "golden retriever" "siberian husky" "german shepherd"
# Same but 200 images per class, 15 epochs, ResNet-18 backbone
python cli.py train cat dog --n-images 200 -... | oney-erge/image-classifier-web-search | cli.py | .py | a34d448538bd99dd | 7 | 0 |
from unittest.mock import patch
from autovision.scraper import ImageScraper
def _patched_scrape(scraper, query, n_images, ddgs_results=None):
"""Helper: run search_and_download with DDGS mocked out."""
with patch("autovision.scraper.DDGS") as mock_ddgs:
mock_ddgs.return_value.images.return_value = dd... | oney-erge/image-classifier-web-search | tests/test_scraper.py | .py | 52aee8dcb101dfd2 | 7.5 | 0 |
"""Retrieve films from OMDb and check which films are on RYM."""
import os
import re
import time
from contextlib import suppress
from difflib import SequenceMatcher
import omdb
import pandas as pd
from bs4 import BeautifulSoup, SoupStrainer
from selenium import webdriver
from selenium.webdriver.chrome.options import ... | pkratz22/omdb_rym | omdb_rym/omdb_rym.py | .py | 70c26ba1816b36ec | 7 | 0 |
"""Test omdb_rym functions.
Classes:
TestOmdbRym
Functions:
test_get_imdb_string(self)
test_get_movie(self)
test_add_movies(self)
"""
import unittest
import omdb_rym
class TestOmdbRym(unittest.TestCase):
"""Test cases for omdb_rym."""
def test_get_imdb_string(self):
"""Test gett... | pkratz22/omdb_rym | omdb_rym/tests.py | .py | d9792d1970a87a12 | 7.5 | 0 |
# Use of this source code is governed by the MIT license.
__license__ = "MIT"
from collections import defaultdict
import itertools
import sys
from bs4.element import (
CharsetMetaAttributeValue,
ContentMetaAttributeValue,
Stylesheet,
Script,
TemplateString,
nonwhitespace_re
)
__all__ = [
'... | pkratz22/omdb_rym | venv/lib/python3.8/site-packages/bs4/builder/__init__.py | .py | 749732af1e82740b | 7 | 0 |
# Use of this source code is governed by the MIT license.
__license__ = "MIT"
__all__ = [
'LXMLTreeBuilderForXML',
'LXMLTreeBuilder',
]
try:
from collections.abc import Callable # Python 3.6
except ImportError as e:
from collections import Callable
from io import BytesIO
from io import StringIO
f... | pkratz22/omdb_rym | venv/lib/python3.8/site-packages/bs4/builder/_lxml.py | .py | 7b8c3dd51662dcd2 | 7 | 0 |
"""Diagnostic functions, mainly for use when doing tech support."""
# Use of this source code is governed by the MIT license.
__license__ = "MIT"
import cProfile
from io import StringIO
from html.parser import HTMLParser
import bs4
from bs4 import BeautifulSoup, __version__
from bs4.builder import builder_registry
i... | pkratz22/omdb_rym | venv/lib/python3.8/site-packages/bs4/diagnose.py | .py | 58ecf2b424e4bea8 | 7 | 0 |
from bs4.dammit import EntitySubstitution
class Formatter(EntitySubstitution):
"""Describes a strategy to use when outputting a parse tree to a string.
Some parts of this strategy come from the distinction between
HTML4, HTML5, and XML. Others are configurable by the user.
Formatters are passed in as... | pkratz22/omdb_rym | venv/lib/python3.8/site-packages/bs4/formatter.py | .py | 59acafd5de9f51cf | 7 | 0 |
"""Tests of the builder registry."""
import unittest
import warnings
from bs4 import BeautifulSoup
from bs4.builder import (
builder_registry as registry,
HTMLParserTreeBuilder,
TreeBuilderRegistry,
)
try:
from bs4.builder import HTML5TreeBuilder
HTML5LIB_PRESENT = True
except ImportError:
HT... | pkratz22/omdb_rym | venv/lib/python3.8/site-packages/bs4/tests/test_builder_registry.py | .py | a6595f46902b87d4 | 7.5 | 0 |
"""Tests to ensure that the html5lib tree builder generates good trees."""
import warnings
try:
from bs4.builder import HTML5TreeBuilder
HTML5LIB_PRESENT = True
except ImportError as e:
HTML5LIB_PRESENT = False
from bs4.element import SoupStrainer
from bs4.testing import (
HTML5TreeBuilderSmokeTest,
... | pkratz22/omdb_rym | venv/lib/python3.8/site-packages/bs4/tests/test_html5lib.py | .py | 7969cb1877a4fd13 | 7.5 | 0 |
"""Tests to ensure that the html.parser tree builder generates good
trees."""
from pdb import set_trace
import pickle
from bs4.testing import SoupTest, HTMLTreeBuilderSmokeTest
from bs4.builder import HTMLParserTreeBuilder
from bs4.builder._htmlparser import BeautifulSoupHTMLParser
class HTMLParserTreeBuilderSmokeTes... | pkratz22/omdb_rym | venv/lib/python3.8/site-packages/bs4/tests/test_htmlparser.py | .py | df6f785ef15b5957 | 7.5 | 0 |
"""Tests to ensure that the lxml tree builder generates good trees."""
import re
import warnings
try:
import lxml.etree
LXML_PRESENT = True
LXML_VERSION = lxml.etree.LXML_VERSION
except ImportError as e:
LXML_PRESENT = False
LXML_VERSION = (0,)
if LXML_PRESENT:
from bs4.builder import LXMLTre... | pkratz22/omdb_rym | venv/lib/python3.8/site-packages/bs4/tests/test_lxml.py | .py | c49afc783aed1d26 | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""
certifi.py
~~~~~~~~~~
This module returns the installation location of cacert.pem or its contents.
"""
import os
try:
from importlib.resources import path as get_path, read_text
_CACERT_CTX = None
_CACERT_PATH = None
def where():
# This is slightly terrible, but ... | pkratz22/omdb_rym | venv/lib/python3.8/site-packages/certifi/core.py | .py | 574bb2c4a398773e | 7 | 0 |
from __future__ import annotations
from typing import TYPE_CHECKING
from django import forms
from django.utils.translation import gettext_lazy as _
if TYPE_CHECKING:
from django.contrib.auth.models import AbstractUser
from django.http import HttpRequest
# Django-Allauth further inherits from this form, and... | kitware-resonant/django-resonant-utils | resonant_utils/allauth.py | .py | 4f985535a0f88dd7 | 7.24 | 2 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, TypeVar
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Manager, Model, QuerySet
from django.utils.translation import gettext_lazy as _
if TYPE_CHECKING:
from collections.abc imp... | kitware-resonant/django-resonant-utils | resonant_utils/db.py | .py | 6a220b39b0d47af9 | 7.24 | 2 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, cast
from unittest.mock import Mock
from django.http import HttpRequest, QueryDict
from ninja.security.http import HttpAuthBase
from ninja.testing import TestClient as UpstreamTestClient
from oauth2_provider.oauth2_backends import get_oauthlib_... | kitware-resonant/django-resonant-utils | resonant_utils/ninja.py | .py | 9e0740d9e853fc38 | 7.24 | 2 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from rest_framework.pagination import LimitOffsetPagination
if TYPE_CHECKING:
from rest_framework.request import Request
from rest_framework.response import Response
class BoundedLimitOffsetPagination(LimitOffsetPagination):
"""
... | kitware-resonant/django-resonant-utils | resonant_utils/rest_framework.py | .py | 475e006600f3b4b0 | 7.24 | 2 |
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from django import template
if TYPE_CHECKING:
from collections.abc import Mapping
register = template.Library()
@register.filter
def get_item[Key, Value](value: Mapping[Key, Value], arg: Key) -> Value | None:
"""
Retr... | kitware-resonant/django-resonant-utils | resonant_utils/templatetags/resonant_utils.py | .py | 71df0bf82df4fe91 | 7.24 | 2 |
#!/usr/bin/env python3
import logging
import sys
import struct
import datetime
from os.path import dirname, realpath
sys.path.append(dirname(dirname(dirname(realpath(__file__)))))
from logger.utils.das_record import DASRecord # noqa: E402
from logger.transforms.transform import Transform # noqa: E402
class ParseK... | OceanDataTools/openrvdas_sikuliaq | logger/transforms/parse_kongsberg_kmb_transform.py | .py | b6d93a09fbad0d14 | 7 | 0 |
#!/usr/bin/env python3
"""
Scans active Coriolix sensors via UDP to discover their true 'data_id'.
Generates a YAML mapping file (API_ID -> DATA_ID) to resolve naming mismatches.
Usage:
./generate_id_mapping.py > sensor_map.yaml
# Or import in other scripts:
# from generate_id_mapping import SensorIDMappe... | OceanDataTools/openrvdas_sikuliaq | utils/generate_id_mapping.py | .py | 92d8e8e36de4d495 | 7 | 0 |
from collections.abc import Callable
from typing import Any
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from ninja.security import HttpBearer, django_auth
from oauth2_provider.oauth2_backends import get_oauthlib_core
from isic.core.permissions import SessionAuthStaffUser
ACC... | ImageMarkup/isic | isic/auth.py | .py | 1d481b780a405e91 | 7.39 | 5 |
import os
import secrets
import sys
from django.conf import settings
from django.contrib.auth.models import Group, User
from django.core.cache import cache
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.test.client import Client
from playwright.sync_api... | ImageMarkup/isic | isic/conftest.py | .py | 07d151ee181481a7 | 7.89 | 5 |
from typing import Any
from django.conf import settings
from django.contrib import messages
from django.core.cache import cache
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import transaction
from django.db.models import Case, Max, Q, Value, When
from django.http.request i... | ImageMarkup/isic | isic/core/api/image.py | .py | c4b08b5b4be56650 | 7.39 | 5 |
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import random
import uuid
import os
# The Dockerfile copies the built React app into ./static (next to this
# file), so Flask serves it directly. No separate frontend server/nginx
# needed - one container, one process.
app = Fla... | mallorysmith64/mine-express | backend/app.py | .py | 502d3cbc6493efcd | 7.15 | 1 |
"""Advanced / scientific calculator button pad."""
from __future__ import annotations
from tkinter import Button, Frame
from typing import Callable
from calculator.theme import BUTTON_STYLES, COLORS, FONTS
# Rows of (label, key, style[, columnspan]). Default colspan is 1.
_ADVANCED_LAYOUT: list[list[tuple]] = [
... | awongCM/py-gui-calculator | calculator/advanced_pad.py | .py | bf48db831c2e1edf | 7 | 0 |
"""Basic calculator button pad."""
from __future__ import annotations
from tkinter import Button, Frame
from typing import Callable
from calculator.theme import BUTTON_STYLES, COLORS, FONTS
# (label, key, style, columnspan)
_BASIC_LAYOUT: list[list[tuple[str, str, str, int]]] = [
[("C", "C", "clear", 1), ("⌫",... | awongCM/py-gui-calculator | calculator/basic_pad.py | .py | bc6a563b5d359338 | 7 | 0 |
from __future__ import annotations
from typing import TYPE_CHECKING
from allauth.mfa.recovery_codes.internal import auth as recovery_codes_auth
from allauth.mfa.totp.internal import auth as totp_auth
from allauth.mfa.webauthn.internal.auth import WebAuthn
from django.urls import reverse
from freezegun import freeze_t... | kitware-resonant/django-auth-style | tests/test_render.py | .py | 19a98ffe38b6ddb3 | 7.89 | 5 |
#!/usr/bin/env python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | DeviationLabs/homely-vibes | BimpopAI/aiy_hat/aiy_runner.py | .py | 857f70d36c3ff8cf | 7.3 | 3 |
#!/usr/bin/env python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | DeviationLabs/homely-vibes | BimpopAI/aiy_hat/auth_helpers.py | .py | 241bea4ad01f8914 | 7.3 | 3 |
from typing import List, Optional, Dict
from fastapi import HTTPException, Header
from openai import OpenAI
import logging
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
import os
from pinecone import PodSpec, Pinecone
from langchain_pinecone import Pine... | DeviationLabs/homely-vibes | BimpopAI/app/utils.py | .py | dd54f778d46503f0 | 7.3 | 3 |
#!/usr/bin/env python3
"""
Script to append GPX files that begin with numbers in numeric order.
Reads numbered GPX files (1_*, 2_*, etc.) and combines them into a single output file.
Uses gpxpy library for proper GPX handling.
"""
import os
import re
from pathlib import Path
from typing import List, Tuple
import gpxpy... | DeviationLabs/homely-vibes | GPXParser/append_numbered_files.py | .py | 4076eea6ee69c3fe | 7.3 | 3 |
#!/usr/bin/env python3
"""
External IP Address Reporter
Fetches and reports the current external IP address via email and pushover notifications.
Useful for monitoring IP changes when using dynamic IP addresses.
"""
import sys
import requests
from typing import Tuple
from lib.config import get_config
from lib.MyPusho... | DeviationLabs/homely-vibes | NetworkCheck/external_ip_reporter.py | .py | 6e1f83fdd633e97d | 7.3 | 3 |
#!/usr/bin/env python3
"""
Network Speed Test Utility
Performs network speed tests using the speedtest-cli tool and reports results
via email and pushover notifications. Supports retry logic for unreliable connections.
"""
import argparse
import json
import shutil
import subprocess
import sys
import time
from typing ... | DeviationLabs/homely-vibes | NetworkCheck/test_uplink.py | .py | 0ceb292fe4656bd4 | 7.8 | 3 |
#!/usr/bin/env python3
"""
Hardware specs gatherer for remote Linux hosts (e.g. Raspberry Pi).
SSHes into a host and collects model, SoC, CPU, memory, storage, network,
OS, firmware, and temperature specs, then prints a pretty two-column table.
Prompts for a sudo password only if the remote sudo requires one
(tries p... | DeviationLabs/homely-vibes | NodeCheck/check_hw_specs.py | .py | c730d235d9f7869c | 7.8 | 3 |
#!/usr/bin/env python3
import argparse
import sys
import time
from typing import Dict, List, Set
from lib.config import NodeType, get_config
from lib.logger import SystemLogger
from lib.MyPushover import Pushover
from NodeCheck.nodes import ArpNode, FoscamNode, GenericNode, SomfyMyLinkNode, WindowsNode
_NODE_CLASS_BY_... | DeviationLabs/homely-vibes | NodeCheck/heartbeat_nodes.py | .py | ddcefffb73a05556 | 7.3 | 3 |
#!/usr/bin/env python3
from typing import List, TYPE_CHECKING
import argparse
import sys
import time
from lib.config import get_config
from lib.logger import SystemLogger
from lib import Mailer
from lib.MyPushover import Pushover
from NodeCheck.nodes import GenericNode, FoscamNode, WindowsNode
if TYPE_CHECKING:
pa... | DeviationLabs/homely-vibes | NodeCheck/manage_nodes.py | .py | d2e5123a35c303c9 | 7.3 | 3 |
#!/usr/bin/env python3
import json
import re
import socket
import subprocess
import time
from lib import NetHelpers
from lib.config import NodeConfig
from lib.logger import SystemLogger
logger = SystemLogger.get_logger(__name__)
# 3 consecutive packet losses before a node is considered down. Matches the
# Nagios-styl... | DeviationLabs/homely-vibes | NodeCheck/nodes.py | .py | fd65e20067223d09 | 7.3 | 3 |
#!/usr/bin/env python3
"""Tests for HeartbeatMonitor flap-suppression logic."""
from typing import List, cast
from unittest.mock import MagicMock
import pytest
from NodeCheck.heartbeat_nodes import HeartbeatMonitor
from NodeCheck.nodes import GenericNode
def _fake_node(name: str, healthy_sequence: List[bool]) -> M... | DeviationLabs/homely-vibes | NodeCheck/test_heartbeat_nodes.py | .py | 0f41594f0af74b22 | 7.8 | 3 |
"""Alert rule model, config loader, and shared Pushover formatting for
RachioFlume usage alerts.
This module also owns two helpers used by both the controller-zone path
(alert_engine) and the hose-timer path (hose_timer_processor):
- `compact_zone_label` — drops the descriptive tail from a raw valve/zone
name so dis... | DeviationLabs/homely-vibes | RachioFlume/alert_rules.py | .py | 1c6a8c9c97a22088 | 7.3 | 3 |
"""Data collection service that polls Rachio and Flume APIs."""
import asyncio
import json
from datetime import datetime, timedelta
from typing import Optional, Dict, Any, List
from RachioFlume.alert_engine import CONTROLLER_STATUS_KEY, AlertEngine
from RachioFlume.hose_timer_processor import HoseTimerProcessor
from ... | DeviationLabs/homely-vibes | RachioFlume/collector.py | .py | b230174f824f8789 | 7.3 | 3 |
"""Rachio Smart Hose Timer client (cloud-rest.rach.io/valve/*).
The hose-timer API is a separate service from the controller API
(api.rach.io/1/public/device/*) but accepts the same Bearer api_key.
Unlike the controller API, there is NO history endpoint — historical runs
must be synthesized from state-transition polli... | DeviationLabs/homely-vibes | RachioFlume/rachio_hose_client.py | .py | fa938040169e1272 | 7.3 | 3 |
"""Weekly reporting system for water tracking data."""
import json
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta
from typing import Dict, Any, List
from pathlib import Path
from RachioFlume.alert_rules import compact_zone_label, load_zone_thresholds_from_config
from RachioFlume.da... | DeviationLabs/homely-vibes | RachioFlume/reporter.py | .py | 086a7edcdb50fea3 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
import math
import tkinter as tk
from apps.common.instruments.gauge_config import GaugeConfig
from apps.common.instruments.gauge_style import GaugeStyle
from apps.common.instruments.instrument_panel import InstrumentPanel
from messaging.con... | markisrt4/OpenRoadCode | apps/automotive_dashboard/automotive_dashboard_window.py | .py | a3824d70c656d9d7 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Standalone graphical consumer of public vehicle telemetry."""
from __future__ import annotations
import argparse
import tkinter as tk
from apps.automotive_dashboard.automotive_dashboard_window import (
AutomotiveDashboardWindow,
)
... | markisrt4/OpenRoadCode | apps/automotive_dashboard/main.py | .py | f12addb550f13ed2 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Standalone demo for VehicleGaugePanel without an OBD-II connection."""
from __future__ import annotations
import math
import signal
import tkinter as tk
from datetime import datetime
from types import SimpleNamespace
from frontends.tk.... | markisrt4/OpenRoadCode | apps/automotive_dashboard/vehicle_gauge_demo.py | .py | 308b94a8a4724d28 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Curses shell, static routes, and home menu for Car TUI."""
import curses
from apps.carTui.car_tui_dependencies import CarTuiDependencies
from apps.carTui.screens import NavigationScreen, RadioScreen, VehicleScreen
from apps.carTui.unit_... | markisrt4/OpenRoadCode | apps/carTui/car_tui.py | .py | c64fd10c86bc745e | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Owned runtime dependencies for the Car TUI application."""
from dataclasses import dataclass
from apps.carTui.radio_catalog import CarTuiRadio
from common.telemetry.navigation_bus_state import NavigationBusState
from common.telemetry.ve... | markisrt4/OpenRoadCode | apps/carTui/car_tui_dependencies.py | .py | bd035192db4980c1 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Command-line bootstrap for the OpenRoadCode Car TUI."""
from __future__ import annotations
import argparse
import curses
import os
from pathlib import Path
from apps.carTui.car_tui import CarTui
from apps.carTui.car_tui_dependencies im... | markisrt4/OpenRoadCode | apps/carTui/main.py | .py | 97f2cdca3d609c8f | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Build Car TUI radio controllers from shared runtime configuration."""
from dataclasses import dataclass
from config.runtime_config import RuntimeConfig
from config.radio_config_manager import load_radio_config
from controllers.radio imp... | markisrt4/OpenRoadCode | apps/carTui/radio_catalog.py | .py | 8e650498ea3f44e6 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Navigation and off-road destination for Car TUI."""
from apps.carTui.unit_preferences import CarTuiUnitPreferences
from common.telemetry.navigation_bus_state import NavigationBusState
from frontends.tui.automotive import NavigationDashbo... | markisrt4/OpenRoadCode | apps/carTui/screens/navigation_screen.py | .py | 8907e20c9f354468 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Message-bus vehicle telemetry destination for Car TUI."""
from apps.carTui.unit_preferences import CarTuiUnitPreferences
from common.telemetry.vehicle_bus_state import VehicleBusState
from frontends.tui.automotive import VehicleDashboard... | markisrt4/OpenRoadCode | apps/carTui/screens/vehicle_screen.py | .py | 62c373627e22daa7 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Mutable presentation preferences owned by the Car TUI."""
from dataclasses import dataclass
from common.units import UnitSystem
@dataclass(slots=True)
class CarTuiUnitPreferences:
"""Hold the currently selected presentation unit s... | markisrt4/OpenRoadCode | apps/carTui/unit_preferences.py | .py | fa8de30ec13f345f | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Present navigation position bus messages in the Car UI shell."""
from __future__ import annotations
import math
from collections.abc import Callable
from messaging.contracts.navigation import PositionStateMessage
class BusPositionPre... | markisrt4/OpenRoadCode | apps/carUi/bus_position_presenter.py | .py | 90ee06055fea556f | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Dependencies required to assemble the Car UI frontend."""
from __future__ import annotations
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
import logging
from apps.carUi.runtime.car_ui_runtime ... | markisrt4/OpenRoadCode | apps/carUi/car_ui_dependencies.py | .py | 2cfcd9484c09346c | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Tk frontend entry point for the Car UI application."""
from __future__ import annotations
import os
import logging
import threading
import tkinter as tk
from collections.abc import Callable
from pathlib import Path
from apps.carUi.car_... | markisrt4/OpenRoadCode | apps/carUi/car_ui_frontend.py | .py | fdf0bd7aa4b65120 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Runtime lifecycle coordination for the Car UI."""
from __future__ import annotations
from apps.carUi.runtime.car_ui_input_runtime import CarUiInputRuntime
from messaging.message_dispatcher import MessageDispatcher
class CarUiLifecycle... | markisrt4/OpenRoadCode | apps/carUi/car_ui_lifecycle.py | .py | 6cf1f282bdb68feb | 7.3 | 3 |
# SPDX-FileCopyrightText: 2026 Mark G. Russell
# SPDX-License-Identifier: MIT
"""Application route registry for Car UI navigation destinations."""
from __future__ import annotations
from collections.abc import Callable
class CarUiRouter:
"""Route Car UI destination keys to registered screen actions."""
de... | markisrt4/OpenRoadCode | apps/carUi/car_ui_router.py | .py | c85126d21a282cb0 | 7.3 | 3 |
# pyright: reportPrivateUsage=false
# pylint: disable=protected-access,super-init-not-called
# ruff: noqa: ANN401, SLF001
"""Tests for Model Target Web API detail helpers."""
import re
from typing import Any
import pytest
import requests
from selenium.webdriver.remote.webdriver import WebDriver
import vws_web_tools
... | VWS-Python/vws-web-tools | tests/test_model_target_web_api_details.py | .py | 82c29c07d41377a2 | 7.5 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.