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
"""Script to exercise cysox object lifecycles for macOS leaks tool. Run with: leaks --atExit -- python tests/check_leaks.py """ import gc import os import tempfile from cysox import sox WAV = os.path.join(os.path.dirname(__file__), "data", "s00.wav") def exercise_signal_info(n=500): """Create/destroy SignalInf...
shakfu/cysox
tests/check_leaks.py
.py
6a7d922377988671
7.65
1
#!/usr/bin/env python3 """ Python equivalent of tests/examples/example3.c This script replicates the functionality of the C example: - On an audio-capable system, plays an audio file starting 10 seconds in - Copes with sample-rate and channel changes if necessary since it's common for audio drivers to support a subs...
shakfu/cysox
tests/examples/example3.py
.py
459a7b70b356c38f
7.65
1
"""Tests for AudioHit-ported features: auto_trim, split_by_silence, pitch_scale, batch.""" import shutil from pathlib import Path import pytest import cysox from cysox import fx class TestSilenceEffect: """Tests for the Silence effect class.""" def test_silence_default_args(self): """Silence effec...
shakfu/cysox
tests/test_audiohit_features.py
.py
95d524abf8c1adb7
7.65
1
"""Tests for buffer protocol support in Format class""" import pytest import array from cysox import sox @pytest.fixture(autouse=True) def initialize_sox(): """Initialize SoX before each test.""" sox.init() yield sox.quit() def test_read_buffer(): """Test Format.read_buffer() returns a memoryvie...
shakfu/cysox
tests/test_buffer_protocol.py
.py
feb522978eb2803a
7.65
1
"""Edge case tests for cysox. Tests unusual inputs, boundary conditions, and error handling paths. """ import os import struct import tempfile import pytest import cysox # For auto-init from cysox import sox class TestZeroLengthFiles: """Test handling of zero-length and minimal audio files.""" def test_z...
shakfu/cysox
tests/test_edge_cases.py
.py
23f490a0171e2eb6
7.65
1
"""Negative test cases for error handling validation""" import pytest import tempfile import os from cysox import sox @pytest.fixture(autouse=True, scope="session") def initialize_sox(): """Initialize SoX once for the entire test session. Uses session scope to avoid repeated init/quit cycles, which can c...
shakfu/cysox
tests/test_error_handling.py
.py
41942b863ca1032f
7.65
1
"""Tests for example0: Basic effects chain Port of tests/examples/example0.c """ import pytest import tempfile import os from cysox import sox @pytest.fixture(autouse=True) def initialize_sox(): """Initialize SoX before each test.""" sox.init() yield sox.quit() def test_example0_basic_effects_chain(...
shakfu/cysox
tests/test_example0.py
.py
00824d7573ff83f9
7.65
1
"""Tests for example1: Apply vol & flanger effects Port of tests/examples/example1.c """ import pytest import tempfile import os from cysox import sox @pytest.fixture(autouse=True) def initialize_sox(): """Initialize SoX before each test.""" sox.init() yield sox.quit() def test_example1_vol_and_flan...
shakfu/cysox
tests/test_example1.py
.py
780d4eaeb840a13e
7.65
1
"""Tests for example2: Display waveform visualization Port of tests/examples/example2.c """ import pytest from cysox import sox @pytest.fixture(autouse=True) def initialize_sox(): """Initialize SoX before each test.""" sox.init() yield sox.quit() def test_example2_waveform_display(): """Test rea...
shakfu/cysox
tests/test_example2.py
.py
e4894346064968b1
7.65
1
"""Tests for example4: Concatenate audio files Port of tests/examples/example4.c """ import pytest import tempfile import os from cysox import sox @pytest.fixture(autouse=True) def initialize_sox(): """Initialize SoX before each test.""" sox.init() yield sox.quit() def test_example4_concatenate_file...
shakfu/cysox
tests/test_example4.py
.py
a57da4daf732b75a
7.65
1
"""Tests for example5: Memory-based I/O Port of tests/examples/example5.c """ import pytest import tempfile import os from cysox import sox @pytest.fixture(autouse=True) def initialize_sox(): """Initialize SoX before each test.""" sox.init() yield sox.quit() @pytest.mark.skip(reason="Memory I/O (mem...
shakfu/cysox
tests/test_example5.py
.py
f2d119ff23fca251
7.65
1
"""Content-level verification for effects. The other fx test modules assert that ``convert()`` produced a file. That cannot distinguish a working effect from one whose arguments libsox refused, because a refused effect still yields a valid output file. These tests measure what is actually in the output and assert a di...
shakfu/cysox
tests/test_fx_audio_content.py
.py
d12dd08142efc3ce
7.65
1
"""Tests for the high-level cysox API.""" import pytest import cysox from cysox import fx class TestInfo: """Tests for cysox.info().""" def test_info_returns_audio_info(self, test_wav_str): """info() returns an AudioInfo object with dict-style access.""" info = cysox.info(test_wav_str) ...
shakfu/cysox
tests/test_high_level_api.py
.py
b2a7a1a2b3eeffd5
7.65
1
"""Tests for onset detection module.""" import os import pytest from pathlib import Path import cysox from cysox import onset # Test data path TEST_DATA = Path(__file__).parent / "data" AMEN_WAV = TEST_DATA / "amen.wav" class TestOnsetDetection: """Test onset detection functionality.""" @pytest.fixture ...
shakfu/cysox
tests/test_onset.py
.py
d5c2c2fba7e7659b
7.65
1
"""Test slice and stutter outputs for examination. Output files are preserved in build/test_output/slice_outputs/ """ import pytest from pathlib import Path import cysox from cysox import fx @pytest.fixture def amen_wav(): """Path to amen break test file.""" return "tests/data/amen.wav" @pytest.fixture de...
shakfu/cysox
tests/test_slice_outputs.py
.py
9f257ff465060a82
7.65
1
from cysox import sox def test_get_effects_globals(): """Test get_effects_globals function""" globals = sox.get_effects_globals() assert isinstance(globals, dict) assert "plot" in globals def test_find_effect(): """Test find_effect function""" # Test finding a known effect effect_handler...
shakfu/cysox
tests/test_sox_effects.py
.py
775fc092cab8fc00
7.65
1
from cysox import sox # Test FileInfo class def test_file_info_creation(): """Test FileInfo creation and properties Note: buf parameter is ignored for safety (read-only property). FileInfo is primarily for internal use by libsox. """ test_data = b"test data" file_info = sox.FileInfo(buf=test_...
shakfu/cysox
tests/test_sox_file.py
.py
d36e00a6c12f3cfb
7.65
1
#!/usr/bin/env python3 """Generate today's English reading comprehension quiz using Google Gen AI SDK. Reads from environment: QUIZ_TODAY - today's date string (YYYYMMDD) GOOGLE_CLOUD_PROJECT - GCP project ID GOOGLE_CLOUD_LOCATION - GCP region (default: us-central1) GEMINI_MODEL - ...
kotaoue/EnglishLog
scripts/daily_quiz/generate_quiz.py
.py
d934be65382d9b9d
7.15
1
#!/usr/bin/env python3 """Generate an SVG image showing yesterday's English quiz scoring result. Reads from environment variables (optional): SCORING_DATE - date string of the scored workbook (YYYYMMDD) SCORING_SCORE - score in X/5 format (e.g. 3/5) When the environment variables are absent the script auto-detec...
kotaoue/EnglishLog
scripts/generate_svg/generate_svg.py
.py
f7117b2f625fc4e8
7.15
1
import copy import logging import ninja.errors from django.conf import settings from django.http import HttpRequest, HttpResponse from ninja import Router, Schema from ninja.pagination import paginate from ninja.security import HttpBearer from api.schemas import ( ATVDocumentResponse, DocumentStatusRequest, ...
City-of-Helsinki/pysakoinnin-sahk-asiointi
api/api.py
.py
26266352806a3838
7
0
import logging from datetime import datetime, timezone from resilient_logger.sources import ResilientLogSource def _now() -> datetime: """Returns the current time in UTC timezone.""" return datetime.now(tz=timezone.utc) def _iso8601_date(time: datetime) -> str: """Formats the timestamp in ISO-8601 form...
City-of-Helsinki/pysakoinnin-sahk-asiointi
mail_service/audit_log.py
.py
19bb31b2c7b0a5cf
7
0
import logging from datetime import timedelta import sentry_sdk from django.conf import settings from django.core.management.base import BaseCommand from django.utils import timezone from mailer.models import Message logger = logging.getLogger(__name__) def get_working_days_ago(days: int) -> timezone.datetime: ...
City-of-Helsinki/pysakoinnin-sahk-asiointi
mail_service/management/commands/check_stale_messages.py
.py
ba76ddacf7297dae
7
0
import os import sys import platform import distutils.util from setuptools import setup, find_namespace_packages MACOSX_VERSIONS = { None:'macosx', 'x86_64':'macosx_10_6_x86_64', 'arm64':'macosx_10_6_arm64' } def get_os_type(): if 'PYRTLSDRLIB_PLATFORM' in os.environ: return os.environ['PYRTLS...
pyrtlsdr/pyrtlsdrlib
setup.py
.py
8ee90c64ed207289
7.39
5
import numpy as np import pandas as pd import pytest from saiph.contribution import filter_variable_contribution @pytest.fixture def contributions() -> pd.DataFrame: df = pd.DataFrame( data=[[1, 0.01], [2, 1]], index=["Var. 1", "Var. 2"], columns=["Dim. 1", "Dim. 2"], ) return df...
octopize/saiph
saiph/contribution_test.py
.py
07a0a4b3510dece9
7.5
0
"""Inverse transform coordinates.""" import ast from typing import cast import numpy as np import pandas as pd from numpy.typing import NDArray from saiph.models import Model from saiph.reduction import DUMMIES_SEPARATOR from saiph.reduction.utils.common import get_dummies_mapping def inverse_transform( coord:...
octopize/saiph
saiph/inverse_transform.py
.py
f646ee356c54293d
7
0
"""FAMD projection module.""" import sys from typing import Any, cast import numpy as np import pandas as pd import scipy from numpy.typing import NDArray from scipy.sparse import csr_matrix from saiph.models import Model from saiph.reduction import DUMMIES_SEPARATOR from saiph.reduction.famd import fit as fit_famd ...
octopize/saiph
saiph/reduction/famd_sparse.py
.py
08076bf20f78f2e2
7
0
"""MCA projection module.""" from itertools import chain, repeat from typing import Any import numpy as np import pandas as pd from numpy.typing import NDArray from saiph.models import Model from saiph.reduction import DUMMIES_SEPARATOR from saiph.reduction.utils.common import ( column_multiplication, diag, ...
octopize/saiph
saiph/reduction/mca.py
.py
7e7d8f233a4fd6cc
7
0
"""PCA projection module.""" import sys import numpy as np import pandas as pd from numpy.typing import NDArray from saiph.models import Model from saiph.reduction.utils.common import ( get_explained_variance, get_projected_column_names, get_uniform_row_weights, ) from saiph.reduction.utils.svd import ge...
octopize/saiph
saiph/reduction/pca.py
.py
1904422699f65e10
7
0
from collections import OrderedDict from itertools import repeat from typing import Any import numpy as np import pandas as pd import scipy from numpy.typing import NDArray from toolz import concat from saiph.reduction import DUMMIES_SEPARATOR def get_projected_column_names(n: int) -> list[str]: return [f"Dim. ...
octopize/saiph
saiph/reduction/utils/common.py
.py
c6548d0faa4397e5
7
0
import numpy as np import pandas as pd from numpy.typing import NDArray from scipy import linalg from sklearn.utils import extmath def get_svd( df: pd.DataFrame, nf: int | None = None, *, svd_flip: bool = True, random_gen: np.random.Generator = np.random.default_rng(), ) -> tuple[NDArray[np.float6...
octopize/saiph
saiph/reduction/utils/svd.py
.py
720a9f1165ef6983
7
0
import numpy as np import pandas as pd import pytest from numpy.testing import assert_array_almost_equal from numpy.typing import NDArray from saiph.reduction.utils.svd import ( get_direct_randomized_svd, get_randomized_subspace_iteration, get_svd, ) # Matrix to decompose @pytest.fixture def matrix() -> ...
octopize/saiph
saiph/reduction/utils/svd_test.py
.py
a9f90a65b6256cc8
7.5
0
from dataclasses import dataclass from io import StringIO from typing import Any import msgspec import numpy as np import pandas as pd from toolz.dicttoolz import keymap, valmap from saiph.models import Model @dataclass class SerializedModel: data: Model __version__: str class ModelJSONSerializer: # !...
octopize/saiph
saiph/serializer.py
.py
e38a8a80c1df8005
7
0
"""Visualization functions.""" import numpy as np import pandas as pd from matplotlib import pyplot as plt from matplotlib.patches import Circle from numpy.typing import NDArray from saiph import transform from saiph.models import Model def plot_circle( model: Model, dimensions: list[int] | None = None, ...
octopize/saiph
saiph/visualization.py
.py
177f04409ce99426
7
0
"""Terminal colours, matching what the fish half of the vocabulary emits. `_ui` colours through `set_color`, whose reset is `\\x1b[m` rather than the more common `\\x1b[0m`. Reproduced exactly so a python tool and a fish function are indistinguishable when both are on screen. Unlike `set_color`, these are suppressed ...
jmanuelrosa/dotfiles
lib/python/dotkit/colors.py
.py
1f38208b1eda4cb8
7.24
2
"""The line vocabulary every script in this repo prints through. The python half of roles/shell/files/fish/functions/_ui.fish, kind for kind and glyph for glyph, so a fish function and a python command are indistinguishable on screen. Two rules hold the whole style together: status is a coloured glyph ✓ green, ...
jmanuelrosa/dotfiles
lib/python/dotkit/ui.py
.py
422cb9bb82c97afc
7.24
2
"""Fixtures for the dotkit suite. Only the colour toggles, because `ui` renders and touches nothing else. The helper they wrap lives in `dotkit.testing` rather than here: two suites need it now that test_ui sits beside the package instead of inside claude-kit's, and a fixture is the one thing a `conftest.py` can own w...
jmanuelrosa/dotfiles
lib/python/tests/conftest.py
.py
e020e25eedfe81e2
7.74
2
"""The design seat decides something, and nobody else quietly offers to decide it instead. The seat was for a while a pure conformance engine: 52 pass/fail rules and not one asking whether the result was any good. It passed its own gate on the median every time, because correctness is a floor and a floor makes no choi...
jmanuelrosa/dotfiles
lib/python/tests/test_design_direction.py
.py
3d218e183ce7951d
7.74
2
"""Pi's skill discovery, run for real, because the whole `.agents/skills` link rests on it. `claude_kit.pi` links one directory and claims that pi then sees every skill a project installed. Three facts have to hold for that to be true, and all three live in pi's code rather than ours: - a symlinked skill *directory...
jmanuelrosa/dotfiles
lib/python/tests/test_pi_discovery.py
.py
3603436359f1193a
7.74
2
"""The velocity extension's couplings are all with pi's own API, so they fail silently. Every name this extension depends on belongs to the installed pi package: the guard that tells an edit result from a write one, the `patch` field it counts, the theme colours it paints with, and the footer call itself. None of them...
jmanuelrosa/dotfiles
lib/python/tests/test_pi_velocity.py
.py
3779621b4a8683b0
7.74
2
"""The review policy reaches every session, and no REVIEW.md reaches anything. One artifact states the design, and it has four ways of silently ceasing to work. `files/claude/rules/code-review.md` is a user-scope rule: linked into ~/.claude/rules/ it loads at launch in every project, which is the whole reason it was ...
jmanuelrosa/dotfiles
lib/python/tests/test_review_policy.py
.py
53d862d52292fd77
7.74
2
"""The Television claude cables read claude-kit, and derive nothing themselves. There is no fish test suite, and that is how the bug this file guards against shipped. `_tv_claude_list` used to rebuild claude-kit's whole answer in jq and fish: the catalogue, the dependency_only hiding, the effective global set, and lin...
jmanuelrosa/dotfiles
lib/python/tests/test_tv_cables.py
.py
843a329d5076e876
7.74
2
"""`git-skill-gate.sh` gates commit and push behind the skills that own them. The hook reads a PreToolUse event on stdin and signals with its exit code: 0 allows the command, 2 blocks it. Cases assert on that code alone, never on the refusal text, so the messages can be reworded freely. Skill attribution is faked by ...
jmanuelrosa/dotfiles
roles/ai/files/claude/hooks/tests/test_git_skill_gate.py
.py
923b93bbbf466902
7.74
2
"""`plan-date-stamp.sh` prefixes an approved plan file with the date. The hook reads a PostToolUse event on stdin and always exits 0, since a failed rename must never cost the user an approved plan. So cases assert on the filesystem and on the emitted JSON, never on the exit code. The plan path is faked by writing a ...
jmanuelrosa/dotfiles
roles/ai/files/claude/hooks/tests/test_plan_date_stamp.py
.py
a857673198c5d1c3
7.74
2
#!/usr/bin/env python3 """context.py - one-shot CodeRabbit thread context for the /coderabbit skill. Resolves the repo and PR, fetches every review thread with its resolved and outdated state, drops the threads a previous run already handled, strips CodeRabbit's collapsed boilerplate, and groups what survives by file ...
jmanuelrosa/dotfiles
roles/ai/files/claude/skills/coderabbit/scripts/context.py
.py
12b9b1f1f0818d47
7.24
2
#!/usr/bin/env python3 """adf.py - build a Jira description in ADF from the squad's ticket template. Reads a markdown-ish file (or stdin on `-`) whose `##` headers name the template's sections and writes the bare ADF `doc` that `acli jira workitem create|edit --description-file` expects: ## Context The Stripe...
jmanuelrosa/dotfiles
roles/ai/files/claude/skills/jira/scripts/adf.py
.py
2dc96f917ac8e5eb
7.24
2
#!/usr/bin/env python3 """context.py - one-shot branch context for the /pr skill. Prints everything the drafting steps need in a single Bash round-trip: host, base and current branch, the resolved GitLab account, the PR/MR template, the commit list, the file stat, a filtered diff, and the deterministic title plus the ...
jmanuelrosa/dotfiles
roles/ai/files/claude/skills/pr/scripts/context.py
.py
7f7fd7dccfd88464
7.24
2
"""SwiftUI lane parser (Xcode 26+). Primary schema is `swiftui-updates` with columns: start, duration, id, update-type, allocations, description, category, view-hierarchy, module, view-name, process, thread, root-causes, severity, cause-graph-node, full-cause-graph-node. We aggregate by view-name across all SwiftUI s...
jmanuelrosa/dotfiles
roles/ai/files/claude/skills/swiftui-expert-skill/scripts/instruments_parser/swiftui.py
.py
f499b222b24c2129
7.24
2
"""Thin wrapper around the `xctrace` CLI.""" from __future__ import annotations import subprocess import xml.etree.ElementTree as ET from dataclasses import dataclass from pathlib import Path @dataclass(frozen=True) class RunInfo: """Per-run metadata and schemas. Instruments traces can hold multiple runs.""" ...
jmanuelrosa/dotfiles
roles/ai/files/claude/skills/swiftui-expert-skill/scripts/instruments_parser/xctrace.py
.py
b680bddb80d7f63f
7.24
2
#!/usr/bin/env python3 """Record an Xcode Instruments .trace file via `xctrace record`. Three modes: (default) Start a recording. Stops on Ctrl+C, stop-file, or time limit. --list-devices Enumerate connected devices + simulators as JSON. --list-templates Enumerate available Instruments templates a...
jmanuelrosa/dotfiles
roles/ai/files/claude/skills/swiftui-expert-skill/scripts/record_trace.py
.py
7d9c33de1146a274
7.24
2
""" Comprehensive health check system for Visor I2D Backend """ import logging import time import os import shutil from django.http import JsonResponse from django.db import connection from django.core.cache import cache from django.conf import settings from rest_framework.decorators import api_view from rest_framework...
PEM-Humboldt/visor-geografico-I2D-backend
applications/common/health.py
.py
5412d49293557237
7.15
1
""" Data quality and validation middleware for Visor I2D Backend """ import json import logging from django.http import JsonResponse from django.core.exceptions import ValidationError from django.utils.deprecation import MiddlewareMixin from rest_framework import status logger = logging.getLogger(__name__) class Se...
PEM-Humboldt/visor-geografico-I2D-backend
applications/common/middleware.py
.py
7956e0575a13b910
7.15
1
""" Enhanced serializers with comprehensive validation for Visor I2D Backend """ from rest_framework import serializers from django.core.exceptions import ValidationError as DjangoValidationError from .validators import ( department_validator, municipality_validator, biodiversity_validator, gbif_validator, use...
PEM-Humboldt/visor-geografico-I2D-backend
applications/common/serializers.py
.py
2f7f9bcf7d74de04
7.15
1
""" PostGIS integration and spatial operations for Visor I2D Backend """ from django.contrib.gis.geos import Point, Polygon, MultiPolygon from django.contrib.gis.measure import Distance from django.contrib.gis.db.models import Q from django.core.exceptions import ValidationError import logging logger = logging.getLogg...
PEM-Humboldt/visor-geografico-I2D-backend
applications/common/spatial.py
.py
f0c5104b488984fe
7.15
1
""" Comprehensive input validation utilities for Visor I2D Backend """ import re from django.core.exceptions import ValidationError from django.core.validators import validate_email from rest_framework import serializers class ColombianDepartmentValidator: """Validator for Colombian department codes""" V...
PEM-Humboldt/visor-geografico-I2D-backend
applications/common/validators.py
.py
c27959a9644ee8ab
7.15
1
from django.shortcuts import render from rest_framework.generics import ListAPIView from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi from .models import DptoQueries, DptoAmenazas from .serializers import dptoQueriesSerializer, dptoDangerSerializer class dptoQuery(ListAPIView): """ AP...
PEM-Humboldt/visor-geografico-I2D-backend
applications/dpto/views.py
.py
9e2509c5b4528ba4
7.15
1
import os from django.shortcuts import render import io import csv import json import boto3 from django.http import HttpResponse, FileResponse from django.db import connection from rest_framework.generics import ListAPIView from rest_framework.views import APIView from rest_framework.response import Response from rest...
PEM-Humboldt/visor-geografico-I2D-backend
applications/gbif/views.py
.py
881a5fe4d733afff
7.15
1
from django.contrib import admin from django import forms from django.db import models from django.utils.html import format_html from .models import Project, LayerGroup, Layer @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): """ Admin interface for Project model """ list_display = ['nomb...
PEM-Humboldt/visor-geografico-I2D-backend
applications/projects/admin.py
.py
68254f7baa803329
7.15
1
from pathlib import Path from textwrap import dedent from typing import Optional import mps import typer from .cli import main as _main from .motion_tracking import FLOW_ALGORITHMS app = typer.Typer(help="Estimate motion in stack of images") def version_callback(show_version: bool): """Prints version informati...
ComputationalPhysiology/mps_motion
src/mps_motion/__main__.py
.py
e229f6ff65a3a6dd
7.15
1
import functools import logging from typing import Optional from typing import Union try: from functools import cached_property # type: ignore except ImportError: # This is only supported in python 3.8 and above try: from cached_property import cached_property # type: ignore except ImportErro...
ComputationalPhysiology/mps_motion
src/mps_motion/mechanics.py
.py
4401e2d9bcde7b26
7.15
1
import logging from pathlib import Path from typing import Optional from typing import Union import cv2 import dask.array as da import matplotlib.pyplot as plt import numpy as np import tqdm from . import frame_sequence as fs from . import scaling from . import utils logger = logging.getLogger(__name__) def apply_...
ComputationalPhysiology/mps_motion
src/mps_motion/visu.py
.py
799c9654b5436be7
7.15
1
import numpy as np from mps_motion import Mechanics from mps_motion import OpticalFlow from mps_motion import scaling from mps_motion import utils def test_resize_data(): frames = np.ones((100, 100, 3)) times = np.linspace(0, 5000, frames.shape[-1]) info = dict(um_per_pixel=1.0) data = utils.MPSData(f...
ComputationalPhysiology/mps_motion
tests/test_scaling.py
.py
7da3ef0231bcf69a
7.65
1
"""Date parsing and formatting utilities.""" from datetime import datetime def parse_date(date_str: str) -> datetime: """Parse an ISO date string (with optional trailing 'Z') to datetime.""" return datetime.fromisoformat(date_str.replace("Z", "+00:00")) def format_date_iso(date_str: str) -> str: """For...
prakashsellathurai/prakashsellathurai.github.io
code/scripts/lib/dates.py
.py
fcb547fb8403a171
7
0
from django.db import models class AdminInterfaceConfiguration(models.Model): """Model for storing the configuration of the admin interface""" name = models.CharField(max_length=255, unique=True, default='Default') description = models.TextField(blank=True, default='') active = models.BooleanField(def...
Amsterdam-Music-Lab/MUSCLE
backend/admin_interface/models.py
.py
86e314cd53a5532f
7.35
4
from .utils import camelize class BaseAction(object): """Base class for all experiment actions in the MUSCLE framework. This class serves as the foundation for various action types that configure frontend components. All action classes (e.g., Score, Playback, Form, etc.) inherit from this base class ...
Amsterdam-Music-Lab/MUSCLE
backend/experiment/actions/base_action.py
.py
a3e9585900d21227
7.35
4
from typing import Optional, TypedDict from .base_action import BaseAction from theme.models import VALID_COLORS class ButtonAction(TypedDict): label: str color: str link: Optional[str] class Button(BaseAction): """A button object to be used for ButtonArrayQuestions, as PlayButton, or a skip / submi...
Amsterdam-Music-Lab/MUSCLE
backend/experiment/actions/button.py
.py
555488291d62bd13
7.35
4
from os.path import splitext from django.template.loader import render_to_string from django.template import Template, Context from django_markup.markup import formatter from django.core.files import File from django.utils.translation import gettext_lazy as _ from typing import Literal from .base_action import BaseA...
Amsterdam-Music-Lab/MUSCLE
backend/experiment/actions/consent.py
.py
6ab0868903898bf6
7.35
4
from typing import List, TypedDict, Optional from django_markup.markup import formatter from .base_action import BaseAction from .button import Button, ButtonAction class StepAction(TypedDict): number: Optional[int] description: str class ExplainerAction(TypedDict): view: str instruction: str ...
Amsterdam-Music-Lab/MUSCLE
backend/experiment/actions/explainer.py
.py
328fc3ffd102c2e6
7.35
4
from django.utils.translation import gettext_lazy as _ from .base_action import BaseAction class HTML(BaseAction): """An action that renders HTML content. See also the `HTML.tsx` component in the frontend project. Args: body (str): The HTML body content Examples: To render a simple HTML ...
Amsterdam-Music-Lab/MUSCLE
backend/experiment/actions/html.py
.py
20404a8f19e1d1eb
7.35
4
from typing import List, Optional, Any, Literal, TypedDict from .base_action import BaseAction from .button import Button from section.validators import audio_extensions from section.models import Section # player types TYPE_AUTOPLAY = "AUTOPLAY" TYPE_BUTTON = "BUTTON" TYPE_MATCHINGPAIRS = "MATCHINGPAIRS" # playbac...
Amsterdam-Music-Lab/MUSCLE
backend/experiment/actions/playback.py
.py
f0615fb56ef8936a
7.35
4
from django.utils.translation import gettext_lazy as _ from .base_action import BaseAction class PlaylistSelection(BaseAction): # pylint: disable=too-few-public-methods """ Provide data for playlist selection view Relates to client component: Playlist.tsx The client component automatically continue...
Amsterdam-Music-Lab/MUSCLE
backend/experiment/actions/playlist.py
.py
cd60f3fe39bb9068
7.35
4
import random from typing import Optional, TypedDict from django.utils.translation import gettext as _ from result.models import Result from session.models import Session from .base_action import BaseAction from .button import Button class ScoreConfig(TypedDict): """ Configuration for the Score action ...
Amsterdam-Music-Lab/MUSCLE
backend/experiment/actions/score.py
.py
107788e0134fb175
7.35
4
# This file is part of the JACoW plugin. # Copyright (C) 2021 - 2026 CERN # # The CERN Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; see # the LICENSE file for more details. from sqlalchemy.ext.declarative import declared_attr from indico.core.db....
indico/indico-plugin-jacow
indico_jacow/models/affiliations.py
.py
eba32c20fa944097
7.24
2
from django.core.cache import cache from rest_framework import exceptions from rest_framework.authentication import BaseAuthentication from rest_framework_api_key.permissions import KeyParser from services.models import ServiceAPIKey class ServiceApiKeyAuthentication(BaseAuthentication): """Authenticates the use...
City-of-Helsinki/atv
atv/authentication.py
.py
ee574c4b6801affb
7.15
1
import os from django.conf import settings from documents.models import Document from documents.utils import get_document_attachment_directory_path from utils.commands import BaseCommand from utils.files import remove_directory, remove_file class Command(BaseCommand): help = "Remove outdated files" directo...
City-of-Helsinki/atv
documents/management/commands/remove_outdated_files.py
.py
1100ea7cb8fe5c55
7.15
1
import sys from pathlib import Path from unittest.mock import patch SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "scripts" sys.path.insert(0, str(SCRIPTS_DIR)) import indexnow_check # ==================== parse_iso_datetime 纯函数测试 ==================== def test_parse_iso_datetime_with_z_suffix(): """Z 后缀...
greenzorro/victor42.eth
tests/test_indexnow_check.py
.py
d855d6d016c09cef
7.5
0
#!/usr/bin/env python3 """ Generate architecture diagram for a Python project in PlantUML format. Usage: python scripts/generate_architecture_diagram.py [path] [--output file.pu] Examples: # Analyze sgraph itself python scripts/generate_architecture_diagram.py ./src/sgraph # Analyze any Python projec...
softagram/sgraph
scripts/generate_architecture_diagram.py
.py
fbd9b1f637cf33e2
7
0
#!/usr/bin/env python3 """ Generate detailed dependency diagram in PlantUML format. Shows all files/modules and their dependencies at the most detailed level. Usage: python scripts/generate_dependency_diagram.py [path] [--output file.pu] Examples: # Analyze sgraph itself python scripts/generate_dependenc...
softagram/sgraph
scripts/generate_dependency_diagram.py
.py
af392dc43e62c24a
7
0
"""Shared types and helper functions for the analyzer architecture.""" from __future__ import annotations from dataclasses import dataclass, field from enum import Enum, auto from pathlib import Path from typing import TYPE_CHECKING from collections.abc import Sequence if TYPE_CHECKING: from sgraph import SGraph ...
softagram/sgraph
src/sgraph/analyzers/base.py
.py
8d53f2e19e335dc6
7
0
"""Shared structures for code analysis.""" from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterator import fnmatch @dataclass(frozen=True, slots=True) class SourceFile: """ Metadata for a source file. Attributes: path: Absolute pat...
softagram/sgraph
src/sgraph/analyzers/code/base.py
.py
f947aa1789682dfc
7
0
"""Python AST processing for building the element structure.""" from __future__ import annotations import ast from typing import Any from sgraph import SElement from ...base import AnalyzerConfig, AnalysisLevel from ..base import SourceFile def visit_module( tree: ast.Module, file_element: SElement, so...
softagram/sgraph
src/sgraph/analyzers/code/python/ast_visitor.py
.py
115587547b7170f9
7
0
"""Python import resolution for creating dependencies.""" from __future__ import annotations from dataclasses import dataclass from typing import Any from sgraph import SElement from ...base import AnalyzerConfig @dataclass(slots=True) class ImportTarget: """A resolved import target.""" element: SElement ...
softagram/sgraph
src/sgraph/analyzers/code/python/import_resolver.py
.py
2a35fa6ddeacdc64
7
0
"""Python source code analyzer.""" from __future__ import annotations import ast from pathlib import Path from typing import Any from sgraph import SGraph, SElement, SElementAssociation from ...base import ( AnalyzerConfig, AnalysisResult, AnalysisError, AnalysisLevel, ) from ..base import SourceFile...
softagram/sgraph
src/sgraph/analyzers/code/python/python_analyzer.py
.py
d5959dc32f8c5181
7
0
from __future__ import annotations import sys from sgraph import SGraph """ Use like this: python3 show_model.py (to get the last model from your /softagram/output) python3 show_model.py path/to/modelfile.xml python3 show_model.py .softagram/download/api/..../modelfile.xml python3 show_model.py /opt/softagram...
softagram/sgraph
src/sgraph/cli/show_model.py
.py
8ad6bf522210eecd
7
0
import difflib import Levenshtein from sgraph import SElement def elem_similarity(elem_a, elem_b, points_level, return_points): points = 0 if not elem_a.typeEquals(elem_b.getType()): # Type change always means a new element. if return_points: return 0 else: r...
softagram/sgraph
src/sgraph/compare/similarityanalysis.py
.py
d209ac5e3a4a19bb
7
0
import json from sgraph import SGraph, SElement def sgraph_element_to_dict(element: SElement): """ Converts a SElement into a dictionary, including its children elements. :param element: SElement object :return: dictionary that contains JSON-serializable data """ output = {'name': element.nam...
softagram/sgraph
src/sgraph/converters/sgraph_json.py
.py
dc18ea5f03ae2e0f
7
0
""" Feature: Database ================= Tests that general results can be loaded from hard-disk via directory aggregation. This script outputs all files which can be associated with a model-fit (e.g. samples, full samples summary, search output). This can take up large amounts of hard-disk space. __Env__ Test-harne...
PyAutoLabs/autofit_workspace_test
scripts/database/directory/general.py
.py
6568e55c875b3e2f
7.24
2
""" Feature: Database ================= Tests that the results of a fit which sums multiple Analysis classes together can be loaded from hard-disk via a database built via a scrape. __Env__ Test-harness configuration (PyAutoHands docs/env_profile_redesign.md §10). Asserts len(agg) > 0; needs a real sampler run (TEST...
PyAutoLabs/autofit_workspace_test
scripts/database/directory/multi_analysis.py
.py
59bcae659d8e92d5
7.24
2
""" Feature: Database ================= Tests that general results can be loaded from hard-disk via a database built via a scrape. __Env__ Test-harness configuration (PyAutoHands docs/env_profile_redesign.md §10). Asserts len(agg) > 0; needs a real sampler run (TEST_MODE=2 bypass leaves the aggregator empty). ENV: ...
PyAutoLabs/autofit_workspace_test
scripts/database/scrape/general.py
.py
605703471639ff3b
7.24
2
""" Feature: Database ================= Tests that general results can be loaded from hard-disk via a database built via a database that is written to during a fit. """ # %matplotlib inline # from pyprojroot import here # workspace_path = str(here()) # %cd $workspace_path # print(f"Working Directory has b...
PyAutoLabs/autofit_workspace_test
scripts/database/session/general.py
.py
e4df95cac199f640
7.24
2
""" Feature: Database ================= Tests that the results of a fit which sums multiple Analysis classes together can be loaded from hard-disk via a database built via a scrape. """ # %matplotlib inline # from pyprojroot import here # workspace_path = str(here()) # %cd $workspace_path # print(f"Workin...
PyAutoLabs/autofit_workspace_test
scripts/database/session/multi_analysis.py
.py
8b98b612a2776fd0
7.24
2
""" Integration guard: latent variables that go NaN in an arbitrary per-sample pattern must NOT crash the end-of-search latent summary. This is the autofit-level guard for the bug Sam hit downstream in PyAutoLens (``KeyError`` on ``total_lensed_source_flux``). The defect is in PyAutoFit itself — ``autofit/non_linear/a...
PyAutoLabs/autofit_workspace_test
scripts/features/latent_nan_robustness.py
.py
bb3adfe2206d0cbe
7.24
2
import boto3 from botocore.exceptions import ClientError # Constants for quota increase SERVICE_CODE = 'iam' QUOTA_CODES = ['L-0DA4ABF3'] # Quota codes for desired policies DESIRED_QUOTA_VALUE = 25 ASSUME_ROLE_NAME = 'OrganizationAccountAccessRole' # Default IAM role for AWS Organizations def assume_role(account_id...
sonraisecurity/sonrai-public-assets
utilities/scripts/CMPQuotas.py
.py
f6d24b3d8f16d58e
7.15
1
#!/usr/bin/env python3 import argparse import json import sys import os from sonrai_api import api, logger def get_account_scope_map(): """Fetches all account scopes and returns a dict mapping account_id to scope.""" query = """ query getCloudHierarchyList($filters: CloudHierarchyFilter) { CloudHie...
sonraisecurity/sonrai-public-assets
utilities/scripts/cpf-migrate-controls.py
.py
6906f5cf70b04090
7.15
1
#!/usr/bin/env python3 import os import shlex import subprocess import sys CPF_PATH = os.path.expanduser("/opt/cpf") def run_command(cmd: list[str]) -> int: """Run a command, echo it, and return the exit code.""" print(f"Running: {' '.join(shlex.quote(part) for part in cmd)}") completed = subprocess.run(cmd, ch...
sonraisecurity/sonrai-public-assets
utilities/scripts/pagerduty-sync-to-cpf-approvers-at-scope.py
.py
d00931f8b6b018a4
7.15
1
import time import datetime import os import logging import jwt import sys import json import requests import readline from os import path from datetime import datetime from pathlib import Path # get the calling scripts and this library's path script_path = os.path.dirname(sys.argv[0]) lib_path = Path(__file__).paren...
sonraisecurity/sonrai-public-assets
utilities/sonrai_api/token.py
.py
bf45a1b556994b29
7.15
1
import hmac import hashlib import sys import hmac from ..errors import SignatureVerificationError class Utility(object): def __init__(self, client=None): self.client = client # Taken from Django Source Code # Used in python version < 2.7.7 # As hmac.compare_digest is not present in prev vers...
nimbbl-tech/nimbbl-python-sdk
nimbbl/utility/utility.py
.py
098af89520dbbe8a
7
0
#! /usr/bin/env python import os import shutil import subprocess import tempfile import sys import logging import argparse # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) SPHINX_DIR = os.path.join(os.getcwd(), ...
canonical/nginx-ingress-integrator-operator
docs/.sphinx/get_vale_conf.py
.py
207c9ea5ec6bae15
7.15
1
# Copyright 2024 Canonical Ltd. # Licensed under the Apache2.0. See LICENSE file in charm source for details. """Library for the ingress relation. This library contains the Requires and Provides classes for handling the ingress interface. Import `IngressRequires` in your charm, with two required options: - "self" (th...
canonical/nginx-ingress-integrator-operator
lib/charms/nginx_ingress_integrator/v0/ingress.py
.py
a96a1441f3a98fbb
7.15
1
# Copyright 2024 Canonical Ltd. # Licensed under the Apache2.0. See LICENSE file in charm source for details. """Library for the nginx-route relation. This library contains the require and provide functions for handling the nginx-route interface. Import `require_nginx_route` in your charm, with four required keyword ...
canonical/nginx-ingress-integrator-operator
lib/charms/nginx_ingress_integrator/v0/nginx_route.py
.py
581a0b18847f1132
7.15
1
#!/usr/bin/env python3 # Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. """Nginx-ingress-integrator charm file.""" import json import logging from typing import Any, Dict, List, Optional, Union, cast import kubernetes.client from charmlibs.interfaces.tls_certificates import ( Certificate...
canonical/nginx-ingress-integrator-operator
src/charm.py
.py
1fe294a4b92b9ead
7.15
1