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 |
|---|---|---|---|---|---|---|
"""
Class to hold information for one material and allow calculation
of x-ray and neutron SLDs for different applications.
"""
from numpy import array, pi
from ..utils.chemical_formula import Formula
from .constants import (Cu_kalpha, E_to_lambda, Mo_kalpha, dens_D2O, dens_H2O, fm2angstrom, muB, r_e, r_e_angstrom,
... | reflectivity/orsopy | orsopy/slddb/material.py | .py | be6ba316584af6ef | 7 | 0 |
import datetime
import json
import os
import pathlib
import ssl
import warnings
from urllib import parse, request
from urllib.error import URLError
from . import DB_FILE, SLDDB
from .dbconfig import WEBAPI_URL
from .element_table import get_element
from .material import Formula, Material
class SLD_API:
"""
... | reflectivity/orsopy | orsopy/slddb/webapi.py | .py | 7a2fc76503d616ba | 7 | 0 |
"""Device facts and slow device queries, kept off the hot loop.
v1 called `adb shell dumpsys input_method` synchronously inside the main loop. Measured on
this machine it takes 0.08-0.11s, so every check stalled the loop for ~10 frames. Worse,
v1's 2-second throttle only advanced when the keyboard was actually found, ... | 1tzkaos/PoGoBot | pogobot/device.py | .py | a28d602df42a0426 | 7 | 0 |
"""What a state handler is allowed to ask for.
Handlers are pure: they return a list of Effects and never touch adb, disk, or globals.
The runner is the single place that applies dry-run, rate limits, and tracing - which is
why `--no-click` cannot leak here (the v1 bot checked it at 5 of 10 actuation sites).
All coor... | 1tzkaos/PoGoBot | pogobot/effects.py | .py | d1d4723d1274aaed | 7 | 0 |
"""Frame transport: every frame carries identity and age so staleness is expressible."""
from __future__ import annotations
import time
from dataclasses import dataclass
from typing import Optional, Protocol
import numpy as np
@dataclass(frozen=True)
class Frame:
"""A single captured frame.
`seq` and `ts`... | 1tzkaos/PoGoBot | pogobot/frames.py | .py | a6e3c5cada0e82c3 | 7 | 0 |
"""What the bot believes about the current frame.
Two rules drive this module:
1. Every optical test reports a *fraction of its ROI area*, never an absolute pixel
count. The old code used counts on ROIs that scale with `--max-size`; measured on a
real device frame, `orange_bino` was 5406 px at 1080x2340 but 479... | 1tzkaos/PoGoBot | pogobot/observation.py | .py | 4553c69218aa937c | 7 | 0 |
"""The preview window must never show an un-annotated frame.
Regression: the throttled branch called `_show(..., obs=None)`, which rendered the bare
frame. That path runs on every loop iteration (capped only by `cv2.waitKey(1)`, so ~1 kHz)
while the HUD was rendered once per inference at 8 Hz, so the overlay was visib... | 1tzkaos/PoGoBot | tests/test_display.py | .py | e82c835003c7990d | 7.5 | 0 |
"""A Gym screen wedged the bot with its close X located the whole time.
Unlike the "NEW LEVEL UNLOCKS" screen (see test_perception_level_unlocks.py), the locator
was never the problem here: `find_close_button` returned (0.500, 0.890) on every frame.
What failed was the gate in front of it. `x_button_signal` measured m... | 1tzkaos/PoGoBot | tests/test_perception_gym_close.py | .py | d58b84c2aabfe99a | 7.5 | 0 |
"""The "NEW LEVEL UNLOCKS" screen (a reward card on a blue backdrop, closed by a round X
low-centre) wedged the bot on the real device.
Unlike the level-up screen, every signal here was already correct: the classifier reads
Menu @ 0.94, `x_button_signal` reads True, so `in_overlay` routed to POPUP exactly as
designed.... | 1tzkaos/PoGoBot | tests/test_perception_level_unlocks.py | .py | 4d5a5e6a173c43e7 | 7.5 | 0 |
# endcoding: utf-8
import math
import os
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import PIL
import scipy.special
class Shape:
def __init__(
self,
name,
position,
control_pts,
n_control_pts,
n_sampling_pts,
radius,
edgy,
... | farfarfun/funfluid | src/funfluid/lbm/core/shape.py | .py | 6cc69a30fe64d780 | 7 | 0 |
import numba as nb
from numba import jit
@jit(nopython=True, parallel=True, cache=True)
def nb_equilibrium(u, c, w, rho, g_eq):
"""计算速度项 Compute velocity term"""
v = 1.5 * (u[0, :, :] ** 2 + u[1, :, :] ** 2)
# 计算平衡 Compute equilibrium
for q in nb.prange(9):
t = 3.0 * (u[0, :, :] * c[q, 0] + u... | farfarfun/funfluid | src/funfluid/lbm/core/speed_nb.py | .py | aedce1f98d4f0a3b | 7 | 0 |
# Copyright (c) 2023 Javad Komijani
"""This is a module for defining actions related to Ginibre Ensemble."""
import torch
import numpy as np
from ..lib.linalg import haar_sqr # special qr (sqr) decomposition
class GinibreGaugeAction:
r"""An action with two pieces for seperate handling of the Q and R
matri... | jkomijani/normflow | src/normflow/action/ginibre_gauge_action.py | .py | 088449dc420890f9 | 7.3 | 3 |
# Copyright (c) 2023 Javad Komijani
"""This is a module for including the determinant of fermion propagators."""
import torch
from fermionic_tools.staggered import dirac_dagger_dirac_operator
class LogDetAction:
"""
The effective action corrresponding to deteriminat of fermion propagators
as:
.. ... | jkomijani/normflow | src/normflow/action/logdet_action.py | .py | 937a3dd363ceb02f | 7.3 | 3 |
# Copyright (c) 2021-2025 Javad Komijani
"""This is a module for defining matrix models..."""
import math
import torch
class MatrixAction:
"""
Matrix action defined as `S = (β/N) ReTr[I - f(X)]` for N×N matrix X.
Args:
beta (float): Coupling constant `β` in the action.
func (callable, ... | jkomijani/normflow | src/normflow/action/matrix_action.py | .py | 9a09859db64ffac9 | 7.3 | 3 |
# Copyright (c) 2026 Javad Komijani
"""This is a module for defining U(1) models..."""
import torch
class PhasorAction:
"""
Phasor action defined as `S = β Re[1 - f(X)]` for a U(1) variable X.
Unlike MatrixAction, X is a plain complex phasor with no matrix structure.
Args:
beta (float): C... | jkomijani/normflow | src/normflow/action/phasor_action.py | .py | df154c3e8ab60e80 | 7.3 | 3 |
# Copyright (c) 2023 Javad Komijani
"""This is a module for Schwinger model's actions..."""
import torch
from .gauge_action import U1GaugeAction
from .logdet_action import LogDetAction
from fermionic_tools.staggered import dirac_dagger_dirac_operator
class SchwingerAction(U1GaugeAction):
r"""The action for Sc... | jkomijani/normflow | src/normflow/action/schwinger_action.py | .py | fca6abc23918b783 | 7.3 | 3 |
# Copyright (c) 2021-2022 Javad Komijani
"""A module for expanding `torch.arange` to higher dimension."""
import torch
def arange_like(x, dim=-1):
"""Return a tensor with shape of `x`, filled with `(0, 1, ..., n)` in the
`dim` direction, where `n = x.shape[dim]`, and repeated in all other
directions.
... | jkomijani/normflow | src/normflow/lib/indexing/arange.py | .py | b8ce484aa12e8011 | 7.3 | 3 |
# Copyright (c) 2022-2025 Javad Komijani
"""
SU(3) phase grid utilities.
Provides a class to generate SU(3) phase mesh grids and compute joint
and marginal probability distributions given a user-defined action.
"""
# pylint: disable=invalid-name
import math
import torch
__all__ = ["SU3PhaseGrid", "su3_phase_margi... | jkomijani/normflow | src/normflow/lib/matrix_handles/su3_eigenphase.py | .py | b1681d9b2fc432c2 | 7.3 | 3 |
# Copyright (c) 2021-2022 Javad Komijani
"""This module is for curve fitting using pytorch
**NOTE** this package will change....
"""
import torch
import time
class CurveFitter:
"""
Parameters:
-----------
net: torch.nn.Module
"""
def __init__(self, net):
self.net = net
sel... | jkomijani/normflow | src/normflow/lib/optim/curvefit.py | .py | 98bfa07ada740a88 | 7.3 | 3 |
# Copyright (c) 2021-2022 Javad Komijani
import torch
import numpy as np
from functools import partial
class Resampler:
"""
Resample the data with bootstrap or jackknife method.
Parameters
----------
method : str, optional
The method of resampling (default is bootstrap)
"""
def ... | jkomijani/normflow | src/normflow/lib/stats/resampler.py | .py | 35d69fa7f12eb8d0 | 7.3 | 3 |
# Copyright (c) 2021-2023 Javad Komijani
"""This module includes utilities for masking inputs.
Each mask must have three methods:
1. split (to partition data to two parts),
2. cat (to put the partitions together),
3. purify (to make sure there is no contamination from other partition).
"""
import torch
... | jkomijani/normflow | src/normflow/mask/double_mask.py | .py | 9d76824fbcbbc87e | 7.3 | 3 |
# Copyright (c) 2021-2023 Javad Komijani
"""This module includes utilities for masking inputs.
Each mask must have three methods:
1. split (to partition data to two parts),
2. cat (to put the partitions together),
3. purify (to make sure there is no contamination from other partition).
"""
import torch
i... | jkomijani/normflow | src/normflow/mask/mask.py | .py | c12c1d2dcd35d478 | 7.3 | 3 |
# Copyright (c) 2021-2024 Javad Komijani
"""This module includes utilities for masking inputs.
Each mask must have three methods:
1. split (to partition data to two parts),
2. cat (to put the partitions together),
3. purify (to make sure there is no contamination from other partition).
"""
import torch
i... | jkomijani/normflow | src/normflow/mask/matrix_mask.py | .py | e8e68cf2e14f64dd | 7.3 | 3 |
"""轻量级冒烟测试套件(smoke tests)。
该仓库(farfarfun/funtask)此前没有任何 tests/ 目录。
注意命名坑:仓库名是 funtask,但实际 Python 导入名是 nlttask(历史遗留命名不一致)。
这些测试只做最基础的“能不能跑起来”的验证:
- 顶层包 / 子模块能否正常 import
- 核心公开类/函数用简单参数调用是否报错
- 任何会连接真实数据库/发起真实 shell 调用的地方都用 mock 隔离
已知问题(发现但按要求不在本测试任务中修复,见注释 / 最终汇报):
1. `nlttask.models.task_model` 在模块导入时就会以相对路径 "sqlite... | farfarfun/funtask | tests/test_smoke.py | .py | 6e0028844ea2a917 | 7.5 | 0 |
"""Asynchronous Python client providing Open Data information of Eindhoven."""
from __future__ import annotations
import asyncio
import socket
from dataclasses import dataclass
from importlib import metadata
from typing import Any, Self
from aiohttp import ClientError, ClientSession
from aiohttp.hdrs import METH_GET... | klaasnicolaas/python-eindhoven | src/eindhoven/eindhoven.py | .py | abfdf6865daec4ae | 7.3 | 3 |
"""Models for Open Data Platform of Eindhoven."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from enum import StrEnum
from mashumaro import field_options
from mashumaro.config import BaseConfig
from mashumaro.mixins.orjson import DataClassORJSONMixin
c... | klaasnicolaas/python-eindhoven | src/eindhoven/models.py | .py | abae791ef65db7f2 | 7.3 | 3 |
"""Emit the JSON bundle the web app (docs/) reads.
One file per division. Contains current standings with event breakdowns,
projection odds + per-position histograms, and everything the client-side
cutline-replay what-if needs: per-sim cutlines, per-event score-distribution
stats, per-place points curves, and each pla... | dgoodenough/discgolf | dgpt/export.py | .py | 9b94645b4ec4fbfa | 7.15 | 1 |
"""Project who plays each remaining event.
Priority order:
1. Manual overrides (data/overrides/fields.csv: tournament_id,pdga_number,plays)
2. The real registered field from PDGA Live, once the event is loaded there
(usually a few days out): round 1 exists with the full player list.
3. Participation rates from this... | dgoodenough/discgolf | dgpt/fields.py | .py | f1fdbf44fb6237f3 | 7.15 | 1 |
"""Publish-gate sanity checks on live-event data (flag loudly, never block).
Every wrong live number this season shipped through a gap that was visible at
ingest: the Jomez leaderboard inversion (b4cfb56) put the model's reconstructed
totals in a different order than the sheet's own authoritative RunningPlace.
These c... | dgoodenough/discgolf | dgpt/invariants.py | .py | 78d90b50d78d629b | 7.15 | 1 |
"""Cheap change-detector for the frequent live cron.
Runs before the heavy refresh (no numpy) and decides whether anything worth
re-simulating has changed since last time: a live event's scores moved, or an
event's completed/live status flipped. If nothing changed it signals a skip,
so the 15-minute cron effectively i... | dgoodenough/discgolf | dgpt/livecheck.py | .py | ac09496536d5f710 | 7.15 | 1 |
"""2026 DGPT points engine.
Base per-place curves (MPO/FPO, Elite Series scale where a win = 150) are
scaled by straight class multipliers. Ties: every tied player receives the
mean of the points for the places the tie group occupies (e.g. two players
T2 each get (125 + 115) / 2 = 120). The Preserve doubles event awar... | dgoodenough/discgolf | dgpt/points.py | .py | d7297daaa4d4b2c4 | 7.15 | 1 |
"""Current official player ratings (PDGA publishes an update roughly monthly).
Event results carry the rating a player HELD when they played, so a standings
table built purely from results goes stale the moment PDGA publishes a new
ratings batch — a player's model rating wouldn't move until their next start.
This modu... | dgoodenough/discgolf | dgpt/ratings.py | .py | f8a3045abcbe5407 | 7.15 | 1 |
"""Build the 2026 points-eligible schedule from the PDGA API.
Elite Series events are tier=ES with the class encoded in the event name
(DGPT- / DGPT+ / DGPT Playoffs / Powerball Cup / Doubles). Pro Majors are
tier=M. JomezPro Series events are found by name (they carry 'JomezPro' in
their PDGA listing).
"""
from __fut... | dgoodenough/discgolf | dgpt/schedule.py | .py | 409311149c6871c7 | 7.15 | 1 |
"""Append-only prediction snapshots for end-of-season backtesting.
Each refresh records the model's current probabilities per player so the
forecast can be scored later (Brier, log-loss, calibration) against the
actual outcomes, which are derivable from the final standings.
Cadence: at most one snapshot per calendar ... | dgoodenough/discgolf | dgpt/snapshot.py | .py | fa5fbf274eba7a1a | 7.15 | 1 |
"""Compute current-season DGPT World Standings from actual results."""
from __future__ import annotations
import csv
from collections import defaultdict
from . import config, live_api, points, ratings, schedule
def _doubles_points(results: list[dict], division: str, tid: int) -> dict[int, dict]:
"""Points earne... | dgoodenough/discgolf | dgpt/standings.py | .py | c133e3dc064f6bb1 | 7.15 | 1 |
"""Continuous validation: diff our computed standings against StatMando.
StatMando administers the official points, so any mismatch means either our
engine drifted (rule change, payload change, new edge case) or their site is
mid-update. Run after the weekly refresh:
python -m dgpt.validate
Exit 1 if any matched... | dgoodenough/discgolf | dgpt/validate.py | .py | d22baa7888a07fe4 | 7.15 | 1 |
"""Capture raw PDGA live-API payloads into tests/fixtures/payloads/.
Each file is the COMPLETE, unmodified API response (the {"data": ...}
envelope), so tests can serve it straight through a mocked live_api._get.
Re-run after adding an event to EVENTS to (re)capture its sheets:
python tests/fixtures/capture.py
C... | dgoodenough/discgolf | tests/fixtures/capture.py | .py | 59293d3bd8f428c8 | 7.65 | 1 |
"""The publish-gate invariant checks must flag exactly the failure signatures
this season actually produced — and stay quiet on clean data."""
from __future__ import annotations
from dgpt import invariants, live_api
from .conftest import event_payload, load_payload, round_payload, row
JOMEZ = 100195
def _serve(fake... | dgoodenough/discgolf | tests/test_invariants.py | .py | bdb46e9d4871fc49 | 7.65 | 1 |
"""livecheck is the live loop's gate: its signature must move when a live
score moves and hold still when nothing changed — a wrong 'unchanged' here is
exactly the silent-stale failure mode.
Each production check runs in a fresh process, so the per-process fetch memo
is cleared between signature() calls to match.
"""
... | dgoodenough/discgolf | tests/test_livecheck.py | .py | 52d34c9a95b0021c | 7.65 | 1 |
"""Divisions smaller than the qualification constants, and empty ones.
FPO's rules admit 4 players on the MVP-performance path and seat 18 by
points. Nothing guaranteed the division actually held that many: the
performance paths index into the player axis with np.partition, so a field
below the constant raised `IndexE... | dgoodenough/discgolf | tests/test_small_division.py | .py | 1fb38c00e0a6eae1 | 7.65 | 1 |
"""End-to-end smoke: the real pipeline over the tiny world, network mocked.
Runs everything a production refresh runs below schedule.build() — standings,
simulate.run (the c287e19 shadowing crash lived at its entry), export,
snapshot, movers, invariants — and asserts structural truths of the output
rather than exact o... | dgoodenough/discgolf | tests/test_smoke.py | .py | 44f304522241f28a | 7.65 | 1 |
from typing import TypedDict, List, Dict, Optional, Any, Callable, Union
from collections.abc import Iterable
import structlog
import pandas as pd
from .reader_fs import DsReaderFs
from .reader_s3 import DsReaderS3
from .normalize_instructions import normalize_instructions
class ChannelInstruction(TypedDict):
c... | pureskillgg/dsdk | pureskillgg_dsdk/ds_io/game_ds_loader.py | .py | 83325351bf08f70b | 7.24 | 2 |
import asyncio
import sys
from aiobotocore.session import get_session
from .exceptions import DeleteMessage
from .message_translators import SqsJsonMessageTranslator
DEFAULT_OPTIONS = {
"WaitTimeSeconds": 20,
"MaxNumberOfMessages": 1,
"MessageSystemAttributeNames": ["All"],
"MessageAttributeNames": [... | pureskillgg/dsdk | pureskillgg_dsdk/sqs/consumer.py | .py | d4d68efb8cce5b82 | 7.24 | 2 |
import abc
import rapidjson
class AbstractMessageTranslator(abc.ABC):
"""Base class for SQS message translators.
A translator converts a raw SQS message dict into a
``{"content": <payload>, "metadata": <fields>}`` mapping. ``content`` is
passed as the first argument to the consumer's handler and ``m... | pureskillgg/dsdk | pureskillgg_dsdk/sqs/message_translators.py | .py | 76831a770056153b | 7.24 | 2 |
import os
from glob import glob
import structlog
from ..ds_io import DsReaderFs, GameDsLoader
from .loader import TomeLoader
from .scribe import TomeScribe
from .manifest import TomeManifest
from .writer_fs import TomeWriterFs
from .reader_fs import TomeReaderFs
from .constants import filter_ds_reader_logs, warn_if_in... | pureskillgg/dsdk | pureskillgg_dsdk/tome/header_tome.py | .py | b827e464c929a158 | 7.24 | 2 |
import structlog
import pandas as pd
class TomeLoader:
def __init__(self, *, reader, has_header=True, log: object = None):
self._reader = reader
self._log = log if log is not None else structlog.get_logger()
self._manifest = None
self._metadata = None
self._exists = None
... | pureskillgg/dsdk | pureskillgg_dsdk/tome/loader.py | .py | 1986a4e1fcbf25b0 | 7.24 | 2 |
"""Exceptions for the csgo dsdk"""
from typing import List
class UnsupportedChannelStructure(Exception):
"""Exception raised for missing a column"""
class MissingColumns(UnsupportedChannelStructure):
"""Exception raised for missing a column"""
def __init__(self, message: str, /, *, columns: List[str])... | pureskillgg/csgo-dsdk | pureskillgg_csgo_dsdk/errors/channel_structure.py | .py | e104e0a1ea667b10 | 7.39 | 5 |
"""
Scrub PII from your data
"""
# pylint: disable=invalid-name
# pylint: disable=c-extension-no-member
from typing import Dict, Union
from numbers import Number
import dateutil.parser
import rapidjson
REDACTED = "redacted"
SCRUB_CSDS_PII_CHANNEL_INSTRUCTIONS = [
{"channel": "player_name"},
{"channel": "hea... | pureskillgg/csgo-dsdk | pureskillgg_csgo_dsdk/scrubber/scrub_pii.py | .py | 52b6790d2e8b9855 | 7.39 | 5 |
"""Man-page-style profile card. Registers on import.
Opts into the Steam prerequisite fetch via `needs_steam=True` and adds an
`extra_markers` entry for heatmap axis labels (unused by the glass card).
"""
from profile_card.cards._shared import (
CardContext,
CardStyle,
common_github_placeholders,
comm... | Jekwwer/Jekwwer | profile_card/cards/man.py | .py | a0a77aa43293adaf | 7.24 | 2 |
"""Public runtime config loader.
Reads `config.json` at the repo root — holds committed, non-secret values
(username, public links, Steam ID). Secrets (`GITHUB_TOKEN`, `STEAM_API_KEY`)
stay in env vars.
"""
import json
from pathlib import Path
from typing import TypedDict
CONFIG_PATH = Path("config.json")
class Li... | Jekwwer/Jekwwer | profile_card/config.py | .py | b86216daf3051ee9 | 7.24 | 2 |
#!/usr/bin/env python3
import json
import os
import sys
from typing import List
VALID_BLOCKS = ["implementation", "remediation", "rollback"]
def _normalize_newlines(value: str) -> str:
"""Normalize CRLF/CR line endings to LF for consistent storage."""
return value.replace('\r\n', '\n').replace('\r', '\n')
... | edamametechnologies/threatmodels | src/cli/import.py | .py | c63dbea34f2f94e1 | 7.15 | 1 |
#!/usr/bin/env python3
import argparse
import json
import sys
from typing import Any, Dict, List, Tuple
from pathlib import Path
FAIL = "FAIL"
WARN = "WARN"
# --- Classification test runner ---
def classify_device(db: Dict[str, Any], device: Dict[str, Any]) -> str:
"""Pure-Python mirror of profiles.rs logic at ... | edamametechnologies/threatmodels | src/profiles/validate.py | .py | 9ef1f80e250e2f05 | 7.15 | 1 |
#!/usr/bin/env python3
"""Generate score-reporting consent pages from the threat-model JSON.
Static operator notices live as hand-edited files under consent/. The
privacy-detailed pages list every check title from the current model, so they
are regenerated here whenever `make update` runs. Downstream
edamame_foundatio... | edamametechnologies/threatmodels | src/publish/generate-consent.py | .py | 7d80b79262b1fcfa | 7.15 | 1 |
'''Update models hash and dates'''
import sys
import hashlib
import json
import datetime
def open_model(filename: str) -> None:
'''Open the file in read mode and return the JSON'''
with open(filename, 'r', encoding="utf-8") as file:
data = json.load(file)
return data
def save_model(filename: st... | edamametechnologies/threatmodels | src/publish/update-models.py | .py | 55f6c033af2e2e4e | 7.15 | 1 |
#!/usr/bin/env python3
import json
import sys
import os
def merge_tags_from_files(input_json_paths):
"""
Reads one or more threat-model JSON files, merges them into a dictionary:
merged = {
metric_name: {
threat_model_name: set_of_tags,
...
},
...
... | edamametechnologies/threatmodels | src/tags/tags.py | .py | c17848f07f633082 | 7.15 | 1 |
from model import Model
import logging
import os
import sys
import getpass
import subprocess
from pathlib import Path
logging.basicConfig(
format='[%(asctime)s][%(levelname)s] %(message)s',
)
OK_LEVEL = 10
logging.addLevelName(OK_LEVEL, "\033[32mOK\033[0m")
def ok(self, message, *args, **kwargs):
... | edamametechnologies/threatmodels | src/test/main.py | .py | 407e090649afaca4 | 7.65 | 1 |
import json
import yaml
from sys import platform
from metric import Metric, TargetIsNotACLI
class Model(object):
'''Perform tests over a threat model'''
def __init__(self, logger, dir_path, ignore_tests_path, username):
self.logger = logger
# Detect platform
self.source = self.detect_... | edamametechnologies/threatmodels | src/test/model.py | .py | 9714470240c342f3 | 7.65 | 1 |
'''Generate markdown files for each threat model into the wiki folder'''
from mdutils.mdutils import MdUtils
import json
import re
def print_action(loc, elevation, target, osName, osVersion):
systemHeader = "Tested for"
actionHeader = "Action"
elevationHeader = "Elevation"
targetHeader = "Script"
... | edamametechnologies/threatmodels | src/wiki/build-wiki.py | .py | 8089c37e059ab825 | 7.15 | 1 |
"""Polovoxel Blender add-on: composition root.
Holds ``bl_info`` and wires the domain/infrastructure/operators/ui layers
together via :func:`register`/:func:`unregister`. No business logic lives
here — everything is imported from the other layers and just registered
with Blender.
"""
import bpy
from . import keymaps
... | polotto/polovoxel | polovoxel/__init__.py | .py | 866907cbff063316 | 7.24 | 2 |
"""Pure grid/coordinate and material-naming math for the Polovoxel add-on.
Nothing in this module imports ``bpy`` or ``bmesh`` and nothing here has
side effects: nothing is created, drawn, or written to a scene. Only
``mathutils.Vector`` is used for vector arithmetic, so this module can be
imported and unit-tested out... | polotto/polovoxel | polovoxel/domain/geometry.py | .py | 39303e7f3a7f8777 | 7.24 | 2 |
"""bpy/bmesh-dependent adapters for the Polovoxel add-on.
This is the only layer allowed to call ``bpy.ops``/``bpy.data``/``bmesh`` to
create objects, assign materials, or read mesh data. Domain math (material
naming, voxel placement) lives in :mod:`polovoxel.domain.geometry` and is
only ever consumed here, never dupl... | polotto/polovoxel | polovoxel/infrastructure/blender_mesh.py | .py | 3a154f81e2dd1104 | 7.24 | 2 |
"""Centralizes keyboard-shortcut registration for the add-on's operators.
Pulling this out of the individual operator classes fixes three bugs that
existed when each operator defined its own ``key_map`` method: a mismatched
``self``/``km`` target on two of them, a copy-pasted ``bl_idname`` on the
cuboid operator, and ... | polotto/polovoxel | polovoxel/keymaps.py | .py | e4530177addc40b3 | 7.24 | 2 |
"""Operator: add a single voxel at the world origin."""
import bpy
from ..domain.geometry import get_material_name
from ..infrastructure.blender_mesh import create_cube
class PolovoxelAddFirstVoxelOperator(bpy.types.Operator):
"""Add one voxel over world origin"""
bl_idname = "object.polovoxel_add_first_voxe... | polotto/polovoxel | polovoxel/operators/add_first_voxel.py | .py | b7a5285452aca11d | 7.24 | 2 |
"""Operator: modal handler that adds a voxel on whatever face the user clicks."""
import bpy
from ..infrastructure.blender_mesh import add_voxel_at_mouse
_running = False
class PolovoxelAddOnClickVoxelOperator(bpy.types.Operator):
"""Add one voxel over click"""
bl_idname = "object.polovoxel_add_on_click_vox... | polotto/polovoxel | polovoxel/operators/add_voxel_on_click.py | .py | 7bd72f1f1b6492fa | 7.24 | 2 |
"""Operator: add a new voxel above the currently selected face (edit mode)."""
import bpy
from ..infrastructure.blender_mesh import add_voxel_on_selected_face
class PolovoxelAddVoxelOperator(bpy.types.Operator):
"""Add new voxel above selected face"""
bl_idname = "object.polovoxel_add_voxel_operator"
bl_... | polotto/polovoxel | polovoxel/operators/add_voxel_on_face.py | .py | e210e11685e402da | 7.24 | 2 |
"""Scene-level state for the Polovoxel add-on.
Holds the current scale/color/location/size/click-toggle values that the
panel displays and the operators read defaults from. No business logic
lives here.
"""
import bpy
def _on_enable_with_click_toggled(self, context):
"""Start the click-to-add modal loop when the... | polotto/polovoxel | polovoxel/ui/properties.py | .py | 9df1bb21e30fa107 | 7.24 | 2 |
import hashlib
from cryptography.fernet import Fernet
def generate_key():
return Fernet.generate_key().decode()
def encrypt(text, cipher_key=None):
"""
加密,我也没测试过,不知道能不能正常使用,纯字母的应该没问题,中文的待商榷
:param text: 需要加密的文本
:param cipher_key: 加密key
:return: 加密后的文本
"""
if cipher_key is None or te... | farfarfun/funsecret | src/funsecret/fernet/fernet.py | .py | 912509b6c00ac069 | 7 | 0 |
import base64
import os
import time
from datetime import datetime
from typing import List
from urllib.parse import quote_plus
from farcache import cache
from farlog import getLogger
from sqlalchemy import (
BIGINT,
Engine,
String,
Text,
UniqueConstraint,
delete,
select,
update,
)
from s... | farfarfun/funsecret | src/funsecret/secret/secret.py | .py | 3cb1154ed6080dd6 | 7 | 0 |
import asyncio
import logging
from functools import reduce
# from slack_sdk.errors import SlackApiError
class AcquisitionState:
def __init__(self, doc):
if "shape" in doc:
shape = doc.get("shape")
elif "num_points" in doc:
shape = (doc.get("num_points"),)
#... | wright-group/bluesky-in-a-box | slack/lib.py | .py | 5b9cc5d998674cd6 | 7.39 | 5 |
import logging
import asyncio
from bluesky.callbacks import CallbackBase
from lib import async_client_method_handler, AcquisitionState
client_handler = async_client_method_handler
class Acquisition(CallbackBase):
def __init__(self, app, channel):
self.app = app
self.channel = channel
... | wright-group/bluesky-in-a-box | slack/slack_event_model.py | .py | 5e8cd9dbc90e8f66 | 7.39 | 5 |
import sys
import os
import json
""" 设置快捷命令方式
在bashrc中保存命令,alias PKM-Operate="cd xxx;pyhton3 build.py"
"""
BASE_PATH = '../../KnowledgeMap'
PATH = BASE_PATH
hide=[]
block={}
def get_all_file(path,ignore=True):
''' 获取某路径下的所有html文件路径名
'''
global hide
temp=[]
for item in os.listdir(path):
if os.path.splitext(ite... | CharlesShan-hub/PKM | pkmizer/oldplugins/Operater/build.py | .py | c532ae6fa40b2b54 | 7.24 | 2 |
import os
import shutil
FROM_PATH='../..'
TO_PATH='../../../CharlesShan-hub.github.io'
ignore_path=[
#'/KnowledgeMap/计算机科学',
#'/KnowledgeMap/计算机科学/计算机网络',
#'/KnowledgeMap/计算机科学/计算机组成原理',
#'/KnowledgeMap/计算机科学/操作系统',
#'/KnowledgeMap/计算机科学/数据结构',
#'/KnowledgeMap/计算机科学/以太坊',
#'/KnowledgeMap/计算机科学/密码学',
#'/Knowle... | CharlesShan-hub/PKM | pkmizer/oldplugins/To_HTML_Path/build.py | .py | 6af207f5049893b5 | 7.24 | 2 |
"""
Markdown Image Downloader Tool
Downloads online images referenced in markdown files and replaces with local references
"""
DESCRIPTION = "Downloads online images from markdown files and replaces URLs with local file references."
PARAM_PROMPTS = {
'input_dir': {
'label': 'Input Directory (contains mark... | CharlesShan-hub/PKM | pkmizer/scripts/image_downloader.py | .py | c6a45a8618a67ab1 | 7.24 | 2 |
"""
DeepSeek Markdown Optimizer
使用 DeepSeek API 批量优化 Markdown 文件(保留内容,仅优化语法)
"""
DESCRIPTION = "使用 DeepSeek API 批量优化 Markdown 文件 - 转换 font 标签为加粗,优化 Markdown 语法"
PARAM_PROMPTS = {
'input_dir': {
'label': '输入目录(包含 Markdown 文件)',
'type': 'path',
'default': '',
},
'prompt_name': {
... | CharlesShan-hub/PKM | pkmizer/scripts/markdown_optimizer.py | .py | 1f37970100294ee9 | 7.24 | 2 |
"""
Markdown File Splitter Tool V2
只读取输入并打印
"""
DESCRIPTION = "Markdown文件分割工具V2 - 只读取输入并打印"
PARAM_PROMPTS = {
'input_file': {
'label': '输入Markdown文件',
'type': 'file',
'default': '',
},
'output_dir': {
'label': '输出目录(将创建/notes子文件夹)',
'type': 'path',
'default'... | CharlesShan-hub/PKM | pkmizer/scripts/markdown_splitter.py | .py | 67de49a1d1895781 | 7.24 | 2 |
"""Asynchronous Python client for the Powerfox local interface."""
from __future__ import annotations
import asyncio
import socket
from dataclasses import dataclass
from importlib import metadata
from typing import Any, Self
from aiohttp import ClientError, ClientResponseError, ClientSession
from aiohttp.hdrs import... | klaasnicolaas/python-powerfox | src/powerfox/local.py | .py | 4dc8335a0ababd97 | 7.15 | 1 |
"""Asynchronous Python client for Powerfox."""
from __future__ import annotations
import asyncio
import json
import socket
from dataclasses import dataclass
from importlib import metadata
from typing import Annotated, Any, Self
from aiohttp import BasicAuth, ClientError, ClientResponseError, ClientSession
from aioht... | klaasnicolaas/python-powerfox | src/powerfox/powerfox.py | .py | e04e170427d9ab4e | 7.15 | 1 |
from pathlib import Path
import pytest
from PySide6.QtWidgets import QApplication
from tests.pixmap_differ import PixmapDiffer
@pytest.fixture(scope='session')
def qt_application() -> QApplication:
return QApplication()
@pytest.fixture(scope='session')
def session_pixmap_differ(qt_application, request) -> Pix... | donkirkby/four-letter-blocks | tests/conftest.py | .py | f09f779ded25f191 | 7.74 | 2 |
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from agr_literature_service.api.models import CopyrightLicenseModel
from agr_literature_service.api.schemas import CopyrightLicenseSchemaPost
def create(db: Session, license: CopyrightLicenseSchemaPost):
"""
:param db:
:param... | alliance-genome/agr_literature_service | agr_literature_service/api/crud/copyright_license_crud.py | .py | d50d5df684aa1162 | 7.15 | 1 |
import hashlib
from typing import Dict, List, Optional, Set
from fastapi import HTTPException, UploadFile, status
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from agr_literature_service.api.crud.referencefile_crud import file_upload_single
from agr_literature_service.api.crud.referenc... | alliance-genome/agr_literature_service | agr_literature_service/api/crud/embedding_file_crud.py | .py | ec0e5b060759f301 | 7.15 | 1 |
import logging
from typing import Any, Dict, List, Optional
from fastapi import HTTPException, status
from fastapi.encoders import jsonable_encoder
from sqlalchemy import func, or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, selectinload
from agr_literature_service.api.models import ... | alliance-genome/agr_literature_service | agr_literature_service/api/crud/laboratory_crud.py | .py | 5dde6638262e3c19 | 7.15 | 1 |
import gzip
import logging
import os
import shutil
import tempfile
from typing import Optional
import boto3
from botocore.exceptions import BotoCoreError, ClientError
from fastapi import UploadFile, HTTPException
from sqlalchemy.orm import Session, joinedload
from starlette.background import BackgroundTask
from starle... | alliance-genome/agr_literature_service | agr_literature_service/api/crud/ml_model_crud.py | .py | a68d3e04230cd817 | 7.15 | 1 |
import logging
from datetime import datetime
from typing import Any, Dict, List, Optional
from fastapi import HTTPException, status
from fastapi.encoders import jsonable_encoder
from sqlalchemy import func, or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, selectinload
from agr_literat... | alliance-genome/agr_literature_service | agr_literature_service/api/crud/person_crud.py | .py | d783a0b7a20ae020 | 7.15 | 1 |
"""
person_name_crud.py
"""
import logging
from typing import Any, Dict, List, Optional
from fastapi import HTTPException, status
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session, selectinload
from agr_literature_service.api.models import PersonModel, PersonNameModel
from agr_literatur... | alliance-genome/agr_literature_service | agr_literature_service/api/crud/person_name_crud.py | .py | 209514522357397a | 7.15 | 1 |
import logging
from typing import Any, Dict, List, Optional
from fastapi import HTTPException, status
from fastapi.encoders import jsonable_encoder
from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session, contains_eager, joinedload
from agr_literature_service.api.models.person_model import PersonMod... | alliance-genome/agr_literature_service | agr_literature_service/api/crud/person_setting_crud.py | .py | 1b69e5e50760bfcc | 7.15 | 1 |
import logging
from typing import List
from fastapi import HTTPException, status
from agr_literature_service.api import resource_descriptor_cache
logger = logging.getLogger(__name__)
def update() -> List[resource_descriptor_cache.ResourceDescriptor]:
"""Force-refresh this worker's in-memory descriptor cache fr... | alliance-genome/agr_literature_service | agr_literature_service/api/crud/resource_descriptor_crud.py | .py | 9fc62d09b36251de | 7.15 | 1 |
from typing import Dict, Any, List, Optional, Tuple
from datetime import datetime, date, time, timezone
def ensure_filter_structure(es_body: Dict[str, Any]) -> None:
"""
Ensure es_body has the nested structure where we attach range filters:
es_body["query"]["bool"]["filter"]["bool"]["must"] (list)
"... | alliance-genome/agr_literature_service | agr_literature_service/api/crud/search_filters.py | .py | ee8d0520d542bfa3 | 7.15 | 1 |
#!/usr/bin/env python3
"""Prune stale SNAPSHOT/RC chart packages from the snapshot/ Helm repository.
Retention policy (union of two rules, a package survives if EITHER holds):
1. it is among the N newest builds of its chart, per pre-release kind
(SNAPSHOT and RC are ranked independently);
2. it was added to g... | epam/edp-helm-charts | scripts/prune-snapshots.py | .py | 03c5ef835ad150b0 | 7.39 | 5 |
"""Entity-level behavioural features derived from the event stream.
The result is deliberately a flat, stable table: it can be written to the offline user/item
feature table and copied to Redis without requiring rank-engine to read the event stream.
"""
import numpy as np
import pandas as pd
DEFAULT_EVENT_TYPES = (... | open-rec/rec-algorithm | algorithm/feature/event_feature.py | .py | f1aa47bf887bc8a3 | 7.39 | 5 |
import inspect
import logging
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
# scikit-learn renamed OneHotEncoder's `sparse` to `sparse_output` in 1.2 and removed the old name
# in 1.4. Pick whichever this install understand... | open-rec/rec-algorithm | algorithm/feature/feature.py | .py | 505acd36e44da168 | 7.39 | 5 |
from pathlib import Path
import torch
import torch.nn as nn
from algorithm.feature.feature_space import FeatureSpace
from algorithm.rank.lr import LRRecModel
from algorithm.utils.file_util import DEFAULT_SCENE, feature_path, rank_model_path
MODEL_FILENAME = "fm.pth"
FEATURE_FILENAME = "fm.features.json"
class FMM... | open-rec/rec-algorithm | algorithm/rank/fm.py | .py | 8eef859abe201ec2 | 7.39 | 5 |
from algorithm.recall.recall import EVENT_UNIQUE_COLUMNS, Recall
from algorithm.structure.score_item import ScoreItem
class Hot(Recall):
"""Popularity recall: interaction count per item, scaled so the most popular one scores 1."""
def __init__(self, events=None, recall_size=1000):
super().__init__(ev... | open-rec/rec-algorithm | algorithm/recall/hot.py | .py | 3f86d45abd6236bd | 7.39 | 5 |
import abc
import math
from collections import defaultdict
from algorithm.recall.recall import EVENT_UNIQUE_COLUMNS, Recall
from algorithm.structure.score_item import ScoreItem
class I2I(Recall):
def __init__(self, events=None, recall_size=100, cut_size=20):
super().__init__(events=events, recall_size=r... | open-rec/rec-algorithm | algorithm/recall/item_cf_i2i.py | .py | 306291c999cb19eb | 7.39 | 5 |
from algorithm.recall.recall import Recall
from algorithm.structure.score_item import ScoreItem
class New(Recall):
"""
Freshness recall: the most recently published items, scored by how new they are relative to the
range actually present in the data.
"""
def __init__(self, items=None, recall_size... | open-rec/rec-algorithm | algorithm/recall/new.py | .py | 39e8f5f736fcbe19 | 7.39 | 5 |
import os
from pathlib import Path
current_path = Path(__file__).resolve()
MODEL_HOME_ENV = "OPENREC_MODEL_HOME"
RANK_DIR = "rank"
FEATURE_DIR = "feature"
# the namespace trained artifacts are filed under, keeping them clear of the pre-trained Douban
# checkpoint that sits at the root of model/rank
DEFAULT_SCENE = ... | open-rec/rec-algorithm | algorithm/utils/file_util.py | .py | 847a4e807dab6f4a | 7.39 | 5 |
"""Distributed rank sample construction; model training remains PyTorch-compatible."""
from pyspark.sql import functions as F
def labelled_interactions(events, users, items):
"""Join labels to as-of entities; the item snapshot excludes latest DELETE tombstones."""
labels = events.filter(F.col("type").isin("c... | open-rec/rec-algorithm | jobs/spark/rank.py | .py | f8b81f4602842999 | 7.39 | 5 |
#!/usr/bin/env python3
# Copyright (c) 2006 Paul Saunders
import sys
from pathlib import Path
import click
import yaml
from aocd.models import Puzzle
class AOCDumper(yaml.SafeDumper):
pass
def str_presenter(
dumper: AOCDumper | yaml.Dumper, data: str
) -> yaml.ScalarNode:
style = "|" if "\n" in data e... | darac/adventofcode | scripts/make_example_yaml.py | .py | a3634fe3c5732c16 | 7 | 0 |
# Copyright (c) 2015 Paul Saunders
"""
--- Day 1: Not Quite Lisp ---
Santa was hoping for a white Christmas, but his weather machine's "snow"
function is powered by stars, and he's fresh out! To save Christmas, he
needs you to collect fifty stars by December 25th.
Collect stars by helping Santa solve puzzles. Two puzz... | darac/adventofcode | src/aoc/year2015/day01.py | .py | a7fedbeb9f0b2551 | 7 | 0 |
# Copyright (c) 2015 Paul Saunders
# spell-checker: disable
"""
--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location,
and then an elf at the North Pole calls him via radi... | darac/adventofcode | src/aoc/year2015/day03.py | .py | 932b635853106c63 | 7 | 0 |
# Copyright (c) 2021 Paul Saunders
# spell-checker: disable
"""
--- Day 1: Sonar Sweep ---
You're minding your own business on a ship at sea when the overboard alarm
goes off! You rush to see if you can help. Apparently, one of the Elves
tripped and accidentally sent the sleigh keys flying into the ocean!
Before you ... | darac/adventofcode | src/aoc/year2021/day01.py | .py | 520799f5e21a161a | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.