text
stringlengths
185
73.3k
repo
stringlengths
7
100
path
stringlengths
4
146
language
stringclasses
7 values
hash
stringlengths
16
16
score
float64
7
8.5
stars
int64
0
237k
from typing import Optional, Union, List import torch from reclib.modules import CompressedInteractionNetwork from reclib.modules import FeedForward from reclib.modules.embedders import LinearEmbedder, Embedding class ExtremeDeepFactorizationMachine(torch.nn.Module): """ This implements xDeepFM from `"xDeep...
p-null/reclib
reclib/models/extreme_deep_factorization_machine.py
.py
7bfbafaaf2b82d06
7.45
7
import torch from reclib.modules import FactorizationMachine from reclib.modules.embedders import LinearEmbedder, Embedding class FactorizationMachine(torch.nn.Module): """ A pytorch implementation of Factorization Machine. `"Factorization Machines"<https://ieeexplore.ieee.org/abstract/document/5694074>`_ ...
p-null/reclib
reclib/models/factorization_machine.py
.py
ba0b1b89cbc5d52a
7.45
7
import torch from reclib.modules import FieldAwareFactorizationLayer from reclib.modules.embedders import LinearEmbedder class FieldAwareFactorizationMachine(torch.nn.Module): """ A pytorch implementation of Field-aware Factorization Machine. Parameters ---------- Reference: Y Juan, ...
p-null/reclib
reclib/models/field_aware_factorization_machine.py
.py
824c07235afcce70
7.45
7
""" :py:class:`Model` is an abstract class representing an reclib model. """ import logging import torch from reclib.common.registrable import Registrable logger = logging.getLogger(__name__) # pylint: disable=invalid-name # When training a model, many sets of weights are saved. By default we want to # save/load t...
p-null/reclib
reclib/models/model.py
.py
4506c36b1703ec99
7.45
7
# ruff: noqa: E501 # pylint: disable=too-many-lines,trailing-whitespace """ annofabapiのmodelをDataClassで定義したクラス Note: このファイルはopenapi-generatorで自動生成される。詳細は generate/README.mdを参照. oneOf, allOfなどは正しく表現できない可能性がある。 """ from dataclasses import dataclass from typing import Any # pylint: disable=unused-import from ...
kurusugawa-computer/annofab-api-python-client
annofabapi/dataclass/annotation_specs.py
.py
2c6f4cfebf504238
7.04
11
# pylint: disable=too-many-lines,trailing-whitespace """ annofabapiのmodelをDataClassで定義したクラス Note: このファイルはopenapi-generatorで自動生成される。詳細は generate/README.mdを参照. oneOf, allOfなどは正しく表現できない可能性がある。 """ from dataclasses import dataclass from typing import Any # pylint: disable=unused-import from dataclasses_json im...
kurusugawa-computer/annofab-api-python-client
annofabapi/dataclass/input.py
.py
ec9e82720f3101fb
7.54
11
# Copyright (c) 2014 OpenStack Foundation. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
openstack/octavia-lib
octavia_lib/hacking/checks.py
.py
0b5aa9b166dff4c0
7.42
6
from github_status_checker.api import API from github_status_checker.models.summary import Summary class Commands(object): # map component arguments to component IDs _COMPONENT_MAP = { "git": "8l4ygp009s5s", "api": "brv1bkgrwx7q", "webhooks": "4230lsnqdsld", "issues_prs_projec...
rapid7/github-status-checker
github_status_checker/controllers/commands.py
.py
86981b08be7deb4f
7.42
6
from os import makedirs, path from typing import Optional, Union import cadquery as cq from OCP.Message import Message, Message_Gravity # type: ignore class StepConstants: THT_LEAD_SOLDER_LENGTH = 3.0 # Lead length on the PCB solder side class StepColor: COPPER = cq.Color('gold2') IC_BODY = cq.Color...
LibrePCB/librepcb-parts-generator
cadquery_helpers.py
.py
941e8cac563612ce
7.62
16
""" Common functionality for generator scripts. """ import collections import csv import re from datetime import datetime from os import path from typing import Any, Dict, List, OrderedDict, Union def init_cache(uuid_cache_file: str) -> Dict[str, str]: print('Loading cache: {}'.format(uuid_cache_file)) uuid...
LibrePCB/librepcb-parts-generator
common.py
.py
ad9c6a48f301d712
7.62
16
from os import makedirs, path from typing import Any, Iterable, List # String escape sequences STRING_ESCAPE_SEQUENCES = ( ('\\', '\\\\'), # Must be the first one to avoid recursion! ('\b', '\\b'), ('\f', '\\f'), ('\n', '\\n'), ('\r', '\\r'), ('\t', '\\t'), ('\v', '\\v'), ('"', '\\"')...
LibrePCB/librepcb-parts-generator
entities/helper.py
.py
b6744600d0164923
7.62
16
""" Generate DO packages. - JEDEC DO-214 https://www.jedec.org/system/files/docs/DO-214D.PDF """ import sys from os import path from uuid import uuid4 from typing import Optional from common import format_ipc_dimension as fd from common import init_cache, now, save_cache from entities.common import ( Align, ...
LibrePCB/librepcb-parts-generator
generate_do.py
.py
9d9c38a82e8d6eea
7.62
16
""" Generate only the 3D models for various SoM, DevKits, etc. """ from os import path import cadquery as cq from cadquery_helpers import StepAssembly, StepColor, StepConstants from common import init_cache CU_THICKNESS = 0.05 # Initialize UUID caches connectors_uuid_cache = init_cache('uuid_cache_connectors.csv'...
LibrePCB/librepcb-parts-generator
generate_modules.py
.py
c1220075e5ff17e2
7.62
16
""" Generate dual mosfet devices. """ from os import makedirs, path from uuid import uuid4 from typing import Any, Dict, Iterable, List, Optional from common import init_cache, now, save_cache generator = 'librepcb-parts-generator (generate_mosfet_dual.py)' # Initialize UUID cache uuid_cache_file = 'uuid_cache_mos...
LibrePCB/librepcb-parts-generator
generate_mosfet_dual.py
.py
da0bdbf524b3204b
7.62
16
""" Generate mounting hole packages & devices - ISO4762: https://cdn.standards.iteh.ai/samples/34460/06335046afaf46fb8e84d91a3eda001d/ISO-4762-2004.pdf - ISO7380: https://cdn.standards.iteh.ai/samples/78699/a175805085534f98983d6c8aa583a5b0/ISO-7380-1-2022.pdf - ISO14580: https://cdn.standards.iteh.ai/samples/56456/880...
LibrePCB/librepcb-parts-generator
generate_mounting_holes.py
.py
c19fb3fb9c892255
7.62
16
import pytest import generate_connectors @pytest.mark.parametrize( ['pin_number', 'pin_count', 'rows', 'spacing', 'y'], [ # Special case: 1 (1, 1, 1, 2.54, 0), # Odd number of pins (1, 5, 1, 2.54, 5.08), (2, 5, 1, 2.54, 2.54), (3, 5, 1, 2.54, 0), (4, 5,...
LibrePCB/librepcb-parts-generator
test_generate_connectors.py
.py
0d2ac1d380dfa411
7.12
16
import re import string from bx_py_utils.string_utils import truncate _LOWERCASES = string.ascii_lowercase + 'äöüß' _UPPERCASES = string.ascii_uppercase + 'ÄÖÜẞ' _OTHER = ' ' + string.punctuation _ANONYMIZATION_TRANS = str.maketrans( _LOWERCASES + _UPPERCASES + string.digits + _OTHER, 'x' * len(_LOWERCASES) ...
boxine/bx_py_utils
bx_py_utils/anonymize.py
.py
4042b5d2be2c9cbd
7.42
6
from __future__ import annotations import importlib import inspect import re from pathlib import Path from bx_py_utils.filename_matcher import filename_matcher from bx_py_utils.string_utils import startswith_prefixes try: from pdoc import extract from pdoc.doc import Module except ImportError as err: _p...
boxine/bx_py_utils
bx_py_utils/auto_doc.py
.py
a795e376452ce824
7.42
6
import tempfile from bx_py_utils.aws.secret_manager import SecretsManager class ClientSideCertManager: """ Helper to manage client-side TLS certificate via AWS Secrets Manager by storing the cert/key content in a temporary file. Libraries like "requests" any many others needs the client-side TLS cer...
boxine/bx_py_utils
bx_py_utils/aws/client_side_cert_manager.py
.py
1f065f57c031f097
7.42
6
import boto3 class SecretsManager: """ Access AWS Secrets Manager values """ def __init__(self, *, region_name): session = boto3.session.Session() self.client = session.client( service_name='secretsmanager', region_name=region_name, ) def get_secre...
boxine/bx_py_utils
bx_py_utils/aws/secret_manager.py
.py
bdf4fc06acc8542c
7.42
6
from __future__ import annotations import dataclasses import re from collections.abc import Generator, Iterable from typing import Any def dict_get(item, *keys) -> None | bool | str | dict | list: """ nested dict `get()` >>> example={1: {2: 'X'}} >>> dict_get(example, 1, 2) 'X' >>> dict_get(...
boxine/bx_py_utils
bx_py_utils/dict_utils.py
.py
ecefaca6d1c693fe
7.42
6
""" DocWrite: bx_py_utils/doc_write/README.md # Doc-Write: DocStrings -> Markdown files In short: Doc-Write transfers source code DocStrings into Markdown files. The philosophy is to add documentation as near to your code as possible. This is to ensure that the documentation is not out of date. If you...
boxine/bx_py_utils
bx_py_utils/doc_write/api.py
.py
41eda25189cd00eb
7.42
6
import dataclasses from pathlib import Path @dataclasses.dataclass class GeneratedInfo: update_count: int remove_count: int paths: list[Path] @dataclasses.dataclass class DocuwriteConfig: """DocWrite: bx_py_utils/doc_write/README.md ## pyproject.toml settings [tool.doc_write] example ``` [to...
boxine/bx_py_utils
bx_py_utils/doc_write/data_structures.py
.py
117889550cdacfda
7.42
6
import ast import collections import inspect import logging import re from collections.abc import Iterator from pathlib import Path from bx_py_utils.doc_write.data_structures import DocuwriteConfig, MacroContext from bx_py_utils.doc_write.macro import process_macros from bx_py_utils.doc_write.walk import iter_file_pat...
boxine/bx_py_utils
bx_py_utils/doc_write/docstrings.py
.py
8edb27bec15717a8
7.42
6
import logging import re from collections.abc import Iterable from bx_py_utils.doc_write.data_structures import MacroContext from bx_py_utils.error_handling import exception2str from bx_py_utils.import_utils import import_string logger = logging.getLogger(__name__) class CallMacro: def __init__(self, macro_con...
boxine/bx_py_utils
bx_py_utils/doc_write/macro.py
.py
d801e51f72b5a21b
7.42
6
import os _conversion_powers = { 'KB': 1, 'MB': 2, 'GB': 3, 'TB': 4, } def cgroup_memory_usage(unit='B', cgroup_mem_file='/sys/fs/cgroup/memory/memory.usage_in_bytes'): """ Returns the memory usage of the cgroup the Python interpreter is running in. This is handy for getting the memory ...
boxine/bx_py_utils
bx_py_utils/environ.py
.py
03b416e0cb6d7edf
7.42
6
import sys TRACEBACK_MAX_CHARS = 100 DEFAULT_STOP_ON_FILE_PATH = ( '/django/core/handlers/base.py', 'django/core/management/base.py', 'django/core/handlers/exception.py', f'/python{".".join(str(v) for v in sys.version_info[:2])}/wsgiref' ) def print_exc_plus(exc=None, stop_on_file_path=None, max_ch...
boxine/bx_py_utils
bx_py_utils/error_handling.py
.py
d6dc1acf631625b8
7.42
6
from __future__ import annotations import hashlib import io import re import tempfile from collections.abc import Iterable from pathlib import Path from typing import BinaryIO class FileError(AssertionError): """ Base error class for all 'file_utils' exceptions. """ class EmptyFileError(FileError): ...
boxine/bx_py_utils
bx_py_utils/file_utils.py
.py
567a798b41772a6e
7.42
6
import inspect import json def introspection_query(depth: int): """ Generate GraphQL introspection query with variable nested depth. """ fields_query = 'kind name ofType {' * depth + 'kind name' + '}' * depth return inspect.cleandoc( '''{ __schema { types { ...
boxine/bx_py_utils
bx_py_utils/graphql_introspection.py
.py
bb12adb43f9d886e
7.92
6
import hashlib import string from bx_py_utils.dict_utils import DictCompareResult, compare_dict_values # Remove umlauts will hopefully avoid to generate valid words ;) ALPHABET = ( '-._~' # Allowed additional characters RFC 3986 'bcdfghjklmnpqrstvwxyz' # lower case letters without aeiou 'BCDFGHJKLMNPQR...
boxine/bx_py_utils
bx_py_utils/hash_utils.py
.py
563556a8f936e5b7
7.42
6
import html as _html import re from html.parser import HTMLParser from bx_py_utils.string_utils import ensure_lf from bx_py_utils.text_tools import cutout try: from lxml import etree, html # lxml is optional requirement except ModuleNotFoundError: html = None else: from lxml.etree import XMLSyntaxError ...
boxine/bx_py_utils
bx_py_utils/html_utils.py
.py
ff0361b81be19dd4
7.42
6
import sys from importlib import import_module from pathlib import Path from bx_py_utils.path import assert_is_file def cached_import(module_path, class_name): # Check whether module is loaded and fully initialized. if not ( (module := sys.modules.get(module_path)) and (spec := getattr(module...
boxine/bx_py_utils
bx_py_utils/import_utils.py
.py
276e8ebf5e74a4f2
7.42
6
import itertools def dedupe_lines(lines, *, cut_marker='...cut {count} lines...'): """ Collapse runs of 4+ identical consecutive items to first, a cut marker, and last. >>> list(dedupe_lines(['a', 'a', 'a', 'a'])) ['a', '...cut 2 lines...', 'a'] >>> list(dedupe_lines(['a', 'a', 'a', 'a'], cut_ma...
boxine/bx_py_utils
bx_py_utils/list_utils.py
.py
2f9475cd486042bf
7.42
6
# https://gist.github.com/Chiron1991/8199fc1a41c2107982053aba809838c6 # # tests functions from the gist were moved to utilities.tests.test_processify # so they can be picked up by our test runner import sys import traceback from functools import wraps from multiprocessing import Process, Queue class _ProcessifyWrapp...
boxine/bx_py_utils
bx_py_utils/processify.py
.py
85a443294dc6412f
7.42
6
import inspect from pathlib import Path from bx_py_utils.path import assert_is_file class FrameNotFound(LookupError): def __init__(self, file_path: Path): self.file_path = file_path def __str__(self): return f'Frame outside "{self.file_path}" not found!' def last_frame_outside_path(file_pa...
boxine/bx_py_utils
bx_py_utils/stack_info.py
.py
9752b69395905892
7.42
6
from __future__ import annotations import hashlib import re import unicodedata from typing import Literal from uuid import UUID def levenshtein_distance(word1: str, word2: str) -> int: """ Calculates the Levenshtein distance between two strings. >>> levenshtein_distance('planet', 'planetary') 3 ...
boxine/bx_py_utils
bx_py_utils/string_utils.py
.py
5df6f020636ff1fd
7.42
6
import difflib import pprint from typing import Any from bx_py_utils.humanize.pformat import pformat def text_ndiff(txt1, txt2, fromfile=None, tofile=None): """ Generate a `ndiff` between two text strings. (fromfile/tofile are ignored, only for compatibility with text_unified_diff signature) """ ...
boxine/bx_py_utils
bx_py_utils/test_utils/assertion.py
.py
17bab5f07c949fa3
7.92
6
from contextlib import ContextDecorator class MassContextManagerExceptions(Exception): def __init__(self, exceptions): self.exceptions = exceptions class MassContextManager(ContextDecorator): """ A context manager / decorator that enter/exit a list of mocks. e.g.: class FooBarMocks(M...
boxine/bx_py_utils
bx_py_utils/test_utils/context_managers.py
.py
87391a4e044cdeff
7.92
6
from unittest.mock import patch from bx_py_utils.test_utils.context_managers import MassContextManager class DenyCallError(SystemExit): """[no-doc] Error that will be raised on request usage. Based on SystemExit to be loud in tests ;) """ class DenyCall: """[no-doc] Will raise DenyCallError on ...
boxine/bx_py_utils
bx_py_utils/test_utils/deny_requests.py
.py
36487817bd615457
7.92
6
from pathlib import Path from bx_py_utils.error_handling import exception2str from bx_py_utils.path import assert_is_dir class FileWatcher: """ Helper to record which new files have been created. Currently the focus is: * Watch only one directory * Cleanup/remove only files """ def __i...
boxine/bx_py_utils
bx_py_utils/test_utils/filesystem_utils.py
.py
40691b4b6fca7a02
7.92
6
import logging class RaiseLogUsage(logging.Handler): """ A log handler, that raise an error on every log output. This is useful to check if tests generates not captured log output. """ def handle(self, record): raise AssertionError(f'Missing log capture for: "{self.format(record)}"') cl...
boxine/bx_py_utils
bx_py_utils/test_utils/log_utils.py
.py
f563a95736c40ce3
7.92
6
class SecretsManagerMock: """ Mock for `bx_py_utils.aws.secret_manager.SecretsManager()` """ def __init__(self, **data): self.data = data def __call__(self, *args, **kwargs): return self def get_secret(self, secret_name, force_bytes=False): secret_data = self.data[secr...
boxine/bx_py_utils
bx_py_utils/test_utils/mock_aws_secret_manager.py
.py
0c542ffe07f3d028
7.42
6
from json import JSONDecodeError from pathlib import Path from bx_py_utils.test_utils.assertion import assert_equal from bx_py_utils.test_utils.snapshot import assert_snapshot def build_requests_mock_history(mock, only_json=True): history = [] for request in mock.request_history: request_info = { ...
boxine/bx_py_utils
bx_py_utils/test_utils/requests_mock_assertion.py
.py
a42a64ab7e63d72c
7.92
6
class MockTimeMonotonicGenerator: """ Helper to mock `time.monotonic()`, `time.time()` etc. in tests. The default output is a float that starts at 1.0 and increases by 1.0 e.g.: class FooBar(TestCase): @mock.patch.object(time, 'monotonic', MockTimeMonotonicGenerator()) def test_som...
boxine/bx_py_utils
bx_py_utils/test_utils/time.py
.py
91e5cb8b7a917102
7.92
6
import torch import torch.nn as nn from Models.senet import SENet __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] def conv1x1(in_channels, out_channels, stride=1): ''' 1x1 convolution ''' return nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) d...
asdf2kr/SENet-pytorch
Models/resnet.py
.py
3eb30189be0f8414
7.45
7
import os import time import shutil import parser import argparse import torch import torch.nn import torch.optim import torchvision.models as models import Models.resnet as resnet from utils import prepare_dataloaders from tqdm import tqdm ''' reference: pytorch, torchvision conda install -c con...
asdf2kr/SENet-pytorch
main.py
.py
c9d31e4f05ffe6d9
7.45
7
''' Leak-scenario fixtures: each scenario constructs a leak whose payload objects are reachable only through a "tricky" edge (traceback, closure cell, suspended coroutine frame, C-internal cache, ...), then dumps the process object graph. Run standalone in a bare subprocess: python -m tests.scenarios.leak_cases <...
kurtbrose/objex
tests/scenarios/leak_cases.py
.py
de3d03b460507edc
8.02
10
''' Ground-truth traversal coverage audit: for every gc-tracked object the exporter saw, every `gc.get_referents` (tp_traverse) edge to another seen object must have a corresponding row in the reference table. This is the Python-upgrade regression guard: a new CPython version that introduces an object type the exporte...
kurtbrose/objex
tests/test_gc_coverage.py
.py
313c7d627fe4cfba
7.02
10
''' Leak-scenario integration tests: each scenario builds a leak in a bare subprocess whose payloads are reachable only through a "tricky" edge, dumps the graph, and this side proves the leak is *attributable* -- the payloads are found by type name and a path to a module/frame root exists that passes through the scenar...
kurtbrose/objex
tests/test_scenarios.py
.py
9d9bcffcea1942c2
7.02
10
"""Configure pytask.""" from __future__ import annotations from typing import Any from pytask import hookimpl from pytask_r.serialization import SERIALIZERS @hookimpl def pytask_parse_config(config: dict[str, Any]) -> None: """Register the r marker.""" config["markers"]["r"] = "Tasks which are executed wi...
pytask-dev/pytask-r
src/pytask_r/config.py
.py
9ca5323bc490c107
7.42
6
"""Execute tasks.""" from __future__ import annotations import shutil from pathlib import Path from typing import Any from pytask import PPathNode from pytask import PTask from pytask import PythonNode from pytask import get_marks from pytask import hookimpl from pytask.tree_util import tree_map from pytask_r.seria...
pytask-dev/pytask-r
src/pytask_r/execute.py
.py
40144798da74a73f
7.42
6
"""Contains the code to serialize keyword arguments to the task.""" from __future__ import annotations import json import uuid from collections.abc import Callable from pathlib import Path from typing import Any from typing import TypedDict from typing import cast from pytask import PTask from pytask import PTaskWit...
pytask-dev/pytask-r
src/pytask_r/serialization.py
.py
c70ee769e5e17dc5
7.42
6
"""Contains shared functions.""" from __future__ import annotations from collections.abc import Callable from collections.abc import Iterable from collections.abc import Sequence from typing import TYPE_CHECKING from typing import Any if TYPE_CHECKING: from pathlib import Path def r( *, script: str | P...
pytask-dev/pytask-r
src/pytask_r/shared.py
.py
8b48ce5af8994555
7.42
6
from __future__ import annotations import shutil import sys from contextlib import contextmanager from typing import TYPE_CHECKING import pytest from click.testing import CliRunner from pytask import storage if TYPE_CHECKING: from collections.abc import Callable needs_rscript = pytest.mark.skipif( shutil.wh...
pytask-dev/pytask-r
tests/conftest.py
.py
deee7a5a93257729
7.92
6
# pangadfs/pangadfs/fitness.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License import numpy as np from pangadfs.base import FitnessBase class FitnessDefault(FitnessBase): def fitness(self, *, population: np.ndarray, poi...
sansbacon/pangadfs
pangadfs/fitness.py
.py
bfc8aa41e70a91c9
7.45
7
# pangadfs/pangadfs/ga.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License import logging from pathlib import Path from typing import Any, Dict, Iterable, List, Union import numpy as np import pandas as pd try: from stevedore.driver import DriverManager from stevedore...
sansbacon/pangadfs
pangadfs/ga.py
.py
952ea334565e4c51
7.45
7
# pangadfs/pangadfs/metrics.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License """Population diversity and exposure metrics.""" from typing import Dict import numpy as np def diversity(population: np.ndarray) -> np.ndarray: """Calculates pairwise overlap between lineups...
sansbacon/pangadfs
pangadfs/metrics.py
.py
9855ae89007920b3
7.45
7
# pangadfs/pangadfs/mutate.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License import numpy as np from pangadfs.base import MutateBase class MutateDefault(MutateBase): def mutate(self, *, population: np.ndarray, mutation_rate: float = .05) -> np.ndarray: """Muta...
sansbacon/pangadfs
pangadfs/mutate.py
.py
c2849c705c56a2be
7.45
7
# pangadfs/pangadfs/penalty.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License """ # Penalty framework Idea is to replace optimizer rules with penalties. Penalties can be negative (bad) or positive (good). * Advantages * Doesn't throw away reasonable options (125% owners...
sansbacon/pangadfs
pangadfs/penalty.py
.py
518f8ceffa4d9827
7.45
7
# pangadfs/pangadfs/pool.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License from pathlib import Path import pandas as pd from pangadfs.base import PoolBase class PoolDefault(PoolBase): def pool(self, *, csvpth: Path, thresh: in...
sansbacon/pangadfs
pangadfs/pool.py
.py
f220cf165a4dd22a
7.45
7
# pangadfs/pangadfs/populate.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License from typing import Dict import numpy as np from pangadfs.base import PopulateBase from pangadfs.sampling import multidimensional_shifting class PopulateDefault(PopulateBase): def populate(...
sansbacon/pangadfs
pangadfs/populate.py
.py
86bf2ac2e1d09558
7.45
7
# pangadfs/pangadfs/pospool.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License from typing import Dict, Iterable import pandas as pd from pangadfs.base import PospoolBase class PospoolDefault(PospoolBase): def pospool(self, *, pool: pd.D...
sansbacon/pangadfs
pangadfs/pospool.py
.py
c3255178f3c6992f
7.45
7
# pangadfs/pangadfs/sampling.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License """Probabilistic sampling utilities for population generation.""" from typing import Iterable, Tuple import numpy as np try: from numba import njit, prange HAS_NUMBA = True except ModuleN...
sansbacon/pangadfs
pangadfs/sampling.py
.py
79d589d6ff7b1fa9
7.45
7
# pangadfs/pangadfs/validate.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License from typing import Dict import numpy as np import pandas as pd try: from numba import njit HAS_NUMBA = True except ModuleNotFoundError: HAS_NUMBA = False from pangadfs.base import Va...
sansbacon/pangadfs
pangadfs/validate.py
.py
33f8a72ccf51965d
7.45
7
# pangadfs/tests/conftest.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License from pathlib import Path import sys import pytest sys.path.append("../pangadfs") from pangadfs.pool import * from pangadfs.pospool import * from pangadfs.populate import * @pytest.fixture def pf(...
sansbacon/pangadfs
tests/conftest.py
.py
c53f1d91bca1db6f
7.95
7
import ctypes import os import subprocess import time from datetime import datetime from enum import Enum from typing import Optional, Tuple, List, Union import cv2 import jellyfish import numpy as np import psutil import pyautogui import pytesseract import win32api import win32con import win32gui import win32process ...
cetteup/BF2AutoSpectator
BF2AutoSpectator/common/utility.py
.py
c15027b8d3e6160e
8.12
16
class GlobalState: """ Holds global state variables, meaning variables not tied to an individual game instance """ __stopped: bool = False __halted: bool = False def set_stopped(self, stopped: bool) -> None: self.__stopped = stopped def stopped(self) -> bool: return self.__...
cetteup/BF2AutoSpectator
BF2AutoSpectator/global_state.py
.py
22c2609b9146061c
7.62
16
""" https://github.com/manu-p-1/cvrp constructive.py Classical constructive heuristics for generating feasible initial CVRP solutions. These produce complete route plans from scratch and are used to seed the genetic algorithm population with high-quality starting points, significantly accelerating convergence. """ im...
manu-p-1/cvrp
ocvrp/constructive.py
.py
b33fe6912484ce22
7.57
13
""" https://github.com/manu-p-1/cvrp distance.py Precomputed all-pairs Euclidean distance matrix for O(1) pairwise distance lookups. Eliminates repeated square-root computations during fitness evaluation and local search, which is the single largest performance bottleneck in evolutionary CVRP solvers. Reference: ...
manu-p-1/cvrp
ocvrp/distance.py
.py
b340bbb5cb1fe692
7.57
13
""" https://github.com/manu-p-1/cvrp parallel.py Parallelization utilities for CVRP optimization. Provides a multi-start island model that runs independent GA instances across CPU cores, and helpers for parallel population initialization. Reference: Alba, E. and Tomassini, M. (2002). "Parallelism and evolutionary...
manu-p-1/cvrp
ocvrp/parallel.py
.py
7fd70da7704a2aa9
7.57
13
""" https://github.com/manu-p-1/cvrp util.py This module contains utility functions and classes for the CVRP problem optimization """ import collections import math from json import JSONEncoder from typing import Tuple, List, Union class Building: def __init__(self, node: int, x: float, y: float, quant: int): ...
manu-p-1/cvrp
ocvrp/util.py
.py
f4401be2f0bf47c3
7.57
13
"""Quick edge-case tests for OCVRPParser refactor.""" import sys, os, tempfile sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) from ocvrp.util import OCVRPParser passed = 0 failed = 0 def check(name, condition): global passed, failed if condition: print(f" PASS {name}") pas...
manu-p-1/cvrp
testing/test_parser.py
.py
6521d7850b9a839f
8.07
13
# Copyright 2024 NWChemEx-Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
NWChemEx/NWChemEx
tests/python/unit_tests/test_compute_energy.py
.py
e2717b7f2dd8bf78
8.12
16
"""Generate api.rst autodoc and call plot_images to generate image examples""" import os import plot_images def automodule(module, image_folder): """Generates the documentation block for a specific module with links to images for each function. Args: module (str): The module file name (e.g., 'mo...
qnngroup/qnngds
docs/src/generate_api.py
.py
ec739b9c9477af26
7.5
9
"""Functions for doing FEM analysis of gdsfactory/qnngds geometries""" from collections import OrderedDict from itertools import combinations import numpy as np from qnngds.typing import LayerSpec import qnngds as qg import matplotlib.pyplot as plt try: import shapely from shapely import LineString fr...
qnngroup/qnngds
src/qnngds/analysis/fem.py
.py
8bce602533cb6923
7.5
9
"""Functions for interfacing with superscreen""" import numpy as np import qnngds as qg from qnngds.typing import LayerSpec import phidl.geometry as pg try: import superscreen as sc except ImportError: raise ImportError( "qnngds.analysis.superscreen requires superscreen to be installed" ) def ma...
qnngroup/qnngds
src/qnngds/analysis/superscreen.py
.py
e67f4b2c40c0daaa
7.5
9
"""Layout for superconducting diode `[1] <https://doi.org/10.1038/s41928-025-01376-4>`_.""" # can be removed in python 3.14, see https://peps.python.org/pep-0749/ from __future__ import annotations import qnngds as qg import numpy as np from functools import partial from qnngds.typing import LayerSpec, DeviceSpec...
qnngroup/qnngds
src/qnngds/devices/diode.py
.py
2c91445a822e816c
7.5
9
"""Single nanowire constriction.""" # can be removed in python 3.14, see https://peps.python.org/pep-0749/ from __future__ import annotations import qnngds as qg import phidl.geometry as pg from qnngds.typing import LayerSpec from qnngds import Device @qg.device def variable_length( constr_width: float = 0.1,...
qnngroup/qnngds
src/qnngds/devices/nanowire.py
.py
5eaa77c912206f6b
7.5
9
"""Layouts for resistors and resistors with superconducting contacts.""" # can be removed in python 3.14, see https://peps.python.org/pep-0749/ from __future__ import annotations import qnngds as qg import phidl.geometry as pg import numpy as np from qnngds.typing import LayerSpec, LayerSpecs from qnngds import Dev...
qnngroup/qnngds
src/qnngds/devices/resistor.py
.py
f5b2ef61732b53a8
7.5
9
"""Layout for various superconducting resonators.""" # can be removed in python 3.14, see https://peps.python.org/pep-0749/ from __future__ import annotations import qnngds as qg import numpy as np import scipy.constants from functools import partial from qnngds.typing import ( LayerSpec, LayerSpecs, De...
qnngroup/qnngds
src/qnngds/devices/resonator.py
.py
dd0995566c41b63d
7.5
9
"""Extend phidl's Layout classes: Modifications: - `Port`: add layer information - `CellArray`: add ports - `Layer`: add outline/keepout info - `CrossSection`: allow "hidden" sections """ # can be removed in python 3.14, see https://peps.python.org/pep-0749/ from __future__ import annotations from ph...
qnngroup/qnngds
src/qnngds/layout.py
.py
da341252106162fb
7.5
9
"""Pads contains functions for generation of pads and pad arrays.""" # can be removed in python 3.14, see https://peps.python.org/pep-0749/ from __future__ import annotations from qnngds.typing import LayerSpecs, DeviceSpecs, DeviceSpec import numpy as np from qnngds import Device import qnngds as qg import phidl.g...
qnngroup/qnngds
src/qnngds/pads.py
.py
187aa6b4c4388419
7.5
9
"""Pdk functions for layer and device management, mostly taken from gdsfactory""" # can be removed in python 3.14, see https://peps.python.org/pep-0749/ from __future__ import annotations from functools import partial import phidl from qnngds import Layer, LayerSet, CrossSection from qnngds.typing import ( Layer...
qnngroup/qnngds
src/qnngds/pdk.py
.py
2d9f6e6ac4347963
7.5
9
"""Teststructures contains lithographic and electrical test structures.""" # can be removed in python 3.14, see https://peps.python.org/pep-0749/ from __future__ import annotations import qnngds as qg import phidl.geometry as pg from typing import List, Optional, Tuple import numpy as np from functools import part...
qnngroup/qnngds
src/qnngds/test_structures.py
.py
bbd1e008e6644aec
7
9
"""Utilities for modifying/combining devices into more complex devices or constructing experiments.""" # can be removed in python 3.14, see https://peps.python.org/pep-0749/ from __future__ import annotations from collections.abc import Sequence from functools import partial import numpy as np from qnngds.typing i...
qnngroup/qnngds
src/qnngds/utilities.py
.py
b522291368ff6474
7.5
9
"""Basic test code""" import unittest import qnngds import pkgutil from functools import partial import phidl.path as pp import phidl.geometry as pg helper_functions = [ "compute_res_wavelength", "compute_veff", "device", "generate", "get_cross_section", "get_device", "get_layer", "get...
qnngroup/qnngds
test/test.py
.py
66f99cef978e8407
8
9
#!/usr/bin/env python3 """Merge one resolved game entry into the latest games.json. The request workflow can build against an older commit while other requests merge. Before publishing, it checks out the latest master and uses this script to reapply its resolved entry semantically instead of rebasing JSON text. """ fr...
voc0der/Skip-Game-Launcher
scripts/merge_entry.py
.py
7157aec48b529b89
7.48
8
#!/usr/bin/env python3 """Check that built launchers actually contain the launch command they should. IExpress gives no useful build-time feedback - it will happily emit an executable with the wrong payload - so this reads the command back out of each .exe and compares it against games.json. python scripts/verify...
voc0der/Skip-Game-Launcher
scripts/verify.py
.py
61d03b4217e3239a
7.48
8
"""Cross-language invariants. The Python resolver, the Python verifier and the PowerShell builder each carry their own copy of the store mapping and the launch-command formats. Nothing at runtime forces them to agree, and a silent divergence is nasty: the builder would write Ubisoft/X.exe while the workflow committed ...
voc0der/Skip-Game-Launcher
tests/test_consistency.py
.py
cab8b4024104699c
7.98
8
"""The public Markdown index is a generated view of games.json.""" from __future__ import annotations import json import pathlib import subprocess import sys from helpers import load_script REPO = pathlib.Path(__file__).resolve().parent.parent def test_committed_index_is_current(): result = subprocess.run( ...
voc0der/Skip-Game-Launcher
tests/test_index.py
.py
4789afd999ccfb8a
7.98
8
"""Tests for the Actions workflows. The important one is the interpolation rule: issue bodies are written by strangers, and `${{ }}` is substituted into the shell script *before* the shell sees it, so a title containing `$(...)` or a backtick runs on the runner. Everything untrusted has to arrive through `env:` instea...
voc0der/Skip-Game-Launcher
tests/test_workflows.py
.py
4fb9c9e10ef9a01f
7.98
8
#!/usr/bin/env python from __future__ import print_function import os.path import pkgutil import re import sys from importlib import import_module import pytest # Set environment variables as needed import os if not('GW_SURROGATE' in os.environ.keys()): os.environ["GW_SURROGATE"]='' # EOBTidalExternal - no one s...
oshaughn/research-projects-RIT
.travis/test-all-mod.py
.py
d915c8075d6b067c
7.14
18
# -*- coding: utf-8 -*- ''' Monte Carlo Integrator ---------------------- Perform an adaptive monte carlo integral. ''' from __future__ import print_function import numpy as np from . import gaussian_mixture_model as GMM import traceback import time from scipy.special import logsumexp regularize_log_scale = 1e-64 # b...
oshaughn/research-projects-RIT
MonteCarloMarginalizeCode/Code/RIFT/integrators/MonteCarloEnsemble.py
.py
36702601f50cac41
7.64
18
#! # USAGE # - directly integrate over variables. Used for distance, phase, polarization maximization. Typically uniform grid quadrature. # # from scipy.integrate import quad, dblquad, tplquad, nquad import sys import numpy as np def marginal_function(f, x_rest, args_and_ranges,g=None,epsrel=1e-5,method='def...
oshaughn/research-projects-RIT
MonteCarloMarginalizeCode/Code/RIFT/integrators/direct_quadrature.py
.py
d71979b8242bbedc
7.64
18
import sys import math #import bisect from collections import defaultdict from types import ModuleType import numpy np=numpy #import numpy as np from scipy import integrate, interpolate, special import itertools import functools xpy_default= numpy class MCSamplerGeneric(object): """ Class to define a set of...
oshaughn/research-projects-RIT
MonteCarloMarginalizeCode/Code/RIFT/integrators/mcsampler_generic.py
.py
f1e17912dd022fb7
7.64
18
# -*- coding: utf-8 -*- ''' Multivariate Truncnorm ---------------------- Draw samples from a truncated multivariate Gaussian distribution. ''' from __future__ import print_function import itertools import numpy as np from scipy.stats import truncnorm from time import time # Code adapted from http://www.aishack.in/tut...
oshaughn/research-projects-RIT
MonteCarloMarginalizeCode/Code/RIFT/integrators/multivariate_truncnorm.py
.py
98ee6b8b4925ccb3
7.64
18
import numpy import scipy.special __author__ = "Chris Pankow <pankow@gravity.phys.uwm.edu>, R. O'Shaughnessy" # # Stat utilities # def welford(x_array, mean=None,var=None,n=0): """ https://www.embeddedrelated.com/showarticle/785.php see also https://brenocon.com/blog/2008/11/calculating-running-variance-...
oshaughn/research-projects-RIT
MonteCarloMarginalizeCode/Code/RIFT/integrators/statutils.py
.py
b785fa43ce6550f9
7.64
18
#! # # REFERENCES # util_ManualOverlapGrid.py # 20160906-Pankow-ProgressPortingNRVariantToMaster/util_ManualOverlapGrid.py # import scipy.linalg as linalg import numpy as np def fit_quadratic(x,y,x0=None,variable_symmetry_list=None,gamma_x=None,prior_x_gamma=None,prior_quadratic_gamma=None,verbose=False,n_digi...
oshaughn/research-projects-RIT
MonteCarloMarginalizeCode/Code/RIFT/interpolators/BayesianLeastSquares.py
.py
f4a9b37067e7b316
7.64
18
# # # based on 'gwalk' # Fit a quadratic to likelihoods (including overall likelihood factor). # Allow code to specify a guess based on fitting a gaussian to it, for speed import numpy as np import numpy.linalg as la import scipy.linalg as linalg try: from gwalk.utils.multivariate_normal import mu_of_params,cov...
oshaughn/research-projects-RIT
MonteCarloMarginalizeCode/Code/RIFT/interpolators/ConstrainedQuadraticLikelihood.py
.py
8263eb1a8fdf95eb
7.64
18
# # efficient_save_sklearn_gp.py # # GOAL # - sklearn gp objects I use always have a simple form # - this saves a json file holding *strings* describing the kernel, AND the X_train_ and y_train_ data used in the GP # - we *may* still use a pickle for now, but it is *much* more efficient -- we're just saving the ...
oshaughn/research-projects-RIT
MonteCarloMarginalizeCode/Code/RIFT/interpolators/efficient_save_sklearn_gp.py
.py
d0e0989bb4472955
7.64
18