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 attributes_doc import attributes_doc, get_doc class TestAttributesDoc: def test__no_doc_strings__no_doc_attributes(self): # act @attributes_doc class Foo1: a = 1 b = 2 # assert assert not hasattr(Foo1, "__doc_a__") assert not hasattr(Fo...
tkukushkin/attributes-doc
tests/test_attributes_doc.py
.py
61f944beda96f644
7.02
10
import pytest from attributes_doc import attributes_doc, enum_doc enum = pytest.importorskip("enum") class TestEnumDoc: def test__no_doc_strings__no_doc_attributes(self): # act @attributes_doc @enum_doc class Foo1(enum.Enum): a = 1 b = 2 # assert ...
tkukushkin/attributes-doc
tests/test_both_decorators.py
.py
66cfeafaa334907c
8.02
10
import pytest from attributes_doc import enum_doc enum = pytest.importorskip("enum") class TestEnumDoc: def test__no_doc_strings__no_doc_attributes(self): # act @enum_doc class Foo1(enum.Enum): a = 1 b = 2 # assert assert Foo1.a.__doc__ == Foo1.__...
tkukushkin/attributes-doc
tests/test_enum_doc.py
.py
34e688a95b781496
7.02
10
from attributes_doc import get_attributes_doc class TestGetAttributesDoc: def test__no_doc_strings__no_doc_attributes(self): # arrange class Foo1: a = 1 b = 2 # act result = get_attributes_doc(Foo1) # assert assert result == {} def tes...
tkukushkin/attributes-doc
tests/test_get_attributes_doc.py
.py
5ae9bbc4ae73e2ae
7.02
10
import json from copy import deepcopy from datetime import date, datetime from json.decoder import JSONDecodeError from typing import Any, Dict, List, Optional, Tuple, Union, cast from urllib.parse import urlencode from requests import Response from requests_oauthlib import OAuth1Session import ornitho from ornitho i...
dda-dev/ornitho-client-python
ornitho/api_requester.py
.py
8a69d41521bf3075
7.48
8
from abc import ABC from typing import Any, Dict, List, Optional, Type, TypeVar, Union from ornitho.api_exception import ObjectNotFoundException from ornitho.api_requester import APIRequester # Create a generic variable that can be 'BaseModel', or any subclass. T = TypeVar("T", bound="BaseModel") class BaseModel(AB...
dda-dev/ornitho-client-python
ornitho/model/abstract/base_model.py
.py
c8953479660dd55b
7.48
8
from abc import ABC, abstractmethod from typing import Any, Dict, Optional, Type, TypeVar from ornitho.model.abstract import BaseModel # Create a generic variable that can be 'CreateableModel', or any subclass. T = TypeVar("T", bound="CreateableModel") class CreateableModel(BaseModel, ABC): """Abstract class fo...
dda-dev/ornitho-client-python
ornitho/model/abstract/createable_model.py
.py
21e130a386c75c19
7.48
8
from abc import ABC from typing import Optional, TypeVar from ornitho.model.abstract import BaseModel # Create a generic variable that can be 'DeletableModel', or any subclass. T = TypeVar("T", bound="DeletableModel") class DeletableModel(BaseModel, ABC): """Abstract class for deletable models via DELETE /ENDPO...
dda-dev/ornitho-client-python
ornitho/model/abstract/deletable_model.py
.py
f75294428a5a904e
7.48
8
from abc import ABC from datetime import date from typing import List, Optional, Tuple, Type, TypeVar, Union from ornitho.api_requester import APIRequester from ornitho.model.abstract import BaseModel # Create a generic variable that can be 'ListableModel', or any subclass. T = TypeVar("T", bound="ListableModel") c...
dda-dev/ornitho-client-python
ornitho/model/abstract/listable_model.py
.py
92f0300eacf27a50
7.48
8
from abc import ABC from datetime import date, datetime from typing import List, Optional, Tuple, Type, TypeVar, Union from ornitho.api_requester import APIRequester from ornitho.model.abstract import BaseModel # Create a generic variable that can be 'SearchableModel', or any subclass. T = TypeVar("T", bound="Searcha...
dda-dev/ornitho-client-python
ornitho/model/abstract/searchable_model.py
.py
b94b448fce1fe15c
7.48
8
from abc import ABC from typing import TypeVar from ornitho.model.abstract import BaseModel # Create a generic variable that can be 'CreateableModel', or any subclass. T = TypeVar("T", bound="UpdateableModel") class UpdateableModel(BaseModel, ABC): """Abstract class for updateable models via POST /ENDPOINT""" ...
dda-dev/ornitho-client-python
ornitho/model/abstract/updateable_model.py
.py
edd6e110f7bc06eb
7.48
8
from typing import Optional from ornitho.model.observer import Observer class Access: def __init__(self, id_observer: int, anonymous: bool, id_access: int) -> None: """Access constructor :param id_observer: Observer ID :param anonymous: Anonymous Observer :param id_access: Access ...
dda-dev/ornitho-client-python
ornitho/model/access.py
.py
e46442ccff08b593
7.48
8
from typing import Optional from ornitho.model.abstract import ListableModel from ornitho.model.taxo_group import TaxonomicGroup class Family(ListableModel): ENDPOINT: str = "families" def __init__(self, id_: int) -> None: """Family constructor :param id_: ID, which is used to get the observ...
dda-dev/ornitho-client-python
ornitho/model/family.py
.py
2bed42b282f3084f
7.48
8
from typing import List, Optional, Union from ornitho import APIException from ornitho.api_requester import APIRequester from ornitho.model.abstract import ListableModel from ornitho.model.field_option import FieldOption class Field(ListableModel): ENDPOINT: str = "fields" def __init__(self, id_: int) -> No...
dda-dev/ornitho-client-python
ornitho/model/field.py
.py
3f4da500f156e511
7.48
8
class Project: def __init__(self, id_: int, project_code: str, project_name: str) -> None: """project constructor :param id_: ID in th ornitho system :param project_code: Shot project Code :param project_name: Full project name :type id_: int :type project_code: str ...
dda-dev/ornitho-client-python
ornitho/model/project.py
.py
ddf59acddcc592e3
7.48
8
from datetime import date, datetime from typing import Dict, List, Optional, Tuple, Union from ornitho.api_requester import APIRequester from ornitho.model.abstract import ListableModel from ornitho.model.access import Access from ornitho.model.entity import Entity from ornitho.model.observation import Observation fro...
dda-dev/ornitho-client-python
ornitho/model/protocol.py
.py
90782cf971bae249
7.48
8
from typing import List, Union from ornitho import APIRequester class Right: ENDPOINT: str = "observers/rights" def __init__(self, id_: int, name: str, comment: str) -> None: """Detail constructor :param id: ID :param name: Name :param comment: Comment :type id: int ...
dda-dev/ornitho-client-python
ornitho/model/right.py
.py
47e2f89f9822504b
7.48
8
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import logging import pickle import warnings from typing import Any, Dict, Optional import yaml from requre.objects import ObjectStorage from requre.simple_object import Simple, Tuple, Void logger = logging.getLogger(__name__) GUESS_STR ...
packit/requre
requre/guess_object.py
.py
516498d7802e3238
7.42
6
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT from typing import Any, Callable, List from git.remote import FetchInfo from git.util import IterableList from requre.storage import PersistentObjectStorage from requre.objects import ObjectStorage from requre.helpers.files import StoreFil...
packit/requre
requre/helpers/git/fetchinfo.py
.py
2602522f3f9aba5d
7.42
6
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import os from typing import Any, Callable from git.refs.head import HEAD from git.remote import PushInfo from git.repo.base import Repo from git.util import IterableList from requre.objects import ObjectStorage from requre.helpers.files ...
packit/requre
requre/helpers/git/pushinfo.py
.py
1de5908ccbcea84e
7.42
6
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import functools import logging import os from typing import Any, Optional from warnings import warn from requre.cassette import Cassette, CassetteExecution from requre.objects import ObjectStorage from requre.record_and_replace import ( ...
packit/requre
requre/helpers/tempfile.py
.py
e27cc1d20e281266
7.42
6
#!/usr/bin/python3 # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import os import sys import shutil import click import importlib.util import atexit from typing import Any import yaml import builtins from requre.import_system import UpgradeImportSystem from requre.postprocessing impor...
packit/requre
requre/requre_patch.py
.py
12091efc21c53ad4
7.42
6
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT from typing import Any, Dict, Optional from requre.objects import ObjectStorage class Simple(ObjectStorage): """ Use this object, when your output is directly YAML serializable, basic objects e.g. string, number, boolean, ...
packit/requre
requre/simple_object.py
.py
f948e20e5c90b4a0
7.42
6
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import inspect import logging import shlex import subprocess from enum import Enum from pathlib import Path from _pytest.python import Function from requre.constants import RELATIVE_TEST_DATA_DIRECTORY, DEFAULT_SUFIX from requre.exception...
packit/requre
requre/utils.py
.py
da0d6d13100b7053
7.42
6
import sys import nzpy import pytest # Check if running in Jython if 'java' in sys.platform: from javax.net.ssl import TrustManager, X509TrustManager from jarray import array from javax.net.ssl import SSLContext class TrustAllX509TrustManager(X509TrustManager): '''Define a custom TrustManage...
IBM/nzpy
tests/test_connection.py
.py
debb5cb88a240023
8.04
11
import time import warnings import nzpy import pytest ''' Python DB API 2.0 driver compliance unit test suite. This software is Public Domain and may be used without restrictions. "Now we have booze and barflies entering the discussion, plus rumours of DBAs on drugs... and I won't tell you what flashes throug...
IBM/nzpy
tests/test_dbapi20.py
.py
0597a25574ecc849
7.04
11
#!/usr/bin/env python3 """ Property-based fuzzing of the span invariants. The scanner's guarantees (verbatim slices, ordered non-overlapping spans trimmed of whitespace, whitespace-only gaps) hold for ANY input, linguistic or not. That makes them ideal for fuzzing: Hypothesis can hunt for offset corruption, lost char...
carlosplanchon/tokenizesentences
tests/test_properties.py
.py
0649c93dc3acdc1f
7.92
6
#!/usr/bin/env python3 """ Heuristic English sentence tokenizer. Index-based scanner inspired by the answer of D Greenberg in StackOverflow: https://stackoverflow.com/questions/4576077/python-split-text-on-sentences The input text is never mutated, only sliced: every sentence returned is a literal substring of the i...
carlosplanchon/tokenizesentences
tokenizesentences/tokenizesentences.py
.py
fcd39323b65db11b
7.42
6
#!/usr/bin/env python3 """ Regenerate tests/test_golden_rules.py from pragmatic_segmenter's README. The Golden Rules (English) live in the README of https://github.com/diasks2/pragmatic_segmenter (MIT license, Copyright (c) 2015 Kevin S. Dias). This tool parses that section, runs the current engine over every rule an...
carlosplanchon/tokenizesentences
tools/gen_golden_rules.py
.py
b8157d7e9b2ef059
7.42
6
# # Copyright 2019 Google LLC # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 ...
GoogleCloudPlatform/gce-automated-ad-join
ad-joining/register-computer/ad/domain.py
.py
09187b950ecda4f3
7.57
13
#!/usr/bin/env python3 import logging import shutil # This creates the log object class Log: logger = None logging_file = "" logging_dir = "" # Initialize the Class def __init__(self, logging_dir=""): from geniusbot.services.backend_adapter import backend xdg_log_dir = backend.r...
Knuckles-Team/geniusbot
geniusbot/logger.py
.py
ab81ee608574ee10
7.45
7
#!/usr/bin/env python3 from PySide6.QtCore import Qt from PySide6.QtWidgets import ( QFrame, QHBoxLayout, QHeaderView, QLabel, QPushButton, QSplitter, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from geniusbot.qt.colors import BG_SECONDARY, BORDER_COLOR class Infr...
Knuckles-Team/geniusbot
geniusbot/qt/infra_cockpit.py
.py
605d98dc45dd0fff
7.45
7
#!/usr/bin/env python3 from PySide6.QtCore import Qt, QTimer from PySide6.QtWidgets import ( QFrame, QHBoxLayout, QLabel, QSplitter, QTextEdit, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, ) from geniusbot.qt.colors import BG_SECONDARY, BORDER_COLOR class TelemetryDashboar...
Knuckles-Team/geniusbot
geniusbot/qt/telemetry_dashboard.py
.py
93c61d881d9909be
7.45
7
import fcntl import os import pty import select import struct import termios from PySide6.QtCore import QObject, QThread, Signal, Slot from PySide6.QtWebChannel import QWebChannel from PySide6.QtWebEngineWidgets import QWebEngineView class TerminalBridge(QObject): """Bridge for bidirectional communication betwee...
Knuckles-Team/geniusbot
geniusbot/qt/terminal_widget.py
.py
4081163fca0dead7
7.45
7
import json from PySide6.QtCore import Qt from PySide6.QtWidgets import ( QDialog, QHBoxLayout, QLabel, QPushButton, QTextEdit, QVBoxLayout, ) from geniusbot.qt.colors import ( ACCENT_PRIMARY, ACCENT_SUCCESS, BG_PRIMARY, BG_SECONDARY, BORDER_COLOR, TEXT_MAIN, ) class ...
Knuckles-Team/geniusbot
geniusbot/qt/tool_guard.py
.py
a9120169ae34393c
7.45
7
from PySide6.QtCore import Qt, Signal from PySide6.QtWidgets import ( QFrame, QHBoxLayout, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget, ) from geniusbot.qt.colors import ( ACCENT_PRIMARY, BG_PRIMARY, BG_SECONDARY, BORDER_COLOR, TEXT_MAIN, TEXT_MUTED, ) from ...
Knuckles-Team/geniusbot
geniusbot/qt/widget_mapper.py
.py
8975a5b050f031f5
7.45
7
import asyncio from collections.abc import Callable from typing import Any from PySide6.QtCore import QObject, QRunnable, QThreadPool, Signal class AgentBridgeSignals(QObject): """Signals for reporting agent run outcomes to the main UI thread.""" started = Signal() finished = Signal(dict) error = Si...
Knuckles-Team/geniusbot
geniusbot/utils/agent_bridge.py
.py
1efe15d9d51323a7
7.45
7
from PySide6.QtCore import QObject, Signal from PySide6.QtGui import QAction, QIcon from PySide6.QtWidgets import QMenu, QSystemTrayIcon class GeniusBotDaemon(QObject): """Cockpit background tray daemon managing window states and quick actions.""" show_requested = Signal() terminal_requested = Signal() ...
Knuckles-Team/geniusbot
geniusbot/utils/daemon.py
.py
3a6a86c355570bee
7.45
7
#!/usr/bin/env python3 import importlib.metadata import logging import os # Resolve centralized log directory via the single backend seam from geniusbot.services.backend_adapter import backend geniusbot_log_dir = backend.resolve_log_dir() geniusbot_log_dir.mkdir(parents=True, exist_ok=True) geniusbot_log_path = geniu...
Knuckles-Team/geniusbot
geniusbot/utils/utils.py
.py
90361f454f939cfb
7.45
7
"""Run an Agent Utilities gate against this checkout in an isolated worktree.""" from __future__ import annotations import argparse import os import shutil import subprocess import sys from pathlib import Path def _is_agent_utilities_root(path: Path) -> bool: """Return whether *path* contains the framework and ...
Knuckles-Team/geniusbot
scripts/run_agent_utilities_gate.py
.py
42716b7859aebcb3
7.45
7
"""Enforce the backend-adapter seam invariant. Only ``geniusbot/services/backend_adapter.py`` may import from ``agent_utilities``. Every other module must route backend access through the adapter facade. This test scans the source tree to guarantee the coupling stays a single swappable seam. """ import re from pathli...
Knuckles-Team/geniusbot
tests/test_backend_adapter_seam.py
.py
d48729fe031597b2
7.95
7
#!/usr/bin/env python3 import inspect import pytest from geniusbot.qt.data_query_panel import DataQueryPanel from geniusbot.qt.federated_search_panel import FederatedSearchPanel from geniusbot.qt.finance_cockpit import FinanceCockpitPanel from geniusbot.qt.graph_explorer import GraphExplorerPanel from geniusbot.qt.i...
Knuckles-Team/geniusbot
tests/test_cockpit_views.py
.py
91fdd2dae10ea219
7.95
7
import os import re # Paths TEST_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(TEST_DIR) WORKSPACE_DIR = os.path.dirname(ROOT_DIR) MASTER_OVERVIEW_PATH = os.path.join( WORKSPACE_DIR, "agent-utilities", "docs", "overview.md" ) def extract_concepts_from_overview(filepath): """Extr...
Knuckles-Team/geniusbot
tests/test_concept_parity.py
.py
341006176628ee2d
7.95
7
"""Tests for the geniusbot KG extraction cockpit (CONCEPT:AU-ECO.connector.git-task-resolver). Qt runs offscreen (conftest). The pure layout math is tested without a display; the panel is exercised by feeding it streamed events directly. """ from __future__ import annotations import json from unittest.mock import As...
Knuckles-Team/geniusbot
tests/test_extraction_cockpit.py
.py
856bd060f2bfcd5b
7.95
7
import pytest from geniusbot.geniusbot import GeniusBot from geniusbot.qt.terminal_widget import TerminalBridge, TerminalWidget from geniusbot.qt.tool_guard import ToolGuardDialog from geniusbot.qt.widget_mapper import AgentControlPanel from geniusbot.utils.agent_bridge import AgentBridgeWorker @pytest.mark.unit @py...
Knuckles-Team/geniusbot
tests/test_geniusbot_window.py
.py
5b0bf3036a872670
7.95
7
"""Wiring tests for the Knowledge-Graph query path. CONCEPT:AU-GBOT.cockpit.through-gbot ``BackendAdapter.run_graph_query`` used to import ``run_graph_query`` from ``agent_utilities.graph`` — a symbol that does not exist there — and swallow the resulting ``ImportError``, so the Graph Explorer and the temporal-graph p...
Knuckles-Team/geniusbot
tests/test_graph_query_wiring.py
.py
33b0140ed6452a1a
7.95
7
"""Tests for the geniusbot temporal graph scrubber panel (CONCEPT:GB-GBOT.cockpit.gbot-7). Qt runs offscreen (conftest). The pure query/expiry math is tested without a display; the panel is exercised by feeding it fact rows directly and checking that expired edges are flagged for the greyed/dashed renderer. """ from ...
Knuckles-Team/geniusbot
tests/test_temporal_graph_panel.py
.py
94e13bf1dd7978da
7.95
7
""" super_csv Django application initialization. """ from django.apps import AppConfig class SuperCSVConfig(AppConfig): """ Configuration for the super_csv Django application. """ name = 'super_csv' plugin_app = { 'settings_config': { 'lms.djangoapp': { 'commo...
openedx/super-csv
super_csv/apps.py
.py
6f8f709158cd1b37
7.42
6
""" Generic class-based CSV Processor. """ import csv import logging from collections import defaultdict from io import StringIO from django.utils.translation import gettext as _ from .exceptions import ValidationError from .mixins import ChecksumMixin, DeferrableMixin log = logging.getLogger(__name__) __all__ = (...
openedx/super-csv
super_csv/csv_processor.py
.py
6740fbbe54f4342d
7.42
6
""" CSV Processing mixins. ChecksumMixin generates and validates checksums on arbitrary columns. DeferrableMixin handles asynchronous processing. """ import hashlib import importlib import logging import simplejson as json from celery import shared_task from celery.result import AsyncResult from celery_utils.logged...
openedx/super-csv
super_csv/mixins.py
.py
0f3cf3f14bd89934
7.42
6
""" Database models for super_csv. """ import logging import uuid from datetime import timedelta from django.contrib.auth import get_user_model from django.core.files.base import ContentFile from django.db import models from django.utils.timezone import now from model_utils.models import TimeStampedModel log = loggi...
openedx/super-csv
super_csv/models.py
.py
fd5ee16e45669a65
7.42
6
""" Serializers for CSV operation data. """ import logging import simplejson as json from django.contrib.auth import get_user_model from django.utils.translation import gettext as _ from rest_framework import serializers from .models import CSVOperation logger = logging.getLogger(__name__) class CSVOperationDataS...
openedx/super-csv
super_csv/serializers.py
.py
a474314d4e7bc7d8
7.42
6
""" Tests for CSVProcessor """ import io from unittest import mock import ddt from django.contrib.auth import get_user_model # could use BytesIO, but this adds a size attribute from django.core.files.base import ContentFile from django.test import TestCase from super_csv import csv_processor, models class DummyPro...
openedx/super-csv
tests/test_csv.py
.py
903962482b821a29
7.92
6
#!/usr/bin/env python """ Tests for the `super-csv` models module. """ from unittest.mock import patch from django.conf import settings from django.test import TestCase from super_csv.models import CSVOperation class TestModel(TestCase): def test_expire_data(self): operation = CSVOperation.record_opera...
openedx/super-csv
tests/test_models.py
.py
02e824d70bfe6562
7.92
6
#!/usr/bin/env python """ Tests for the `super-csv` mixins module. """ import json from django.test import TestCase from super_csv.serializers import CSVOperation, CSVOperationSerializer class SerializerTestCase(TestCase): def setUp(self): super().setUp() self.data = { "total_rows"...
openedx/super-csv
tests/test_serializers.py
.py
0adb30286981fef3
7.92
6
#include <fstream> #include <iostream> /* multi line comment */ #pragma once using std::cerr; using std::cout; using std::endl; using std::ifstream; #define FOO(1) X(1) #define DEPRECATED(func) func __attribute__ ((deprecated)) #define IsPointDef(...) \ template<> \ struct IsPoint<__VA_ARGS__> \ {\...
asottile/babi-grammars
testdata/source_cpp.cpp
.cpp
b7e5da0919e7619c
7.02
10
package dockerfile import ( "io" "os" "sort" "github.com/moby/buildkit/frontend/dockerfile/command" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // Represents a single line (layer) in a Dockerfile. // For example `FROM ubuntu:xenial` type Command struct { Cmd string // lowercased command nam...
asottile/babi-grammars
testdata/source_go.go
.go
c32749c733c55fa4
7.02
10
import java.io.*; public class Employee { String name; int age; String designation; double salary; // This is the constructor of the class Employee public Employee(String name) { this.name = name; } // Assign the age of the Employee to the variable age. public void empAge(int empAge...
asottile/babi-grammars
testdata/source_java.java
.java
c086cbdf6aa693d1
7.02
10
# # bitbake helper # # Copyright (c) Cybertrust Japan Co., Ltd. # # SPDX-License-Identifier: MIT # import re import subprocess import pathlib import pprint def find_layers(): """ This function returns layer list that is sorted by layer priority. """ cmd = ["bitbake-layers", "show-layers"] process ...
miraclelinux/meta-emlinux
scripts/lib/python/bitbake_runner.py
.py
4980aa105feae236
7.52
10
# # EMLinux CVE checker. # Download and store NVD's CVE data # # Copyright (c) Cybertrust Japan Co., Ltd. # # SPDX-License-Identifier: MIT # import sqlite3 import datetime import urllib.request import urllib.parse import gzip import http import time import json import logging CVE_DATABASE_NAME = "nvd_cve_db.db" CVE_...
miraclelinux/meta-emlinux
scripts/lib/python/cve/nvd_cve.py
.py
0fb3efeba85cc73a
7.52
10
# # EMLinux CVE checker # # Copyright (c) Cybertrust Japan Co., Ltd. # # SPDX-License-Identifier: MIT # from typing import Any, Tuple from lib.python.cve.plugin.eml_cve_plugin_base import EmlCvePlugin from lib.python.cve.cve_product import CveProduct, CveProductList from lib.python.cve.cve_info import CveStatus, CveCh...
miraclelinux/meta-emlinux
scripts/lib/python/cve/plugin/eml_cve_nvd_plugin.py
.py
291f842fee6b4350
7.52
10
from packageurl import PackageURL from cyclonedx.exception import MissingOptionalDependencyException from cyclonedx.factory.license import LicenseFactory from cyclonedx.model import HashType, AttachedText from cyclonedx.model.bom import Bom from cyclonedx.model.component import Component, ComponentType from cyclonedx....
miraclelinux/meta-emlinux
scripts/lib/python/sbom/sbom_cyclonedx.py
.py
929d7fe57527e377
7.52
10
"""Objects to read and write stored climate model data. """ import json import logging import fsspec from xarray import open_zarr logger = logging.getLogger(__name__) def read(url_or_path): """Read Dataset from Zarr store Parameters ---------- url_or_path : str Location of Zarr store to re...
ClimateImpactLab/dodola
dodola/repository.py
.py
ce367983e16c145d
7.63
17
import numpy as np import pytest import xarray as xr import cftime from dodola.core import ( train_quantiledeltamapping, adjust_quantiledeltamapping, adjust_quantiledeltamapping_year, train_analogdownscaling, adjust_analogdownscaling, _add_cyclic, xclim_units_any2pint, xclim_units_pint2c...
ClimateImpactLab/dodola
dodola/tests/test_core.py
.py
240f39f91272bf39
8.13
17
import json import fsspec from xarray import Dataset, open_zarr import dodola.repository def test_memory_repository_read(): """Basic test that memory_repository.read() works""" url = "memory://test_memory_repository_read.zarr" Dataset({"bar": 321}).to_zarr(url) # Manually write to memory FS. assert d...
ClimateImpactLab/dodola
dodola/tests/test_repository.py
.py
8904fd6c4d89548b
8.13
17
from django.contrib import admin from django.contrib.admin import register from age.models import AgeRegistration from age.forms import AgeRegistrationAdminForm @register(AgeRegistration) class AgeRegistrationAdmin(admin.ModelAdmin): """Admin interface for the age registration model.""" list_display = ( ...
KiOui/TOSTI
website/age/admin.py
.py
9ea77db3c6e5d0e8
7.54
11
from django.apps import AppConfig class AgeConfig(AppConfig): """Age App Config.""" default_auto_field = "django.db.models.BigAutoField" name = "age" def ready(self): """Register signals.""" from age import signals # noqa def user_account_tabs(self, _): """Register user...
KiOui/TOSTI
website/age/apps.py
.py
55af5f67e49cb729
7.54
11
from django import forms from django.contrib.auth import get_user_model from age.models import AgeRegistration User = get_user_model() class AgeRegistrationAdminForm(forms.ModelForm): """Age Registration Admin Form.""" class Meta: """Meta class.""" model = AgeRegistration labels = ...
KiOui/TOSTI
website/age/forms.py
.py
669df3827e44c6bc
7.04
11
from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class AgeRegistration(models.Model): """Class to save an age registration.""" YIVI = "yivi" MANUAL = "manual" VERIFIED_BY_CHOICES = ( (YIVI, "Yivi"), (MANUAL, "Manually"), ) u...
KiOui/TOSTI
website/age/models.py
.py
083295723b9a59b6
7.54
11
from django.conf import settings from django.contrib.auth import get_user_model from age import models User = get_user_model() def verify_minimum_age(user: User, minimum_age: int = 18) -> bool: """Verify whether someone has a certain minimum age.""" minimum_registered_age = get_minimum_age(user) return ...
KiOui/TOSTI
website/age/services.py
.py
e525f9e827a26b59
7.54
11
from django.contrib import admin from announcements.models import Announcement @admin.register(Announcement) class AnnouncementAdmin(admin.ModelAdmin): """Manage the admin pages for the announcements.""" list_display = ("title", "since", "until", "visible") def visible(self, obj): """Is the obj...
KiOui/TOSTI
website/announcements/admin.py
.py
ca5cd5f41f718fd6
7.04
11
from announcements.services import ( validate_closed_announcements, sanitize_closed_announcements, encode_closed_announcements, ) from django.apps import apps class ClosedAnnouncementsMiddleware: """Closed Announcements Middleware.""" def __init__(self, get_response): """Initialize.""" ...
KiOui/TOSTI
website/announcements/middleware.py
.py
e3c88b98cb183be9
7.54
11
from django.db import models from django.db.models import Q from django.utils import timezone from tinymce.models import HTMLField class AnnouncementManager(models.Manager): """Announcement Manager.""" def visible(self): """Get only visible announcements.""" return self.get_queryset().filter...
KiOui/TOSTI
website/announcements/models.py
.py
c610df4d101136d6
7.54
11
import json import urllib.parse from announcements.models import Announcement def sanitize_closed_announcements(closed_announcements) -> list: """Convert a cookie (closed_announcements) to a list of id's of closed announcements.""" if closed_announcements is None or not isinstance(closed_announcements, str):...
KiOui/TOSTI
website/announcements/services.py
.py
41bed4baeec41398
7.54
11
from django.urls.converters import IntConverter from .models import Association class AssociationConverter(IntConverter): """Converter for Association model.""" def to_python(self, value): """ Cast integer to Association. :param value: the primary key of the Association :ret...
KiOui/TOSTI
website/associations/converters.py
.py
0a12d9bb29703ec1
7.54
11
from django.apps import AppConfig from django.urls import reverse class BorrelConfig(AppConfig): """Borrel Config.""" default_auto_field = "django.db.models.BigAutoField" name = "borrel" def ready(self): """Register signals.""" from borrel import signals # noqa def new_reservat...
KiOui/TOSTI
website/borrel/apps.py
.py
f1f6c2cd4b3708f9
7.54
11
import secrets from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.core.validators import MinLengthValidator from django.db import models from django.db.models import Case, When, Value from django.utils import timezone from queryable_properties.managers import ...
KiOui/TOSTI
website/borrel/models.py
.py
15945419e93ca7a4
7.54
11
from import_export.fields import Field from import_export import resources from borrel import models class ProductResource(resources.ModelResource): """Product Resource.""" category = Field(attribute="category", column_name="category") def before_import_row(self, row, row_number=None, **kwargs): ...
KiOui/TOSTI
website/borrel/resources.py
.py
fac09b3e0544c218
7.54
11
import numpy as np from scipy import fft from scipy.interpolate import UnivariateSpline from ..units import c_light def expand_1d_static_fieldmap(z0, fz0, spline_s=0): """ Expands 1D static fieldmap z, fz into r, z using splines. Cylindrically symmetric geometry. This is valid for both electric and...
ChristopherMayes/openPMD-beamphysics
beamphysics/fields/expansion.py
.py
0f097f0df6d66025
7.65
19
from typing import Optional import numpy as np from scipy.integrate import quad from scipy.optimize import curve_fit from scipy.special import ellipe, ellipk from ..fields import FieldMesh from ..units import mu_0 def C_full(kc: float, p: float, c: float, s: float) -> float: r""" Generalized complete ellipt...
ChristopherMayes/openPMD-beamphysics
beamphysics/fields/solenoid.py
.py
c593b58a8e2d6855
7.65
19
import os import numpy as np from ..readers import component_alias from ..status import ParticleStatus astra_species_name = {1: "electron", 2: "positron", 3: "proton", 4: "hydrogen"} astra_species_index = {v: k for k, v in astra_species_name.items()} # Inverse mapping astra_particle_status_names = { -1: "stand...
ChristopherMayes/openPMD-beamphysics
beamphysics/interfaces/astra.py
.py
fcfd2c251cd0294c
7.65
19
import numpy as np from ..species import mass_of from ..units import c_light # Remove from below, because this docstring is used directly in ParticleGroup # pg : ParticleGroup # The ParticleGroup instance to convert. def particlegroup_to_bmad(pg, p0c=None, tref=None): """ Convert a ParticleGroup i...
ChristopherMayes/openPMD-beamphysics
beamphysics/interfaces/bmad.py
.py
4d4827b3fc7a3bdc
7.65
19
import numpy as np def write_opal(particle_group, outfile, dist_type="emitted", verbose=False): """ OPAL's ASCII format is described in: https://gitlab.psi.ch/OPAL/Manual-2.2/wikis/distribution outfile is the name out the ASCII file to be written. dist_type is one of: 'emitted' : T...
ChristopherMayes/openPMD-beamphysics
beamphysics/interfaces/opal.py
.py
382207a3e1dc1a8a
7.65
19
import numpy as np from scipy.constants import physical_constants from ..species import e_charge, mec2 amu_to_rest_mass_energy = ( physical_constants["atomic mass constant energy equivalent in MeV"][0] * 1e6 ) def identify_species(mass, charge): m = round(mec2) q = round(charge * 1e20) / 1e20 if m ...
ChristopherMayes/openPMD-beamphysics
beamphysics/interfaces/simion.py
.py
40453496839d3b28
7.65
19
import numpy as np import scipy.constants mu_0 = scipy.constants.mu_0 # ------------------ # FieldMesh write T7 def write_fish_t7(fm, filePath, fmt="%10.8e", verbose=False): """ Writes a T7 file from FISH t7data dict. Input: fm: FieldMesh object filePath: requested filePath to write ...
ChristopherMayes/openPMD-beamphysics
beamphysics/interfaces/superfish.py
.py
c177086388d0270a
7.65
19
from .units import nice_array, parse_bunching_str, pmd_unit TEXLABEL = { # 'status' "t": "t", "energy": "E", "kinetic_energy": r"E_\text{kinetic}", # 'mass', "higher_order_energy_spread": r"\sigma_{E_{(2)}}", "higher_order_energy": r"E_{(2)}", "E": "E", "Ex": "E_x", "Ey": "E_y",...
ChristopherMayes/openPMD-beamphysics
beamphysics/labels.py
.py
0446f248b7f95036
7.65
19
# # Simple species module. # # TODO: replace with a real package # import scipy.constants mec2 = scipy.constants.value("electron mass energy equivalent in MeV") * 1e6 mpc2 = scipy.constants.value("proton mass energy equivalent in MeV") * 1e6 mmc2 = scipy.constants.value("muon mass energy equivalent in MeV") * 1e6 mhm...
ChristopherMayes/openPMD-beamphysics
beamphysics/species.py
.py
0685c4b70e159446
7.15
19
from typing import Tuple import numpy as np from scipy import stats as scipy_stats def norm_emit_calc(particle_group, planes=["x"]): """ 2d, 4d, 6d normalized emittance calc planes = ['x', 'y'] is the 4d emittance planes = ['x', 'y', 'z'] is the 6d emittance Momenta for each plane are takes a...
ChristopherMayes/openPMD-beamphysics
beamphysics/statistics.py
.py
84672aa729d26ecc
7.65
19
from typing import Literal, Union import numpy as np import pytest from .particles import ParticleGroup def pg_from_random_normal( n_particle: int, mean: Union[np.ndarray, None] = None, cov: Union[np.ndarray, None] = None, species: str = "electron", t_or_z: Literal["t", "z"] = "z", ) -> Particle...
ChristopherMayes/openPMD-beamphysics
beamphysics/testing.py
.py
7a527ee86287b3fa
8.15
19
""" Abstract base class for wakefield models. This module provides the abstract base class that defines the interface for all wakefield implementations. Classes ------- WakefieldBase Abstract base class for all wakefield models """ from __future__ import annotations from abc import ABC, abstractmethod import m...
ChristopherMayes/openPMD-beamphysics
beamphysics/wakefields/base.py
.py
c79bf6c4fc1ad197
7.65
19
""" Impedance-based wakefield model. This module provides the ImpedanceWakefield class for defining wakefields through their impedance function Z(k). Classes ------- ImpedanceWakefield Wakefield defined through its impedance Z(k) """ from __future__ import annotations from typing import Callable import numpy a...
ChristopherMayes/openPMD-beamphysics
beamphysics/wakefields/impedance.py
.py
bc2da91330f2beea
7.65
19
""" Pseudomode wakefield representation. This module provides the pseudomode wakefield model, which represents wakefields as a sum of damped sinusoidal modes. Classes ------- Pseudomode Single pseudomode parameters (amplitude, decay, wavenumber, phase) PseudomodeWakefield Wakefield represented as a sum of pse...
ChristopherMayes/openPMD-beamphysics
beamphysics/wakefields/pseudomode.py
.py
567803bdc6621374
7.65
19
""" Impedance-based resistive wall wakefield model. This module provides the ResistiveWallWakefield class, an accurate impedance-based model for resistive wall wakefields. Classes ------- ResistiveWallWakefield Accurate impedance-based resistive wall wakefield model """ from __future__ import annotations from d...
ChristopherMayes/openPMD-beamphysics
beamphysics/wakefields/resistive_wall/impedance.py
.py
5685752fb66b5f7f
7.65
19
""" Pseudomode-based resistive wall wakefield model. This module provides the ResistiveWallPseudomode class, a fast approximation of the resistive wall wakefield using a damped sinusoidal representation. Classes ------- ResistiveWallPseudomode Fast pseudomode-based resistive wall wakefield model """ from __futur...
ChristopherMayes/openPMD-beamphysics
beamphysics/wakefields/resistive_wall/pseudomode.py
.py
6e959c96eedbedcd
7.65
19
""" Tabular wakefield representation. This module provides the TabularWakefield class for wakefields defined by user-supplied tabular data with interpolation. Classes ------- TabularWakefield Interpolation-based wakefield from user-supplied data """ from __future__ import annotations import numpy as np from sci...
ChristopherMayes/openPMD-beamphysics
beamphysics/wakefields/tabular.py
.py
9d7df11bbe809d2d
7.65
19
from dataclasses import replace from math import pi import numpy as np def drift_wavefront(w, z, backend=np, device="cpu", curvature=0): """ Propagate a wavefront `w` by distance `z` in real space, modifying each slice along the z-dimension. """ if curvature == 0: w2 = drift_wavefront_ba...
ChristopherMayes/openPMD-beamphysics
beamphysics/wavefront/propagators.py
.py
6f280fdb9f0213db
7.65
19
import torch from torch import nn from typing import Dict, List, Optional class MultiOutputUnet(nn.Module): def __init__(self, in_channels=1, output_heads: Dict[str, dict] = None, n_filter=32, **kwargs): """ Multi-output U-Net architecture supporting various output heads. Parameters ...
danihae/bio-image-unet
bio_image_unet/multi_output_unet/multi_output_unet.py
.py
93f0c632bf09438b
7.42
6
import os import shutil from pathlib import Path from typing import Tuple, List import numpy as np import tifffile import torch from albumentations import (ShiftScaleRotate, GaussNoise, ShotNoise, RandomCrop3D, RandomBrightnessContrast, Compose, Blur) from torch.utils.data import Dataset ...
danihae/bio-image-unet
bio_image_unet/multi_output_unet3d/data.py
.py
2d3965505dae781e
7.42
6
import torch from torch import nn import torch.nn.functional as F from typing import Dict class MultiOutputUnet3D(nn.Module): """ 3D U-Net architecture supporting multiple output heads (e.g., segmentation, flow). Adapted from Li, X. et al. Real-time denoising enables high-sensitivity fluorescence time-lap...
danihae/bio-image-unet
bio_image_unet/multi_output_unet3d/multi_output_unet3d.py
.py
d87d34bd43da44f6
7.42
6
import os import time from typing import Union import torch.optim as optim from matplotlib import pyplot as plt from torch.utils.data import DataLoader, random_split from tqdm import tqdm from .losses import * from .multi_output_unet3d import MultiOutputUnet3D from ..utils import init_weights, get_device class Trai...
danihae/bio-image-unet
bio_image_unet/multi_output_unet3d/train.py
.py
c4c41f0a40ea3021
7.42
6