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
""" Llama.cpp-based Inference Engine for Ignis AI. Optimized for GGUF models with CUDA acceleration. """ import os from pathlib import Path from typing import Dict, Any, Optional, AsyncGenerator, List import asyncio from llama_cpp import Llama class InferenceEngine: """ Inference engine using llama.cpp for GG...
shumskyw/Ignis
src/core/inference_engine.py
.py
97c64dbd5ab5cb5c
7
0
""" Memory utilities for Ignis AI. Contains helper functions, validation logic, and utility classes. """ import hashlib import re from datetime import datetime, timedelta from typing import Any, Dict, List, Optional, Tuple from ..utils.logger import get_logger logger = get_logger(__name__) class MemoryValidation: ...
shumskyw/Ignis
src/core/memory_utils.py
.py
dd6f468bd9a19891
7
0
""" Personality engine for Ignis AI. Manages personality traits, personas, and response filtering. """ import json import os import random from pathlib import Path from typing import Any, Dict, List, Optional from ..utils.logger import get_logger logger = get_logger(__name__) class PersonalityEngine: """ M...
shumskyw/Ignis
src/core/personality_engine.py
.py
b3cc14fc3027c09a
7
0
""" REST API for Ignis AI using FastAPI. Provides programmatic access to Ignis. """ import asyncio import os from typing import Any, Dict, List, Optional import uvicorn from fastapi import BackgroundTasks, FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Field ...
shumskyw/Ignis
src/interfaces/api/rest_api.py
.py
9110a8c8be454fd2
7
0
""" Web UI for Ignis AI using Gradio. Provides browser-based chat interface. """ import asyncio import json import os from pathlib import Path from typing import List, Optional, Tuple from ...utils.logger import get_logger logger = get_logger(__name__) class WebUI: """ Web-based user interface for Ignis AI...
shumskyw/Ignis
src/interfaces/web_ui/app.py
.py
56186650dbf6ba4f
7
0
""" Custom Web UI for Ignis AI - iMessage-style interface. Serves static HTML/CSS/JS files and integrates with Ignis API. """ import asyncio import os import time import webbrowser from pathlib import Path import uvicorn from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddl...
shumskyw/Ignis
src/interfaces/web_ui/custom_app.py
.py
cce23dc1378ec47d
7
0
""" Calculator plugin for Ignis AI. Provides mathematical calculation capabilities. """ import math import re from typing import Any, Dict, List, Optional from .base_plugin import BasePlugin class CalculatorPlugin(BasePlugin): """ Plugin that provides mathematical calculation capabilities. """ def ...
shumskyw/Ignis
src/plugins/calculator.py
.py
9ddfe13d27e051c3
7
0
""" Coding assistant plugin for Ignis AI. Provides programming help and code analysis. """ import re from typing import Any, Dict, List, Optional from .base_plugin import BasePlugin class CodingAssistantPlugin(BasePlugin): """ Plugin that provides coding assistance features. """ def __init__(self):...
shumskyw/Ignis
src/plugins/coding_assistant.py
.py
ae4e5f193be90fd8
7
0
""" Document reader plugin for Ignis AI. Allows reading and processing local documents. """ import os import re from pathlib import Path from typing import Any, Dict, List, Optional from .base_plugin import BasePlugin class DocumentReaderPlugin(BasePlugin): """ Plugin that allows reading local documents for...
shumskyw/Ignis
src/plugins/document_reader.py
.py
48725921aa28e2a6
7
0
""" Logging utilities for Ignis AI. """ import logging import logging.handlers import os from pathlib import Path from typing import Optional def get_logger(name: str) -> logging.Logger: """ Get a configured logger instance. Args: name: Logger name (usually __name__) Returns: Config...
shumskyw/Ignis
src/utils/logger.py
.py
faeb2112c188f9c1
7
0
""" Async Performance Debugger Analyzes and optimizes async operations for better performance. """ import asyncio import inspect import os import threading import time import tracemalloc from concurrent.futures import ThreadPoolExecutor from functools import wraps from typing import Any, Callable, Dict, List, Optional...
shumskyw/Ignis
tests/performance/async_performance_debugger.py
.py
e2b24635bafd5dc3
7.5
0
""" ChatGPT-Competitive Performance Optimizer Advanced optimizations to make Ignis compete with ChatGPT-level performance. """ import asyncio import json import os import threading import time import tracemalloc from concurrent.futures import ThreadPoolExecutor from functools import lru_cache, wraps from pathlib impor...
shumskyw/Ignis
tests/performance/chatgpt_competitor_optimizer.py
.py
ab35ef61ef195bc3
7.5
0
""" ChatGPT-Level Performance Optimizer Benchmarks and optimizes Ignis AI for ChatGPT-level speed and quality. """ import asyncio import json import os import statistics import time from pathlib import Path from typing import Any, Dict, List, Tuple import psutil from async_performance_debugger import AsyncPerformance...
shumskyw/Ignis
tests/performance/chatgpt_performance_optimizer.py
.py
2400d789a9c98516
7.5
0
""" Ignis Performance Integration Integrates ChatGPT-competitive optimizations into the Ignis AI system. """ import asyncio import inspect import os import sys import time import types from typing import Any, Dict, List, Optional from .async_performance_debugger import AsyncPerformanceDebugger from .chatgpt_competito...
shumskyw/Ignis
tests/performance/ignis_performance_integration.py
.py
996a0321745dd87f
7.5
0
""" Unified Memory & Performance Debug Suite Combines conversation continuity, async performance, and short-term memory debugging. """ import asyncio import time from typing import Any, Dict, List from async_performance_debugger import AsyncPerformanceDebugger from conversation_continuity_debugger import Conversation...
shumskyw/Ignis
tests/performance/unified_debug_suite.py
.py
945a68abf75c5262
7.5
0
#!/usr/bin/env python3 """ Test script for assumption detection functionality. """ import sys from pathlib import Path # Add project root to path project_root = Path(__file__).parent.parent sys.path.insert(0, str(project_root)) sys.path.insert(0, str(project_root / 'src')) from src.core.ignis import IgnisAI def te...
shumskyw/Ignis
tests/unit/test_assumption_detection.py
.py
6be88ba23acc3858
7.5
0
from dataclasses import dataclass, field from typing import ClassVar, Literal import requests Arch = Literal["amd64", "arm64"] @dataclass class Binary: arch: Arch """Architecture for the pre-compiled binary.""" version: ClassVar[str] """Version of the binary.""" gh_repo: ClassVar[str | None] =...
activatedgeek/dotfiles
pkgs/myinfra/src/myinfra/utils/binary.py
.py
3ffb34895b3686f6
7.15
1
"""Benchmark: measure-adapted TEDOPA star vs Gauss-Legendre star. Compares how well each N-mode star discretization reproduces the exact bath correlation function ``C(t) = int J_beta(w) e^{-i w t} dw`` for a few thermalized spectral densities. The TEDOPA star (Gauss quadrature of the actual measure J_beta dw) resolves...
nominhanggai/fishbone-tensor-networks
benchmarks/bath_discretization.py
.py
4ede2161b979015f
7.35
4
"""The high-level interface: spin-boson and fishbone dynamics in a few lines. Declare the bath(s) and physical system with :class:`~fishbonett.models.SystemBath` or :class:`~fishbonett.models.Fishbone`, then call ``run`` once. Run with: python examples/friendly_interface.py """ import numpy as np from fishbonett im...
nominhanggai/fishbone-tensor-networks
examples/friendly_interface.py
.py
9342b01f3c9d4220
7.35
4
"""Vibrationally assisted transfer in a biased molecular dimer. The model is the Brownian-oscillator dimer used by Dijkstra et al. (arXiv:1309.4910). Run the inexpensive engine check with ``python examples/vibronic_dimer.py``. The ``docs`` profile reconstructs the two quantum benchmark trajectories at omega/J = 4 and ...
nominhanggai/fishbone-tensor-networks
examples/vibronic_dimer.py
.py
bfb9aea87318d173
7.35
4
"""Numerical forms of the package's open-system conventions. The package uses ``hbar = 1`` and ``J(omega) = pi * sum_k |g_k|**2 delta(omega - omega_k)``. Consequently a quadrature node with weight ``q_k`` has ``g_k**2 = J(omega_k) q_k / pi`` and the reorganization energy is ``lambda = integral J(omega) / (pi * omega...
nominhanggai/fishbone-tensor-networks
src/fishbonett/bath/conventions.py
.py
43dfcc42702ab915
7.35
4
"""Binding between a bath specification and its system coupling operators.""" from __future__ import annotations from dataclasses import dataclass, replace from collections.abc import Sequence import numpy as np from numpy.typing import ArrayLike from fishbonett.bath.spec import Bath __all__ = ["CoupledBath", "bind...
nominhanggai/fishbone-tensor-networks
src/fishbonett/bath/coupled.py
.py
b549881bb712561c
7.35
4
r"""Measure-adapted Gaussian discretization for TEDOPA-style chain mappings. The implementation follows two standard numerical facts. First, a positive continuous measure can be represented accurately by a sufficiently fine composite Gaussian rule. Second, Lanczos tridiagonalization of the diagonal node matrix, star...
nominhanggai/fishbone-tensor-networks
src/fishbonett/bath/tedopa.py
.py
32986234e6bb1912
7.35
4
"""Tensor contractions used by the tensor-network engines. The package requires :mod:`opt_einsum` so that its MPS and tree engines use the same contraction-path implementation on every supported installation. This module keeps that dependency behind one stable package-level function. """ from functools import lru_cach...
nominhanggai/fishbone-tensor-networks
src/fishbonett/contract.py
.py
be1180bf6bd1846e
7.35
4
"""Boys localization for multi-state diabatization. Obtain diabatic electronic couplings from adiabatic state/transition dipole matrices via Jacobi sweeps that maximize the Boys localization function. Reference: J. Chem. Phys. 129, 244101 (2008). """ import itertools as it import numpy as np from numpy.linalg import...
nominhanggai/fishbone-tensor-networks
src/fishbonett/diabatization.py
.py
5aed454fe7f2a043
7.35
4
"""Balanced mode-tree topology and generic tree-operator construction. The interaction representation removes the free bath and leaves a sum of modes coupled to the system. The finite conditional-coupling exponential is represented as a low-bond tree operator, applied to a balanced binary tree tensor network, then com...
nominhanggai/fishbone-tensor-networks
src/fishbonett/evolve/_modetree_core.py
.py
813cc308eeb46535
7.35
4
"""Whole-run drivers for the balanced mode-tree TTNO propagator.""" import numpy as np import scipy.linalg from fishbonett.linalg import DEFAULT_EPS, Truncation from fishbonett.evolve._modetree_core import ( _resolve_sys, build_balanced_tree, init_state, ) from fishbonett.evolve._modetree_sweeps import ( apply...
nominhanggai/fishbone-tensor-networks
src/fishbonett/evolve/_modetree_driver.py
.py
a7a3ad185f90e7b8
7.35
4
"""Graph-generic tensor operations for balanced mode-tree propagation. The high-level integrator applies the commuting system--bath exponential as a tree tensor-network operator (TTNO), then restores mixed-canonical form and truncates every edge by its Schmidt spectrum. """ import numpy as np import scipy.linalg from...
nominhanggai/fishbone-tensor-networks
src/fishbonett/evolve/_modetree_sweeps.py
.py
fe4a9b73620bffe8
7.35
4
"""Environment contractions and local exponential actions for MPS evolution. Tensors use ``(left bond, right bond, physical)`` and MPO tensors use ``(left operator bond, right operator bond, physical out, physical in)``. The exponential action is an Arnoldi process, so the primitive remains correct for a mildly non-He...
nominhanggai/fishbone-tensor-networks
src/fishbonett/evolve/_tdvp_kernels.py
.py
d3fc6beee9154814
7.35
4
"""Swap-network TEBD for conventional exciton-bath MPS layouts.""" from __future__ import annotations import numpy as np import scipy.linalg as la from fishbonett.contract import _einsum_cached from fishbonett.evolve._tdvp_kernels import right_canonicalize from fishbonett.evolve.tebd import update_bond from fishbone...
nominhanggai/fishbone-tensor-networks
src/fishbonett/evolve/exciton_tebd.py
.py
53d505743dac23ae
7.35
4
""" Demo Scripts - Examples of how to use the utility functions. """ import sys from pathlib import Path # Add parent directory to path for imports sys.path.insert(0, str(Path(__file__).parent.parent)) from datetime import datetime, timedelta from utils.file_utils import find_files, get_file_info, get_directory_size...
VOIDsymbyote/python-utils-toolkit
examples/demo_scripts.py
.py
f4a2069fded0b954
7
0
""" System Utilities - Functions for system-related operations. """ import os import sys import platform import subprocess from pathlib import Path from typing import Dict, List, Optional from datetime import datetime def get_disk_usage(path: str = "/") -> Dict: """ Get disk usage information for a path. ...
VOIDsymbyote/python-utils-toolkit
utils/system_utils.py
.py
4b16cdc612b4a116
7
0
import graphene from app.controllers.utils import atomic_transaction from app.data_access.employment import OAuth2ClientOutput from app.domain.company import link_company_to_software from app.domain.permissions import company_admin from app.helpers.authentication import AuthenticatedMutation from app.helpers.authoriza...
MTES-MCT/mobilic-api
app/controllers/third_party_company.py
.py
3b88cef25a258c3b
7.3
3
""" CartPole Hacking Detection Demo This example demonstrates how the hacking detection system works by using policies that exhibit different hacking behaviors. """ import sys from pathlib import Path import time # Add parent directory to path sys.path.insert(0, str(Path(__file__).parent.parent)) import gymnasium a...
32olaa/reward-scope
examples/cartpole_hacking_demo.py
.py
82f01f4aeda5d62c
7
0
""" Command-line interface for RewardScope. """ import click from pathlib import Path import sys @click.group() @click.version_option(version="0.1.0") def cli(): """RewardScope - RL Reward Debugging Tools""" pass @cli.command() @click.option('--port', default=8050, help='Dashboard port') @click.option('--d...
32olaa/reward-scope
reward_scope/cli.py
.py
01d1177fd3de2aa6
7
0
""" Adaptive Baseline Module (Experimental) Per-run adaptive baselines that learn "normal" behavior from the first N episodes of a training run, then flag deviations from this baseline. """ from typing import Dict, List, Optional, Any from dataclasses import dataclass, field import numpy as np from collections import...
32olaa/reward-scope
reward_scope/core/baselines.py
.py
6b7c456ed8ee1eea
7
0
""" Data Collector Module Stores training data in SQLite for persistence and fast querying. Supports real-time streaming to dashboard via WebSocket. """ from dataclasses import dataclass, field from typing import Dict, List, Optional, Any import sqlite3 import json import time from pathlib import Path import numpy as...
32olaa/reward-scope
reward_scope/core/collector.py
.py
0ad455361edc827d
7
0
""" FastAPI Dashboard Application Real-time web dashboard for RL training visualization. """ from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates import asyncio from pa...
32olaa/reward-scope
reward_scope/dashboard/app.py
.py
a2c860c025474c0c
7
0
""" Export utilities for RewardScope data. Provides functions to export alerts and episode history to JSON or CSV formats. """ from typing import List, Dict, Any, Optional import json import csv from pathlib import Path def export_alerts_to_file(alerts: List[Any], path: str, format: Optional[str] = None) -> None: ...
32olaa/reward-scope
reward_scope/utils/export.py
.py
9b60786bb95b052f
7
0
""" Screenshot automation helper for Modal LLM Evaluator This script helps automate taking screenshots of the Streamlit UI. Requires: playwright, pillow Install: pip install playwright pillow Setup: playwright install chromium """ import asyncio import os from pathlib import Path from playwright.async_api import asy...
McTosh1/modal-llm-evaluator
docs/images/take_screenshots.py
.py
e57cd691f2132c2f
7
0
""" Cost tracking and budget management for LLM evaluations """ from typing import Dict, List, Optional from dataclasses import dataclass, field from datetime import datetime @dataclass class CostEntry: """Single cost entry""" timestamp: datetime model: str provider: str input_tokens: int out...
McTosh1/modal-llm-evaluator
evaluator/cost_tracker.py
.py
09a054f13e912e73
7
0
""" Evaluation metrics for LLM outputs """ import re from typing import Dict, Any, List, Optional, Callable from difflib import SequenceMatcher class EvaluationMetrics: """Calculate various evaluation metrics for LLM outputs""" @staticmethod def exact_match(output: str, expected: str) -> bool: "...
McTosh1/modal-llm-evaluator
evaluator/metrics.py
.py
c1da73dda79ac3fe
7
0
""" Results storage and Power BI export functionality """ import json import pandas as pd from datetime import datetime from typing import List, Dict, Any, Optional from pathlib import Path import sqlalchemy class ResultsStorage: """Store and export evaluation results""" def __init__(self, experiment_name: ...
McTosh1/modal-llm-evaluator
evaluator/storage.py
.py
796561533e148136
7
0
""" Modal LLM Evaluator - Main orchestration engine This is the core Modal app that runs evaluations in parallel across multiple models and prompts. """ import modal import os from typing import List, Dict, Any, Optional from evaluator.providers import get_provider from evaluator.metrics import EvaluationMetrics from...
McTosh1/modal-llm-evaluator
main.py
.py
3928a812078e4d6c
7
0
""" Setup verification script Run this to check if your Modal LLM Evaluator is configured correctly. """ import sys def check_modal(): """Check if Modal is installed and configured""" print("[*] Checking Modal installation...") try: import modal print(f" [OK] Modal version: {modal.__vers...
McTosh1/modal-llm-evaluator
setup_check.py
.py
02cb128818d155cc
7
0
# pylint: disable=missing-docstring # pyright: reportUnboundVariable=false """ Installs ACME DNS01 challenges using dynamic DNS updates :depends: dnspython """ import logging import socket import time from contextlib import contextmanager try: import dns import dns.inet import dns.name import dns.que...
jgraichen/salt-acme
_modules/acme_dns.py
.py
f5580633b26fc6d1
7.24
2
""" Sign certificate signing requests (CSR) using the ACME execution module on the salt master. :depends: cryptography """ import fnmatch import logging import re import yaml _MISSING_MODULES = [] try: from cryptography import x509 from cryptography.hazmat.backends import default_backend except ImportError...
jgraichen/salt-acme
_runners/acme.py
.py
3b60c52c0e296275
7.24
2
from pathlib import Path from typing import Callable, Mapping, Any from pytoy.lib_tools.buffer_executor.protocol import BufferJobProtocol from pytoy.ui.ui_enum import get_ui_enum, UIEnum from pytoy.ui import PytoyBuffer class BufferJob: """Façade class for creating and managing buffer jobs across different UIs."...
Sillte/vim-pytoy
MEMORY/buffer_executor/buffer_job.py
.py
a8e547da9b24a50d
7
0
import inspect import functools import vim from pytoy.func_utils import PytoyVimFunctions class CommandManager: """Handling `Command!` for `vim` with `python`. Note ------- Requirements for `command`. Registration of `Command` is performed via `CommandManager.register`. Example ----...
Sillte/vim-pytoy
MEMORY/command_utils/__init__.py
.py
792794d33263df19
7
0
"""IPython Terminal NOTE: When you handle `vim.buffer`, you shoud be careful not to access at the same time. I wonder, they are not `thread-safe`? """ import vim import time import re from threading import Thread from queue import Queue, Empty from pytoy.infra.timertask import TimerTask from pytoy.ui.p...
Sillte/vim-pytoy
MEMORY/ipython_terminal.py
.py
becc089ad5b87077
7
0
import shlex from typing import Callable, Any import inspect from pytoy.shared.old_command.models import RangeCountOption, CommandFunction from pytoy.shared.old_command.models import RangeCountType from pytoy.shared.old_command._opts_converter import _OptsConverter from pytoy.shared.old_command._customlist_manager im...
Sillte/vim-pytoy
MEMORY/old_command/__init__.py
.py
3c38da8ab084e6e7
7
0
"""The role of `_OptsConverter` is the below two points. 1. convert the return of `opts` (Lua-like return of the command in neovim) so that the given `callable` can accept them as the argument. 2. Infer the options of `VimFunction` (such as nargs/count/range) or verify the values of them. When there is no specifica...
Sillte/vim-pytoy
MEMORY/old_command/_opts_converter.py
.py
fc3f5e9fe88deb12
7
0
from dataclasses import dataclass, field from enum import Enum from typing import Callable, Any, TypeAlias from pytoy.shared.lib.text import LineRange # Type alias for command functions (can be callable, classmethod, or staticmethod) CommandFunction: TypeAlias = Callable[..., Any] | staticmethod NARGS: TypeAlias = st...
Sillte/vim-pytoy
MEMORY/old_command/models.py
.py
590a20723ecec417
7
0
from .models import RangeCountOption, CommandFunction, NARGS from typing import Any, Protocol class ConverterProviderProtocol(Protocol): def condition( self, target: CommandFunction, nargs: NARGS | None, range_count_option: RangeCountOption, ) -> tuple[bool, str | int, RangeC...
Sillte/vim-pytoy
MEMORY/old_command/protocol.py
.py
588bd58e5a6c6216
7
0
"""Perform operations related to `Quickfix`. """ import os from pytoy.ui_utils import QuickFix from pytoy.git_utils.git_user import GitUser from pathlib import Path import vim class QuickFixFilter: """Filter `QuickFix`'s contents based on `context`.""" def __init__(self, location=None): self.locat...
Sillte/vim-pytoy
MEMORY/quickfix_handler.py
.py
8aa19b974b3235b1
7
0
""" This is currently not used (`2022/01/30`). Originally, this is intended to be used for `ipython`. However, due to handling of `<ctrl-c>`, vim's terminal is adopted (See `ipython_terminal`.) """ import subprocess import time from subprocess import PIPE from threading import Thread, Lock from queue import Queue,...
Sillte/vim-pytoy
MEMORY/sham_console.py
.py
8050bdf553ac94c8
7
0
from queue import Queue from pathlib import Path from typing import Mapping from .protocol import TerminalBackendProtocol, ApplicationProtocol, LineBufferProtocol class TerminalBackend(TerminalBackendProtocol): def __init__(self, impl: TerminalBackendProtocol): self._impl = impl @property def imp...
Sillte/vim-pytoy
MEMORY/terminal_backend/__init__.py
.py
95d81b436f3855bf
7
0
import sys from typing import Type, Sequence from .protocol import ApplicationProtocol, LINE_WAITTIME from .utils import force_kill class AppClassManagerClass: """Register and creation of the `Application` with` the given name.""" def __init__(self): self._app_types: dict[str, Type[ApplicationProtoco...
Sillte/vim-pytoy
MEMORY/terminal_backend/application.py
.py
4400e510bfed974a
7
0
from pytoy.lib_tools.terminal_backend.protocol import ( LineBufferProtocol, DEFAULT_LINES, DEFAULT_COLUMNS, ) import re # Comprehensive regex to remove ANSI escape codes and other common control characters. # This regex is designed to work with Python strings (Unicode). # It covers: # 1. CSI (Control Sequ...
Sillte/vim-pytoy
MEMORY/terminal_backend/line_buffers/line_buffer_naive.py
.py
dcfe4e2ce92215f0
7
0
import subprocess import sys import os # `import psutil` may take time. def find_children(parent_pid: int) -> list[int]: """Return the list of children process.""" import psutil try: parent = psutil.Process(parent_pid) return [elem.pid for elem in parent.children(recursive=True)] exce...
Sillte/vim-pytoy
MEMORY/terminal_backend/utils.py
.py
b71a34d781ab90d5
7
0
from pytoy.tty_executor.impls.process_utils import force_kill from pytoy.tty_executor.models import ConsoleSnapshot, WaitOperation, InputOperation from pytoy.tty_executor.protocol import TTYApplicationProtocol from typing import Sequence class ShellApplication(TTYApplicationProtocol): WIN_DEFAULT_SHELL_COMMAND ...
Sillte/vim-pytoy
MEMORY/tty_executor/applications.py
.py
06ed3383345136c1
7
0
def force_kill(pid: int, timeout: float = 1.0): import psutil try: proc = psutil.Process(pid) # 子プロセスを再帰的に取得(新しい順で処理が安全) children = proc.children(recursive=True) for child in children: try: child.terminate() except Exception: ...
Sillte/vim-pytoy
MEMORY/tty_executor/impls/process_utils.py
.py
63b37fab826d6ad4
7
0
import argparse import json from pathlib import Path def open_json(fp): """ Open a JSON file and return the object :param fp: The path to the object :return: The dictionary object """ with open(fp, mode="r", encoding="utf-8") as open_file: obj = json.load(open_file) return obj d...
MoTrPAC/motrpac-atac-seq-pipeline
src/merge_jsons.py
.py
a0f6c38e9d339f9b
7.3
3
""" Extract transcription start sites from an Ensembl GTF. Used to create the TSS reference file used in ~/ATAC_PIPELINE/atac-seq-pipeline/scripts/build_genome_data.sh Usage: python tss_from_gtf.py <gtf_file> <tss_outfile> Supports both compressed (.gz) and uncompressed GTF files. Output will be gzipped if the ou...
MoTrPAC/motrpac-atac-seq-pipeline
src/tss_from_gtf.py
.py
0492e2e73af8119a
7.3
3
import logging import ipywidgets as widgets from IPython.display import display DEFAULT_FORMAT = '%(asctime)s - [%(levelname)s] %(message)s' class OutputWidgetHandler(logging.Handler): """ Custom logging handler sending logs to an output widget """ def __init__(self, *args, **kwargs): super(Output...
farfarfun/funtool
funtool/log/log_widget.py
.py
5747469dea1e7dac
7
0
import datetime import logging import time from notetool.tool.log import logger logger.setLevel(logging.DEBUG) _DAY_SECOND = 24 * 60 * 60 _HOUR_SECOND = 60 * 60 _TEN_MINUTE_SECOND = 10 * 60 _MINUTE_SECOND = 60 class WorkTime: def __init__(self): pass @staticmethod def time_to_end(time_str=Non...
farfarfun/funtool
funtool/time/core.py
.py
cb1e85b8da12d288
7
0
import gzip import os import tarfile import zipfile """ # gz: 即gzip。通常仅仅能压缩一个文件。与tar结合起来就能够实现先打包,再压缩。 # tar: linux系统下的打包工具。仅仅打包。不压缩 # tgz:即tar.gz。先用tar打包,然后再用gz压缩得到的文件 # zip: 不同于gzip。尽管使用相似的算法,能够打包压缩多个文件。只是分别压缩文件。压缩率低于tar。 # rar:打包压缩文件。最初用于DOS,基于window操作系统。 """ def un_gz(file_path, target_path=None): """ ung...
farfarfun/funtool
funtool/tool/compress.py
.py
9f6b536f761bb886
7
0
import datetime import xml.dom.minidom from io import BytesIO basestring = str # Could make this the base class; will need to add 'publish' class WriteXmlMixin: def write_xml(self, outfile, encoding="UTF-8"): from xml.sax import saxutils handler = saxutils.XMLGenerator(outfile, encoding) ...
farfarfun/funtool
funtool/tool/pyrss.py
.py
4cfeb69d2b9ac2de
7
0
"""Ambush: the turtle, moved to where the traffic is. Round one's turtle put its five units on the edges and the corners and was never found, which is a way of not losing and no way of winning. The same five units stand in the middle here, two squares apart so that nothing can reach two of them in one step, on the squ...
aburston/board_game_concept
matches/bots/ambush.py
.py
cb9288874de96d0c
7.15
1
"""Assassin: attack 10, health 1 - kills anything it touches, dies to anything. The bet: a round of combat is simultaneous (R5.2) and ceil(health / attack) decides it, so attack 10 destroys any unit in the game in one round. At 32 points a piece these trade one-for-one against anything, including a champion that cost ...
aburston/board_game_concept
matches/bots/assassin.py
.py
7008d682cd64d36a
7.15
1
"""Attrition: buy energy, not statistics, and keep hunting to the last point. What the first five games taught: a unit stops being a unit the moment it cannot afford to walk, and every army in round one froze around turn fifteen with its statistics intact and its pockets empty. Energy is the game. It is also the cheap...
aburston/board_game_concept
matches/bots/attrition.py
.py
a8fd470dd5c0cbec
7.15
1
"""Bulwark: a wall across the frontier, and two swords behind it. A wall is attack 0 and energy 0 - ten health standing on a square for ten points, which can never move, never strike and never rest. Ten of them laid along the frontier row close the board: an enemy that wants into this half has to break one, and breaki...
aburston/board_game_concept
matches/bots/bulwark.py
.py
8bf1cdbb90f0531d
7.15
1
"""What every bot needs, and nothing about any particular strategy. A bot is handed one thing: the view its own player is published (R6.4). These helpers only ever read that view. """ DIRECTIONS = {'north': (0, -1), 'south': (0, 1), 'east': (1, 0), 'west': (-1, 0)} STEP = {step: name for name, step in D...
aburston/board_game_concept
matches/bots/common.py
.py
c73acc382f02445a
7.15
1
"""Drain: the sponge with the legs to reach everybody. Game 38 showed the shape of the idea and the flaw in the first cut: sponges took ten energy off every camper that killed one, but only five of the twelve had the energy to reach a camper at all, so the camp finished the game half drained and entirely intact. This...
aburston/board_game_concept
matches/bots/drain.py
.py
bd609de423182763
7.15
1
"""Duellist: two champions that win every fight, and a scout to find them one. Attack 10 destroys any unit in the game in a single round (health stops at 10), so a champion never loses a duel it does not tie. What it cannot do is find anybody: at ten energy a round it can afford three fights, and every step it takes l...
aburston/board_game_concept
matches/bots/duellist.py
.py
4e0d7595c5ac0435
7.15
1
"""Grinder: three units of ten health that kill by attrition. The bet: energy spent to kill an enemy is about its health, whatever your attack (a x ceil(h/a)), so attack 1 is the cheapest killer there is against small units - and ten health absorbs ten separate attackers. Three of these can absorb thirty attacks and p...
aburston/board_game_concept
matches/bots/grinder.py
.py
acb2c57b14839cd5
7.15
1
"""Hunter: two champions with thirty energy each, quartering the board. The bet: attack 10 wins every duel it does not tie, ten health survives ten small attackers, and thirty energy is both the search range to find an enemy who is hiding and the three kills to finish them. The weakness it accepts: two units means tw...
aburston/board_game_concept
matches/bots/hunter.py
.py
bb62b79653f1d6e3
7.15
1
"""Marathon: the same hunt, with enough points to pay for the walking. This is the control on what ten undecided games suggested: that nobody loses on a ten by ten board for a hundred points because searching it costs more energy than a hundred points can buy. Same doctrine as Attrition - health 10, attack 1, sweep a ...
aburston/board_game_concept
matches/bots/marathon.py
.py
ec317b09e6e82047
7.15
1
"""Marksman: the control, run properly. Marathon tested whether a bigger budget breaks a camp and answered no, but it answered the wrong question: at attack 1 against health 10 it killed its enemies by dying on them. This is the same 400-point budget with the one statistic that matters put right. Attack 5 kills a ten-...
aburston/board_game_concept
matches/bots/marksman.py
.py
78ca7d3f9188ed37
7.15
1
"""Nomad: three runners that never fight and are never caught. A game is decided when one player has nothing standing (R7.2), so a unit that survives is a veto on losing. These are the cheapest units that can keep moving for thirty turns, and their doctrine is to spend that on being somewhere else: a unit is only foun...
aburston/board_game_concept
matches/bots/nomad.py
.py
a950e506daae6afa
7.15
1
"""Phalanx: one rank of five, advancing in step. The bet: a line abreast sweeps a five-wide corridor without ever leaving a gap, and five units of five health are hard for small attackers to chew through while being numerous enough to survive a champion or two. The weakness it accepts: a rank is a compromise - too sh...
aburston/board_game_concept
matches/bots/phalanx.py
.py
1f581840793d986d
7.15
1
"""Reaper: two champions carrying almost nothing but energy. What the split board changes is that hunting is affordable: an enemy is somewhere in fifty squares rather than a hundred, and it is not going to be behind you. What two hundred points changes is that you can buy the energy to do the hunting and the killing o...
aburston/board_game_concept
matches/bots/reaper.py
.py
23e555514aaa1244
7.15
1
"""Sponge: units bought to be attacked, not to attack. The idea is that energy is something you can take off an opponent rather than only something they spend: a defender pays its attack value every round of every fight it is in, and goes on paying until one side is destroyed. So: ten health, and almost no energy. Let...
aburston/board_game_concept
matches/bots/sponge.py
.py
75a55d26f0d3d891
7.15
1
"""Swarm: buy the most bodies the budget allows and sweep abreast. The bet: the game is won by the last player with *anything* standing (R7.2), so the cheapest thing that can walk and hit is the most win-conditions per point. Nine bodies at 11 points each, walking south in nine lanes, search the whole board in nine tu...
aburston/board_game_concept
matches/bots/swarm.py
.py
f399f8515709498e
7.15
1
"""Tide: the swarm again, with the legs it was missing. Round one's swarm was nine bodies with nine energy: eight steps and one punch. It found the enemy, traded three of itself for one point of damage, and then stood still for forty turns. This is the same idea with a third more energy each, one body fewer, and no re...
aburston/board_game_concept
matches/bots/tide.py
.py
c8d18086bc6a28a3
7.15
1
"""Turtle: five units that never move, and are therefore never seen. The bet: an enemy is invisible until it is fought (R6.2), so a unit that never moves is a hidden square somebody has to step on to find. Energy is only spent by moving and attacking, so a unit that never moves keeps all ten points of its energy for t...
aburston/board_game_concept
matches/bots/turtle.py
.py
80df0e7f93f06369
7.15
1
"""Completing a line that is being typed. Everything here answers one question - given what has been typed so far, what words could come next - and answers it from the same two places the session answers every other question from: the grammar in `grammar.py`, and the role's table in `roles.py`. A word is offered only ...
aburston/board_game_concept
src/board_game_concept/cli/complete.py
.py
ff00e4217ba45c2f
7.15
1
"""The language the three roles share. One grammar, described once. Which parts of it a given role may use is a separate question, answered by `roles.py`; how a line is read is answered by `parser.py`. Keeping the vocabulary here means `help` can be generated from the same description the parser works to, rather than ...
aburston/board_game_concept
src/board_game_concept/cli/grammar.py
.py
9642e61d7e069414
7.15
1
"""What `help` prints. Generated from the grammar and the role's own table, so it lists what the role will actually accept. The three roles used to keep their own hand-written block, which is why they had drifted from the commands they took. """ from .grammar import USAGES def usages_for(role): """The commands ...
aburston/board_game_concept
src/board_game_concept/cli/help.py
.py
14d9ddfc30a76ddd
7.15
1
"""Turning what a `show` command has to say into the text a terminal shows. Layout only. What there is to say is `views.py`'s answer, and this module decides how it sits on the page: which columns, in what order, padded to what width. Plain ASCII throughout - no colour and no box drawing - so the same text reads in a ...
aburston/board_game_concept
src/board_game_concept/cli/render.py
.py
14fd16d0d3ee291c
7.15
1
"""Which part of the grammar each role may use. The parser reads the whole language whatever the caller is; what a caller is allowed to *do* is decided here, in one table, rather than by each session loop checking for itself. That is what keeps the three roles honest about their differences: the observer is read-only ...
aburston/board_game_concept
src/board_game_concept/cli/roles.py
.py
939144920ddc7284
7.15
1
"""The parts of an interactive session that all three roles share. What each role does with a command differs, and so does the shape of its loop - the server runs unattended once setup is over, the client waits for its turn, the observer only ever reads. What they have in common is how a line becomes a command, how a ...
aburston/board_game_concept
src/board_game_concept/cli/session.py
.py
68a96b2e70d0ecbc
7.15
1
"""Answering a `show` command, once, for whichever role asked. The three roles used to hold a copy each of the same ladder of subjects, and the copies had drifted: two of them printed pending orders by interpolating a raw dictionary, and all three printed the storage YAML as though it were display. There is one ladder...
aburston/board_game_concept
src/board_game_concept/cli/show.py
.py
f86df7f58aef607c
7.15
1
"""What a player has spent of their point budget, and what they may still buy. One module, asked by both of the places a unit can reach the board: the client's `add unit`, which refuses, and the turn's resolution, which rejects. Two enforcers restating the arithmetic would be two rules as far as a player reading the t...
aburston/board_game_concept
src/board_game_concept/domain/budget.py
.py
3689480e07af4b8d
7.15
1
"""What happened while a turn was resolved. Resolution used to narrate itself to stdout behind a debug flag, which meant the only way to find out what a turn had done was to edit the source and run it again. It reports these instead: `Board.commit` returns them in the order they happened, and the caller decides whethe...
aburston/board_game_concept
src/board_game_concept/domain/events.py
.py
9c3fc7e362986cb2
7.15
1
class Player: """One player of a game, known by their number. The range is stated here rather than by whoever registers a player, because a number arrives by more than one door: typed at the server prompt, read from a player configuration file, and read back from a game on disk. A check at any one ...
aburston/board_game_concept
src/board_game_concept/domain/player.py
.py
922b2427e16e2b4b
7.15
1
from .square import Empty from .events import Event from .player import Player # Unit # name: One or more character # symbol: One single character # attack: damage per attack # health: total amount of health class UnitType: NONE = 0 NORTH = 1 EAST = 2 SOUTH = 3 WEST = 4 INITIAL = 0...
aburston/board_game_concept
src/board_game_concept/domain/unit.py
.py
09479faad7846fb2
7.15
1
"""What a `show` command has to say, before anyone has decided how to say it. One function per subject, each returning plain data - lists of dicts, and for the board a dict of dimensions and rows. Nothing here prints, and nothing here knows whether the answer is going out as a table or as JSON. That is the whole point...
aburston/board_game_concept
src/board_game_concept/http/views.py
.py
ab179ae48016e863
7.15
1
#!/usr/bin/env python3 """ Video merging functionality for lecture_downloader package. """ import os import json import asyncio import tempfile import subprocess from typing import List, Dict from .utils import natural_sort_key, format_module_name_with_padding, get_video_duration, get_ffmpeg_exe def _print_merge_ma...
lightkey2/lecture-downloader
lecture_downloader/merger.py
.py
ede2ada0f944aa12
7.15
1
#!/usr/bin/env python3 """ Pipeline functionality for lecture_downloader package. Orchestrates the complete workflow: download -> merge -> transcribe. """ import os import asyncio from typing import Dict, List, Optional, Union from .merger import _merge_all_modules_async, _print_merge_mapping from .transcriber import...
lightkey2/lecture-downloader
lecture_downloader/pipeline.py
.py
5a50d16dd0663216
7.15
1