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
# amcli/commands/mclean.py import shutil from pathlib import Path import yaml def load_config(): with open("config.yml") as f: return yaml.safe_load(f) def run(): """ Maintainer clean: remove all generated files under outputdir. Equivalent to 'make maintainer-clean'. """ config = load...
ono-kojiro/learning_python
amcli/src/amcli/commands/mclean.py
.py
116880aac84fd70e
7
0
# amcli/commands/patch.py import re from pathlib import Path def run(target: str, project: str, application: str): """ Apply patches to Django project files. target: "urls" など """ if target == "urls": return _patch_urls(project, application) raise ValueError(f"Unknown patch target: {...
ono-kojiro/learning_python
amcli/src/amcli/commands/patch.py
.py
fbe319daa33f6fc6
7
0
"""Action selection and the green-time splits the actions stand for.""" import random def actionSelection(randomProbability, qTable, numberOfAction): """Pick an action epsilon-greedily and return it with its green times. `qTable` is the single Q-table row for the current state and `randomProbability` th...
mojtabanorouzie/Reinforcement-Learning-TSC
ReinforcementLearningPack/ActionSelection.py
.py
f645b353c02a85e6
7.15
1
"""Export settled agent experience as labelled rows, for later use off-line. Once an agent has stopped exploring a given state, the action it greedily picks there is its learned answer for that traffic situation. This module writes those answers out alongside the raw measurements that produced them, one CSV row per de...
mojtabanorouzie/Reinforcement-Learning-TSC
ReinforcementLearningPack/CreateDataSet.py
.py
c1c813c1c8f3d17b
7.15
1
"""Reward: score the current delay against a sliding window of recent delay.""" def getReward(oldDta, delayTime): """Return [reward, updatedWindow] for the delay times just observed. `delayTime` is the average delay on each of the four incoming approaches; `oldDta` is the five-slot window of the previous...
mojtabanorouzie/Reinforcement-Learning-TSC
ReinforcementLearningPack/GetReward.py
.py
6cc067dc43f7e8e4
7.15
1
"""The agent and its temporal-difference update.""" import random class ReinforcementLearningAgent: """One learning traffic signal controller, bound to one junction. Holds a `numberOfState` x `numberOfAction` Q-table and everything needed to carry a decision across control cycles: `state` and `action` a...
mojtabanorouzie/Reinforcement-Learning-TSC
ReinforcementLearningPack/QLearning.py
.py
40585d94eed3b23a
7.15
1
"""Structural tests for the two lookup tables at the core of the agent. These cover ``GetState.getState`` and ``ActionSelection.getPhaseDuration``, the only two modules in ``ReinforcementLearningPack`` that are pure functions with no Aimsun dependency. Both are syntax-compatible with Python 3, so these tests run anywh...
mojtabanorouzie/Reinforcement-Learning-TSC
tests/test_state_and_action_tables.py
.py
26558ea9fe4ede38
7.65
1
""" #!/usr/bin/env python3 Original from https://github.com/dgiese/dustcloud/blob/master/dustcloud/build_map.py Modified to resemble the map inside the Mi Home application This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free...
Luzifer/mimap
build_map.py
.py
2e45babb4f8aa6a4
7.3
3
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from core import compatible os_name = compatible.os_name() def finish(): """ reset the color of windows/terminal before exit """ if "linux" in os_name or os_name == "darwin": sys.stdout.write("\033[0m") else: import ctypes ...
armangheysari/OWASP-Nettacker
core/color.py
.py
03d2ee981eefb2d9
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import netaddr import time import sys import requests from core.alert import * from core.compatible import version from netaddr import iprange_to_cidrs from netaddr import IPNetwork from core.log import __log_into_file def getIPRange(IP): """ get IPv4 range from R...
armangheysari/OWASP-Nettacker
core/ip.py
.py
0cafb1bc0d497036
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, Text Base = declarative_base() class Update_Log(Base): """ This Class defines the table schema for the update log table, Any changes related to updating log table need...
armangheysari/OWASP-Nettacker
database/models.py
.py
7cef33c280cb021c
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import create_engine from core.config import _database_config from database.models import Base USER = _database_config()["USERNAME"] PASSWORD = _database_config()["PASSWORD"] HOST = _database_config()["HOST"] PORT = _database_config()["PORT"] DATABASE = ...
armangheysari/OWASP-Nettacker
database/mysql_create.py
.py
270923233b5d0a10
7
0
#!/usr/bin/env python3 """Build aligned-loci intersection across IVTFF editions (A6 condition B base).""" from __future__ import annotations import json import sys from pathlib import Path import pandas as pd ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from vmb.alignment import...
pablogventura/voynich-metric-battery
scripts/build_aligned_loci.py
.py
7fa5a23bd2b3c5eb
7
0
#!/usr/bin/env python3 """Plot hero heatmap: metrics x transliteration editions.""" from __future__ import annotations import sys from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns ROOT = Path(__file__).resolve().parents[1] TABLES = ROOT / "results"...
pablogventura/voynich-metric-battery
scripts/plot_heatmap.py
.py
6f794d57d522b5f1
7
0
#!/usr/bin/env python3 """Run ablation matrix A–E (PROTOCOL A6) and variance-decomposition summary.""" from __future__ import annotations import argparse import sys from pathlib import Path import numpy as np import pandas as pd ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from ...
pablogventura/voynich-metric-battery
scripts/run_ablation_matrix.py
.py
05f914d30e80a20f
7
0
#!/usr/bin/env -S uv run # /// script # requires-python = ">=3.10" # dependencies = [ # "rich>=13.0.0", # "pypandoc>=1.13", # "python-slugify>=8.0.0", # "click>=8.0.0", # ] # /// """ draftpost.py - Create a new blog post draft with YAML metadata header. This script creates a new post in the mpr.drafts ...
crossjam/mpr
draftpost.py
.py
93c4f8bb050c1900
7.24
2
""" Archive Data Generator Plugin Computes archive data once during site generation instead of on every page render """ from pelican import signals def compute_archives(generator): """ Reindex Pelican's already-computed period_archives (year/month groupings) into structures the theme can use without any p...
crossjam/mpr
plugins/archive_data.py
.py
4ea43c0ecd9933f2
7.24
2
""" Explicit Modified Date Plugin With DEFAULT_DATE = "fs", Pelican's readers.path_metadata() backfills both `date` and `modified` from the file's on-disk mtime whenever a post doesn't set them explicitly. That makes `modified` indistinguishable from "no Modified: field was set" -- any incidental edit to a file (forma...
crossjam/mpr
plugins/explicit_modified.py
.py
7a515666c52de6c9
7.24
2
# -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer from pelican.settings import DEFAULT_CONFIG, get_settings_from_file SETTINGS_FILE_BASE = 'pelicanconf.py' SETTINGS = {} ...
crossjam/mpr
tasks.py
.py
537cb48ad4c5e2a5
7.24
2
from django.conf import settings from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password=None): """Cr...
fernandezgarcete/profiles-rest-api
profiles_api/models.py
.py
8606938dea683528
7
0
from rest_framework import serializers from profiles_api import models class HelloSerializer(serializers.Serializer): """Serializes a name field for testing our APIView""" name = serializers.CharField(max_length=10) class UserProfileSerializer(serializers.ModelSerializer): """Serializes a user Profile o...
fernandezgarcete/profiles-rest-api
profiles_api/serializers.py
.py
94a0cb3a52bd8c4f
7
0
from rest_framework import filters, status, viewsets from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from rest_f...
fernandezgarcete/profiles-rest-api
profiles_api/views.py
.py
a36dbe74b1c43821
7
0
import time from django.db import connections from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command to pause execution until database is available""" def handle(self, *args, **options): self.stdout.write('Waiting...
fernandezgarcete/recipe-app
app/core/management/commands/wait_for_db.py
.py
19d55029254670c1
7
0
from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): """Setting up defualts""" self.client = Client() self.admin_user = get_user_model().objects.create_superuser( ...
fernandezgarcete/recipe-app
app/core/tests/test_admin.py
.py
e8dc4589b7c56361
7.5
0
from unittest.mock import patch from django.core.management import call_command from django.db.utils import OperationalError from django.test import TestCase class CommandTests(TestCase): def test_wait_for_db_ready(self): """Test waiting for db when db is available""" with patch('django.db.utils....
fernandezgarcete/recipe-app
app/core/tests/test_commands.py
.py
3d5b192bfe50b317
7.5
0
from unittest.mock import patch from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='test@example.com', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password) class ModelTests(Tes...
fernandezgarcete/recipe-app
app/core/tests/test_models.py
.py
f36e11d6de1d1ed2
7.5
0
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Ingredient, Recipe from recipe.serializers import IngredientSerializer INGREDIENT_URL = reverse('recipe:in...
fernandezgarcete/recipe-app
app/recipe/tests/test_ingredient_api.py
.py
f90ac9d399f71bdc
7.5
0
import tempfile import os from PIL import Image from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.models import Recipe, Tag, Ingredient from recipe.serializers import Recip...
fernandezgarcete/recipe-app
app/recipe/tests/test_recipe_api.py
.py
c2e741ffefae88c7
7.5
0
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Tag, Recipe from recipe.serializers import TagSerializer TAGS_URL = reverse('recipe:tag-list') class Pub...
fernandezgarcete/recipe-app
app/recipe/tests/test_tags_api.py
.py
6afc93ad91eb1099
7.5
0
from rest_framework import viewsets, mixins, status from rest_framework.authentication import TokenAuthentication from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from core.models import Tag, Ingredient, Recipe from recipe i...
fernandezgarcete/recipe-app
app/recipe/views.py
.py
7103112033aa9d1f
7
0
from django.contrib.auth import get_user_model, authenticate from django.utils.translation import ugettext_lazy as gtl from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): """Serializer for the user object""" class Meta: model = get_user_model() fields = (...
fernandezgarcete/recipe-app
app/user/serializers.py
.py
40aee6cf049d48c9
7
0
from rest_framework import generics, authentication, permissions from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from user.serializers import UserSerializer, AuthTokenSerializer class CreateUserView(generics.CreateAPIView): """Create a new user in the sy...
fernandezgarcete/recipe-app
app/user/views.py
.py
de9e419bf56b94a9
7
0
# -*- coding: utf-8 -*- """ Accounts #################### *Module* ``project.user.account`` This module defines routes to manage accounts of users. """ from flask import render_template, redirect, url_for, flash from flask_login import login_user, login_required, logout_user from . import user_app from .forms impo...
jasmine95dn/flask_best_worst_scaling
project/user/account.py
.py
803aaea93beda180
7
0
# -*- coding: utf-8 -*- """ Views ################# *Module* ``project.user.views`` This module defines routes to manage views for users. """ from flask import render_template, redirect, url_for, flash, current_app from flask_login import login_required, logout_user, current_user from . import user_app from .forms ...
jasmine95dn/flask_best_worst_scaling
project/user/views.py
.py
f6dc9a9e5137a565
7
0
""" Unit Tests for models.py """ def test_new_user(new_user): """ GIVEN a User model WHEN a new User is created THEN check 1. if username, email, password are defined correctly 2. if password is stored as hashed password, not plaintext 3. if get_id() returns a strin...
jasmine95dn/flask_best_worst_scaling
tests/unit/test_models.py
.py
5c408d5211ab59b8
7.5
0
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import log_utils log_utils.enable_latex() def finv_1(r_init, tau, k1, k2): def f(rr): return rr + k1 * rr ** 3 + k2 * rr ** 5 r_l = 0 r_u = 2 * r_init while f(r_u) < r_init: # r_l = r_u r_...
josh-gleason/deep_calib
scripts/distortion_analysis.py
.py
7e46ab85dbf3a793
7
0
""" Ignore: # Get the appropriate helper function from watch.utils import util_kwimage import liberator lib = liberator.Liberator() from watch.utils import util_kwimage lib.expand(['watch']) lib.add_dynamic(util_kwimage.upweight_center_mask) lib.add_dynamic(util_kwimage._auto_kernel_sig...
Kitware/kwarray
dev/demo_stitcher.py
.py
e28aa03d6e0ff231
7.24
2
#!/usr/bin/env python import scriptconfig as scfg class UsageConfig(scfg.Config): default = { 'print_packages': False, 'remove_zeros': False, 'hardcoded_ubelt_hack': 0, 'extra_modnames': [], } def count_package_usage(modname): import ubelt as ub import glob from ...
Kitware/kwarray
dev/gen_api_for_docs.py
.py
778a6a7b2df03e14
7.24
2
""" References: https://en.wikipedia.org/wiki/Hodges%E2%80%93Lehmann_estimator https://www.youtube.com/watch?v=PaRZge3njm4 https://github.com/borisvish/Median-Polish https://jerryzli.github.io/robust-ml-fall19/lec3.pdf https://www.mwsug.org/proceedings/2006/stats/MWSUG-2006-SD01.pdf *** > Very g...
Kitware/kwarray
dev/robust_notes.py
.py
ee436433e72c04ef
7.24
2
from __future__ import annotations """ A convenient interface to solving assignment problems with the Hungarian algorithm (also known as Munkres or maximum linear-sum-assignment). The core implementation of munkres in in scipy. Recent versions are written in C, so their speed should be reflected here. TODO: - [ ]...
Kitware/kwarray
kwarray/algo_assignment.py
.py
073cb29687353fd1
7.24
2
from __future__ import annotations """ Functions for partitioning numpy arrays into groups. """ import numpy as np import ubelt as ub from packaging.version import parse as Version ARGSORT_HAS_STABLE_KIND: bool = Version(np.__version__) >= Version('1.15.0') __TODO__: str = """ TODO: For group items I would like ...
Kitware/kwarray
kwarray/util_groups.py
.py
ee51dfcdabfa9ad7
7.24
2
from __future__ import annotations """ Misc tools that should find a better home """ import numpy as np import ubelt as ub import numbers from typing import TYPE_CHECKING, overload if TYPE_CHECKING: from collections.abc import Sequence class FlatIndexer(ub.NiceRepr): """ Creates a flat "view" of a jagg...
Kitware/kwarray
kwarray/util_misc.py
.py
3a47e8f3d9aec443
7.24
2
from __future__ import annotations """ Utilities related to slicing References: https://stackoverflow.com/questions/41153803/zero-padding-slice-past-end-of-array-in-numpy TODO: - [ ] Could have a kwarray function to expose this inverse slice functionality. Also having a top-level call to apply an e...
Kitware/kwarray
kwarray/util_slices.py
.py
cc9dc521cd43c7b4
7.24
2
from __future__ import annotations """ Torch specific extensions """ import numpy as np import sys from typing import TYPE_CHECKING, cast if TYPE_CHECKING: from torch import Tensor def _is_in_onnx_export() -> bool: torch = sys.modules.get('torch', None) if torch is None: return False try: ...
Kitware/kwarray
kwarray/util_torch.py
.py
ee5840f32e8e296e
7.24
2
from typing import Any, cast def indexable_allclose( dct1, dct2, rel_tol=1e-9, abs_tol=0.0, return_info=False ): """ PORT FROM UBELT WITH SUPPORT FOR NDARRAYS Walks through two nested data structures and ensures that everything is roughly the same. """ import ubelt as ub import numpy a...
Kitware/kwarray
tests/test_arrayapi.py
.py
8454971b01ce9f8e
7.74
2
import numpy as np import ubelt as ub import kwarray from kwarray import distributions as dmod def test_rng_case1(): """ Reproduce a bug from kwarray.__version__ < 0.6.13 """ rng = 0 rng = kwarray.ensure_rng(rng) a = dmod.Distribution.random(rng=rng) print(a) values1 = a.sample(10) ...
Kitware/kwarray
tests/test_distributions.py
.py
c357ed7903c032ad
7.74
2
import eccodes import numpy as np import pyproj from eccodes import * from .definitions.grib_namespace import * from .definitions.Table_4_5 import TYPE_LEVEL class cgrib(): def __init__(self, gid, gribkeys=None): self.perturbationNumber = 0 self.gridkeys = sorted( GLOBAL_ATTRIBUTES_K...
rodri90y/gdio
gdio/cgrib.py
.py
20beb61d15f783cd
7.39
5
# Error model for QrackStabilizer's near-Clifford weak-simulation gate set. # # Mechanism (verified directly against the compiled library, Qrack commit # 4024713136dbc2cfefec70a69c7abd6f964da4e7, with the FlipQuadrant fix): # QStabilizer::RZ represents an arbitrary Z-rotation by first stripping # whole pi/2 multiples E...
vm6502q/qiskit-qrack-provider
qiskit/providers/qrack/backends/qstabilizer_noise.py
.py
6505d603ad278b4c
7.24
2
# Based on and adapted from the AceQasmSimulator pattern in this same # provider (itself adapted from # https://github.com/Qiskit/qiskit-qcgpu-provider/blob/master/qiskit_qcgpu_provider/qasm_simulator.py). # # Unlike AceQasmSimulator, this backend has NO sample-measure shortcut: # every shot rebuilds a fresh QrackStabi...
vm6502q/qiskit-qrack-provider
qiskit/providers/qrack/backends/qstabilizer_qasm_simulator.py
.py
61c4d7086a48208f
7.24
2
""" This module implements the job class used by simulator backends. Taken mostly from https://github.com/Qiskit/qiskit-qcgpu-provider/blob/master/qiskit_qcgpu_provider/job.py """ from qiskit.providers.job import JobV1 from qiskit.providers import JobStatus class QrackJob(JobV1): """ QrackJob class. Thi...
vm6502q/qiskit-qrack-provider
qiskit/providers/qrack/qrackjob.py
.py
d29556483c8bfa8f
7.24
2
# This code is based on and adapted from https://github.com/Qiskit/qiskit-aer/blob/master/qiskit/providers/aer/aerprovider.py # # Adapted by Daniel Strano # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this sour...
vm6502q/qiskit-qrack-provider
qiskit/providers/qrack/qrackprovider.py
.py
7050ce3fcdfbf35b
7.24
2
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
vm6502q/qiskit-qrack-provider
qiskit/providers/qrack/sampler.py
.py
20697390bb5b862e
7.24
2
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
vm6502q/qiskit-qrack-provider
test/benchmark/simple_benchmarks.py
.py
57ce1026829f6394
7.74
2
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
vm6502q/qiskit-qrack-provider
test/terra/backends/qasm_simulator/qasm_basics.py
.py
ace4eec01badbabb
7.74
2
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
vm6502q/qiskit-qrack-provider
test/terra/decorators.py
.py
47ba4c6a8ccb1dbd
7.74
2
""" ProgramVer - A Python version of Microsoft's 'winver'. Copyright (C) 2017-2026 willtheorangeguy """ # pylint: disable=import-error, invalid-name import os from tkinter import Tk, Text, INSERT, PhotoImage, Label, Button, TOP, BOTTOM # Import Statements # Helper Functions def get_resource_path(filename): ""...
willtheorangeguy/ProgramVer
main.py
.py
f89c18514385e90b
7.3
3
# -*- coding: future_fstrings -*- from django.test import TestCase from pool.models import Team, Game, Pick, Monday,Main,set_now from django.contrib.auth.models import User import requests, csv import datetime from pytz import timezone import pool.utils import random def load_teams(): pool.utils.restore('testdata/tes...
tammer/pool
pool/tests.py
.py
7b99379865447fd2
7.5
0
"""Dev tool: capture real Bandcamp response shapes to sanity-check the pydantic models in bandcamp_extract.bandcamp.types. Uses the locally saved session (~/.config/bcextr/session.json, created via `bcextr api login`). Strictly read-only: it never downloads a zip or mutates anything, only lists/reads data. Dumps raw J...
JonMontgo/bandcamp_extract
scripts/probe_bandcamp_api.py
.py
737aedce9308c43e
7.3
3
import html import json import re import time from typing import get_args import requests from .types import ( CollectionItem, CollectionItemsResponse, CollectionSummaryResponse, DownloadFormat, DownloadPageData, ProfilePageData, ) PAGEDATA_RE = re.compile(r'<div id="pagedata" data-blob="([^"...
JonMontgo/bandcamp_extract
src/bandcamp_extract/bandcamp/client.py
.py
7039fe5c859043ee
7.3
3
from django import forms from django.conf import settings from django.core.mail import send_mail from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string class KiriForm(forms.Form): name = forms.CharField( max_length=120, initial=f'{settings.KROONIKA[...
kalevhark/kroonika
kiri/forms.py
.py
a57cffb3a226ec0e
7.15
1
from django.utils.safestring import mark_safe from rest_framework import routers from wiki.viewsets import ( UserViewSet, KroonikaViewSet, ArtikkelViewSet, IsikViewSet, OrganisatsioonViewSet, ObjektViewSet, PiltViewSet, AllikasViewSet, ViideViewSet, ) from ilm.viewsets import ( ...
kalevhark/kroonika
kroonika/routers.py
.py
ce4bc27638fb8940
7.15
1
#!/usr/bin/env python ''' Module for reading from and writing to yaml files. Useful reference for yaml file: http://en.wikipedia.org/wiki/User:Baxter.brad/Drafts/YAML_Tutorial_and_Style_Guide Useful methods for pyYAML (ruamel.yaml is built on pyYAML): yaml.load(fh), yaml.load_all yaml.dump(fh), yaml.dump_all YAMLError...
saridut/floripy
floripy/file_formats/yamlio.py
.py
4cb3c9e7c6f6c48f
7
0
#!/usr/bin/env python import math import numpy as np from .flowfieldbase import FlowfieldBase class Linear_flow(FlowfieldBase): def __init__(self, **kwargs): self.set_property('U', kwargs['U']) self.set_property('Omega', kwargs['Omega']) self.set_property('E', kwargs['E']) def set_p...
saridut/floripy
floripy/flowfield/linear.py
.py
d7b95f933172cf68
7
0
#!/usr/bin/env python import math import numpy as np from .hydrodynamicsbase import HydrodynamicsBase class Spheres_hydrodynamics(HydrodynamicsBase): def __init__(self, model, flowfield, kwargs): self._model = model self._num_bodies = self._model.num_bodies self._all_radius = model.get_al...
saridut/floripy
floripy/hydrodynamics/spheres.py
.py
05d41eed054f6d3e
7
0
#!/usr/bin/env python import math import numpy as np import scipy.linalg as sla from floripy.mathutils import xform as tr from floripy.mathutils import linalg as mla def get_sector_angles(vertices_xy, center=[0.0,0.0]): vertex_degree = len(vertices_xy) edge_unit_vectors = [] for vertex in vertices_xy: ...
saridut/floripy
floripy/mathutils/geometry.py
.py
d1a1bff754e665c6
7
0
#!/usr/bin/env python import math import csv import numpy as np from ...mathutils import xform as tr from ...mathutils.linalg import unitized from .miura_sheet_trajectory import MiuraSheetTrajectory def get_phi_theta(v): ''' v: (3,) ndarray Returns phi and theta in degrees. phi: Angle measured from t...
saridut/floripy
floripy/models/miura_sheet/analyze_traj.py
.py
c71ae8b1226cd741
7
0
from math import comb import click def probability_all_slots(num_drafts: int, slots: int = 12) -> float: """Return the probability that all draft slots appear at least once.""" if num_drafts < 0: raise ValueError("num_drafts must be non-negative") if slots < 1: raise ValueError("slots mus...
mraspberry/scripts
draft-spot-odds/src/draft_spot_odds/__init__.py
.py
72207c0fbeb94c91
7
0
""" Pyparsing parser for BibTeX files A standalone parser using mo_parsing. mo_parsing has a simple and expressive syntax so the grammar is easy to read and write. Submitted by Matthew Brett, 2010 Simplified BSD license """ from mo_parsing import ( Regex, Suppress, ZeroOrMore, Group, Optional, ...
klahnakoski/mo-parsing
examples/btpyparse.py
.py
5b8344913257e25d
7.35
4
""" This module can parse a Delphi Form (dfm) file. The main is used in experimenting (to find which files fail to parse, and where), but isn't useful for anything else. """ __version__ = "1.0" __author__ = "Daniel 'Dang' Griffith <pythondev - dang at lazytwinacres . net>" from mo_parsing import CaselessLiteral from ...
klahnakoski/mo-parsing
examples/dfmparse.py
.py
20a68ec4e83f9791
7.35
4
# eval_arith.py # # Copyright 2009, 2011 Paul McGuire # # Expansion on the mo_parsing example simpleArith.py, to include evaluation # of the parsed tokens. # # Added support for exponentiation, using right-to-left evaluation of # operands # from mo_parsing import ( Word, nums, alphas, Combine, one_o...
klahnakoski/mo-parsing
examples/eval_arith.py
.py
c6066748298d65b2
7.35
4
# httpServerLogParser.py # # Copyright (c) 2016, Paul McGuire # """ Parser for HTTP server log output, of the form: 195.146.134.15 - - [20/Jan/2003:08:55:36 -0800] "GET /path/to/page.html HTTP/1.0" 200 4649 "http://www.somedomain.com/020602/page.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" 127.0.0.1 - u....
klahnakoski/mo-parsing
examples/httpServerLogParser.py
.py
54d9b233b3d09d0b
7.35
4
from threading import Thread class ThreadWithReturn(Thread): ''' 以多线程方式执行函数, 并且可在线程结束后通过 get 方法获取函数执行结果 (如果函数有返回值) ''' def __init__(self, target=None, args=None, kwargs=None): super(ThreadWithReturn, self).__init__(target=target, args=args, kwargs=kwargs) self.target = target ...
meterio/gear
gear/utils/thread.py
.py
40f88f3e300d9974
7.15
1
#!/usr/bin/env python3 """ Tool to pack a directory into a .docx, .pptx, or .xlsx file with XML formatting undone. Example usage: python pack.py <input_directory> <office_file> [--force] """ import argparse import shutil import subprocess import sys import tempfile import defusedxml.minidom import zipfile from pa...
montenoki/dotfiles
.config/opencode/skill/docx/ooxml/scripts/pack.py
.py
6fe762f45aff8c63
7
0
""" Validator for tracked changes in Word documents. """ import subprocess import tempfile import zipfile from pathlib import Path class RedliningValidator: """Validator for tracked changes in Word documents.""" def __init__(self, unpacked_dir, original_docx, verbose=False): self.unpacked_dir = Path...
montenoki/dotfiles
.config/opencode/skill/docx/ooxml/scripts/validation/redlining.py
.py
97abfdff4f08f43f
7
0
#!/usr/bin/env python3 """ Utilities for editing OOXML documents. This module provides XMLEditor, a tool for manipulating XML files with support for line-number-based node finding and DOM manipulation. Each element is automatically annotated with its original line and column position during parsing. Example usage: ...
montenoki/dotfiles
.config/opencode/skill/docx/scripts/utilities.py
.py
62a4b689056501b9
7
0
import json import sys from pypdf import PdfReader, PdfWriter from pypdf.annotations import FreeText # Fills a PDF by adding text annotations defined in `fields.json`. See forms.md. def transform_coordinates(bbox, image_width, image_height, pdf_width, pdf_height): """Transform bounding box from image coordinat...
montenoki/dotfiles
.config/opencode/skill/pdf/scripts/fill_pdf_form_with_annotations.py
.py
599d6f307edb4ee6
7
0
#!/usr/bin/env python3 """ Rearrange PowerPoint slides based on a sequence of indices. Usage: python rearrange.py template.pptx output.pptx 0,34,34,50,52 This will create output.pptx using slides from template.pptx in the specified order. Slides can be repeated (e.g., 34 appears twice). """ import argparse impor...
montenoki/dotfiles
.config/opencode/skill/pptx/scripts/rearrange.py
.py
c04ac37916f398ba
7
0
#!/usr/bin/env python3 """ Create thumbnail grids from PowerPoint presentation slides. Creates a grid layout of slide thumbnails with configurable columns (max 6). Each grid contains up to cols×(cols+1) images. For presentations with more slides, multiple numbered grid files are created automatically. The program out...
montenoki/dotfiles
.config/opencode/skill/pptx/scripts/thumbnail.py
.py
c21fd950b6ada7bd
7
0
#!/usr/bin/env python3 """ Skill Initializer - Creates a new skill from template Usage: init_skill.py <skill-name> --path <path> Examples: init_skill.py my-new-skill --path skills/public init_skill.py my-api-helper --path skills/private init_skill.py custom-skill --path /custom/location """ import sy...
montenoki/dotfiles
.config/opencode/skill/skill-creator/scripts/init_skill.py
.py
0bba250b94caa4cb
7
0
#!/usr/bin/env python3 """ Skill Packager - Creates a distributable zip file of a skill folder Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory] Example: python utils/package_skill.py skills/public/my-skill python utils/package_skill.py skills/public/my-skill ./dist """ impor...
montenoki/dotfiles
.config/opencode/skill/skill-creator/scripts/package_skill.py
.py
692525dd8096aee5
7
0
"""Opt-in interaction logging to Azure Blob Storage. When enabled, every completed voice-assistant interaction is logged as a JSONL record to an append blob. Daily rotation keeps one blob per day: ``logs/YYYY-MM-DD.jsonl``. The feature is entirely opt-in: unless a valid connection string is provided at startup, the l...
skateman/hh-hassio-repo
mcp-orchestrator/src/app/remote_logging.py
.py
a4c26f95f0f0c4df
7
0
#!/usr/local/bin/python # The MIT License (MIT) # # Copyright (c) 2014 Austin Hyde # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rig...
osmollo/my_workstation
library/yay.py
.py
9d3f3ded160b6b5c
7.35
4
#!/usr/bin/env python3 """ Lucy's Arm - Servo control script Controls a servo motor on GPIO 7 to wave and gesture. Usage: python3 arm.py <command> [options] Commands: wave [count] - Wave hello/goodbye (default: 2 times) raise - Raise the arm up lower - Lower the arm down back ...
MarzlS/lucy
nanobot/workspace/skills/arm/scripts/arm.py
.py
84f26f3617bdf075
7
0
#!/usr/bin/env python3 """ Lucy's Aura - LED control script Controls a Neopixel LED on GPIO 18 to express emotions and moods. Usage: python3 aura.py <command> [options] Commands: shine <color> - Set LED to a solid color pulse <color> [duration] - Pulse the LED (duration: 0.5-2.0 seconds) disco ...
MarzlS/lucy
nanobot/workspace/skills/aura/scripts/aura.py
.py
796146aae33c92f9
7
0
#!/usr/bin/env python3 """ Lucy's Voice - Text-to-Speech using edge-tts (Microsoft Edge TTS). Usage: python3 voice.py say "Hello, I am Lucy!" python3 voice.py say "Hallo, ich bin Lucy!" --voice de-DE-SeraphinaMultilingualNeural python3 voice.py play /path/to/audio.wav python3 voice.py list-voices Requ...
MarzlS/lucy
nanobot/workspace/skills/voice/scripts/voice.py
.py
5b577fcf4d604669
7
0
"""Entry point.""" import sys import colorama # Call deinit() before importing pretty_errors because Colorama can't handle # multiple calls of init(). # See: https://github.com/tartley/colorama/issues/205 colorama.deinit() import pretty_errors # noqa: E402 from . import main # noqa: E402 def entry_point() -> N...
tueda/polybench
polybench/__main__.py
.py
ba3cd3f5e54b8254
7.24
2
"""Routines for making comparison plots.""" import itertools from pathlib import Path from typing import Dict, Optional, Sequence, Union import matplotlib.pyplot as plt import numpy as np import pandas as pd from pandas.core.frame import DataFrame from .prob import ProblemSet from .solver import Result def write_c...
tueda/polybench
polybench/plot.py
.py
ffeb257eb61e433a
7.24
2
"""Capsulize polynomial operations.""" from typing import Union import symengine class Polynomial: """Polynomial wrapper class.""" __slots__ = ("_raw",) def __init__(self, expr: Union[str, int, "Polynomial"] = 0) -> None: """Construct a polynomial.""" if isinstance(expr, str): ...
tueda/polybench
polybench/poly.py
.py
19cb73926be10a5e
7.24
2
"""Problems for benchmarking.""" import functools import itertools import math import random from typing import Any, Iterator, Sequence from typing_extensions import Literal from .poly import Polynomial @functools.lru_cache(maxsize=128) def variables(n_vars: int) -> Sequence[str]: """Return a set of variables....
tueda/polybench
polybench/prob.py
.py
7e97601cdf5aec28
7.24
2
"""Solver.""" import filecmp import hashlib import os import shutil import subprocess import urllib import urllib.error import urllib.request import uuid from logging import Logger from pathlib import Path from typing import List, NamedTuple, Optional, Sequence, Type, Union import importlib_resources from .poly impo...
tueda/polybench
polybench/solver.py
.py
0f1c5d1c82f2dcde
7.24
2
"""Fermat Solver.""" import os import re import shutil import time from pathlib import Path from typing import Dict, Optional, Sequence from ..prob import ProblemSet from ..solver import Result, Solver, SolverSetupError class FermatSolver(Solver): """Fermat Solver.""" _name = "Fermat" _env_var = "FERMA...
tueda/polybench
polybench/solvers/fer.py
.py
ed9dabc3df29fea5
7.24
2
"""FLINT Solver.""" from pathlib import Path from typing import Optional, Sequence from ..prob import ProblemSet from ..solver import Result, Solver, SolverSetupError class FlintSolver(Solver): """FLINT Solver.""" _name = "FLINT" def _find_executable(self) -> str: s = f"{self._build_dir}/build...
tueda/polybench
polybench/solvers/flint.py
.py
14f838bb1c5a67fb
7.24
2
"""reFORM Solver.""" from pathlib import Path from typing import Optional, Sequence from ..prob import ProblemSet from ..solver import Result, Solver, SolverSetupError class ReformSolver(Solver): """reFORM Solver.""" _name = "reFORM" def _prepare(self, problems: ProblemSet) -> Optional[str]: i...
tueda/polybench
polybench/solvers/reform.py
.py
cb240bd17e8548ba
7.24
2
"""Rings Solver.""" import re from typing import Optional, Sequence from ..prob import ProblemSet from ..solver import Result, Solver, SolverSetupError class RingsSolver(Solver): """Rings Solver.""" _name = "Rings" def _prepare(self, problems: ProblemSet) -> Optional[str]: if problems.problem_...
tueda/polybench
polybench/solvers/rings.py
.py
399899ac3d349d77
7.24
2
"""Singular Solver.""" import os import shutil from pathlib import Path from typing import Optional, Sequence from ..prob import ProblemSet from ..solver import Result, Solver, SolverSetupError class SingularSolver(Solver): """Singular Solver.""" _name = "Singular" _env_var = "SINGULAR_COMMAND" de...
tueda/polybench
polybench/solvers/singular.py
.py
0dcd6d225749e9e8
7.24
2
"""Symbolica Solver.""" from pathlib import Path from typing import Optional, Sequence import toml from ..prob import ProblemSet from ..solver import Result, Solver, SolverSetupError class SymbolicaSolver(Solver): """Symbolica Solver.""" _name = "Symbolica" def _prepare(self, problems: ProblemSet) ->...
tueda/polybench
polybench/solvers/symbolica.py
.py
0b5ab6d3db72f8df
7.24
2
"""Common utility routines.""" import contextlib import os from pathlib import Path from typing import Iterator, Union def bytes2human(n: int) -> str: """Convert `n` bytes into a human readable string. >>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M' """ # http://code.act...
tueda/polybench
polybench/util.py
.py
db9060808e90a546
7.24
2
"""Generate a Markdown table from a log file.""" from __future__ import annotations import fileinput from typing import Sequence def extract_rows(file_input: fileinput.FileInput[str]) -> list[tuple[str, str]]: """Extract key-value pairs from the input.""" rows = [] tools = set() for line in file_in...
tueda/polybench
scripts/log2mdtbl.py
.py
3732288c96fbca3e
7.24
2
"""Convert poetry.lock to requirements.txt.""" import sys import toml from packaging.specifiers import SpecifierSet from packaging.version import Version def is_compatible_version(version: str, specifiers: str) -> bool: """Check if the version is compatible with the specifiers.""" if specifiers == "*": ...
tueda/polybench
scripts/poetry2pip.py
.py
b73ef531d1a7ba44
7.24
2
import random from pathlib import Path from typing import List, Set HANGMAN_STAGES = [ r""" +---+ | | | | | | ========= """, r""" +---+ | | O | | | | ========= """, r""" +---+ ...
deepakv30/Hangman
hangman.py
.py
1851c1bd8a01f3e6
7
0