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 |
|---|---|---|---|---|---|---|
"""
Advanced data types.
Note that these are often complementary types: the default type suffice in many
cases.
"""
from enum import StrEnum
from typing import Union
from tested.datatypes.basic import (
BasicNothingTypes,
BasicNumericTypes,
BasicObjectTypes,
BasicSequenceTypes,
BasicStringTypes,
... | dodona-edu/universal-judge | tested/datatypes/advanced.py | .py | 7268a3767e0916dd | 8 | 9 |
"""
A Marko renderer that only renders TESTed code; all other things are left alone.
"""
from marko import block
from marko.md_renderer import MarkdownRenderer
from tested.configs import Bundle
from tested.dsl import parse_dsl, parse_string
from tested.judge.evaluation import Channel, guess_expected_value, should_sho... | dodona-edu/universal-judge | tested/descriptions/renderer.py | .py | b2befb6e59d8b1a2 | 8 | 9 |
"""
Class hierarchy for the partial Dodona format.
Most concepts of the format map directly to class in this module. Besides the
modeling of the data, this module provides a serializer, which writes a Dodona
update to a given output stream. See :func:`report_update`.
When running the module from the command line, a j... | dodona-edu/universal-judge | tested/dodona.py | .py | 0fe277d9cb0ec9ed | 7 | 9 |
"""
Translate the Python AST into the TESTed AST.
This module will parse a string with a Python statement and translate it into
the TESTed AST from the serialisation module.
Note that we only support the subset of the Python syntax that is also supported
by our AST.
Some useful notes:
- The parser will convert "cas... | dodona-edu/universal-judge | tested/dsl/ast_translator.py | .py | 5123a711547429b9 | 8 | 9 |
"""
Check the consistency of i18n translation files and verify that all keys used in
the source code are present in the English base translation.
Exits with a non-zero status code if any issues are found.
"""
import re
import sys
from pathlib import Path
import yaml
from tested.datatypes import AllTypes
from tested... | dodona-edu/universal-judge | tested/internationalization/validation.py | .py | 0dbd2342c62787c1 | 8 | 9 |
import logging
from collections.abc import Iterable
from typing import IO, Literal
from tested.dodona import (
AppendMessage,
CloseContext,
CloseJudgement,
CloseTab,
CloseTest,
CloseTestcase,
EscalateStatus,
ExtendedMessage,
Message,
StartTestcase,
Status,
StatusMessage,... | dodona-edu/universal-judge | tested/judge/collector.py | .py | e3115af9892bd543 | 8 | 9 |
"""
Functions responsible for the compilation step.
"""
import logging
from pathlib import Path
from tested.configs import Bundle
from tested.dodona import Status
from tested.internationalization import get_i18n_string
from tested.judge.planning import CompilationResult, ExecutionPlan
from tested.judge.utils import (... | dodona-edu/universal-judge | tested/judge/compilation.py | .py | 98b6f1c2763ce4bc | 8 | 9 |
import logging
import shutil
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from tested.configs import Bundle
from tested.dodona import (
AppendMessage,
CloseContext,
CloseJudgement,
CloseTab,
LinkedFile,
Metadata,
StartContext,
StartJudgement,
... | dodona-edu/universal-judge | tested/judge/core.py | .py | d787a001d32eacf8 | 8 | 9 |
import logging
from collections.abc import Collection
from enum import StrEnum, unique
from pathlib import Path
from typing import Literal
from tested.configs import Bundle
from tested.dodona import (
AppendMessage,
CloseContext,
CloseJudgement,
CloseTab,
CloseTest,
CloseTestcase,
EscalateS... | dodona-edu/universal-judge | tested/judge/evaluation.py | .py | 98e345f62fdd8035 | 7 | 9 |
import itertools
import logging
import shutil
from pathlib import Path
from attrs import define
from tested.configs import Bundle
from tested.dodona import Status
from tested.judge.compilation import process_compile_results, run_compilation
from tested.judge.planning import CompilationResult, ExecutionPlan, PlannedEx... | dodona-edu/universal-judge | tested/judge/execution.py | .py | d7db65d8170686f4 | 8 | 9 |
import logging
from attrs import define
from tested.configs import Bundle
from tested.dodona import AnnotateCode, AppendMessage, Severity
from tested.judge.collector import OutputManager
_logger = logging.getLogger(__name__)
def run_linter(bundle: Bundle, collector: OutputManager, remaining: float):
"""
Ru... | dodona-edu/universal-judge | tested/judge/linter.py | .py | b6982023244d4946 | 8 | 9 |
"""
Common utilities for the judge.
"""
import logging
import shutil
import subprocess
from pathlib import Path
from attrs import define
from tested.configs import Bundle
from tested.languages.conventionalize import EXECUTION_PREFIX
from tested.languages.language import FileFilter
_logger = logging.getLogger(__name... | dodona-edu/universal-judge | tested/judge/utils.py | .py | 2d3829f4a6a87ff8 | 8 | 9 |
"""
This package contains all things related to supporting programming languages. This
ranges from the templates for actually generating the code, to the actual code
needed to execute the templates.
In short, if it has to do with the templates or is programming language specific,
you will probably find it in this pack... | dodona-edu/universal-judge | tested/languages/__init__.py | .py | ddde40f37a85bbed | 8 | 9 |
import shlex
from collections.abc import Callable
from tested.datatypes import AdvancedStringTypes, BasicStringTypes
from tested.languages.conventionalize import submission_file
from tested.languages.preparation import (
PreparedContext,
PreparedExecutionUnit,
PreparedTestcase,
PreparedTestcaseStatemen... | dodona-edu/universal-judge | tested/languages/bash/generators.py | .py | 9a10c1f0f10e923e | 7 | 9 |
import json
from typing import cast
from tested.datatypes import (
AdvancedNumericTypes,
AdvancedStringTypes,
AllTypes,
BasicBooleanTypes,
BasicNothingTypes,
BasicNumericTypes,
BasicStringTypes,
resolve_to_basic,
)
from tested.languages.preparation import (
PreparedContext,
Prep... | dodona-edu/universal-judge | tested/languages/c/generators.py | .py | 67ab02262e002a9a | 7 | 9 |
"""
Functions to conventionalize various aspects of a programming langauge.
"""
import logging
from collections.abc import Callable
from typing import TYPE_CHECKING, Literal
if TYPE_CHECKING:
from tested.languages import Language
_logger = logging.getLogger(__name__)
EXECUTION_PREFIX = "execution"
def camel_... | dodona-edu/universal-judge | tested/languages/conventionalize.py | .py | bfe546184dd77482 | 8 | 9 |
import json
from typing import cast
from tested.datatypes import AllTypes, resolve_to_basic
from tested.datatypes.advanced import (
AdvancedNumericTypes,
AdvancedSequenceTypes,
AdvancedStringTypes,
)
from tested.datatypes.basic import (
BasicBooleanTypes,
BasicNothingTypes,
BasicNumericTypes,
... | dodona-edu/universal-judge | tested/languages/cpp/generators.py | .py | 476701e7ca203c86 | 7 | 9 |
"""
Translates items from the test suite into the actual programming language.
"""
import logging
import re
import shlex
from pathlib import Path
from typing import TYPE_CHECKING, TypeAlias
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name
... | dodona-edu/universal-judge | tested/languages/generation.py | .py | c3380753d1951001 | 8 | 9 |
"""Utility files and functions for wavelengths
"""
__authors__ = "Eric Emsellem"
__copyright__ = "(c) 2017, ESO + CRAL"
__license__ = "MIT License"
__contact__ = " <eric.emsellem@eso.org>"
# Modules
from astropy import constants as const
from . import util_pipe as upipe
full_muse_wavelength_range = [4000., 10... | emsellem/pymusepipe | src/pymusepipe/emission_lines.py | .py | 4ccf86099f224d20 | 7.54 | 11 |
import json
import requests
from abc import ABC, abstractmethod
from functools import wraps
from common.logger import get_logger
logger = get_logger(__name__)
def delivery_exception_handler(method):
@wraps(method)
def wrapper(self, *args, **kwargs):
try:
self.health_check()
r... | singnet/snet-marketplace-service | common/alerts.py | .py | d86b55244d7f3d39 | 7.64 | 18 |
import io
import json
import logging
import ipfshttpclient
class IPFSUtil(object):
def __init__(self, ipfs_url, port):
self.ipfs_conn = ipfshttpclient.connect(f"/dns/{ipfs_url}/tcp/{port}/http")
def read_bytesio_from_ipfs(self, ipfs_hash):
ipfs_data = self.ipfs_conn.cat(ipfs_hash)
f... | singnet/snet-marketplace-service | common/ipfs_util.py | .py | 145ef32345f544cc | 7.64 | 18 |
from urllib.parse import urlparse
import boto3
# create an STS client object that represents a live connection to the
# STS service
class S3Util(object):
def __init__(self, aws_access_key, aws_secret_key):
self.aws_access_key = aws_access_key
self.aws_secret_key = aws_secret_key
def get_s... | singnet/snet-marketplace-service | common/s3_util.py | .py | 71e0989b35476e00 | 7.64 | 18 |
import json
from enum import EnumMeta, Enum
import os
import tarfile
import tempfile
from typing import List, Tuple, Union
from zipfile import ZipFile
from common.exceptions import BadRequestException
from contract_api.config import IPFS_URL
from common.exceptions import LighthouseInternalException
from common.logger ... | singnet/snet-marketplace-service | common/storage_provider.py | .py | f232693ab1b34e2e | 7.64 | 18 |
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from contract_api.config import NETWORK_ID, NETWORKS
from contract_api.infrastructure.models import Base
# this is the Alembic Config object, which provides
# access to the values w... | singnet/snet-marketplace-service | contract_api/alembic/env.py | .py | d94c5a146b61d955 | 7.64 | 18 |
"""unique_constraint_for_service_group_table
Revision ID: 057da5046949
Revises: 5ae9b3bdc7ce
Create Date: 2021-05-24 22:42:15.311655
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '057da5046949'
down_revision = '0cc7c0eab723'
branch_labels = None
depends_on = ... | singnet/snet-marketplace-service | contract_api/alembic/versions/057da5046949_unique_constraint_for_service_group_.py | .py | 9a51339a0aca911d | 7.64 | 18 |
"""added demoComponent flag in service metadata
Revision ID: 0cc7c0eab723
Revises: 5ae9b3bdc7ce
Create Date: 2021-05-24 13:52:35.647079
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '0cc7c0eab723'
down_revision = '5ae9b3bd... | singnet/snet-marketplace-service | contract_api/alembic/versions/0cc7c0eab723_added_democomponent_flag_in_service_.py | .py | 870416fab4c8aabf | 7.64 | 18 |
"""offchain_service_config_table_added
Revision ID: 4dd258579fce
Revises: 6947016cfc24
Create Date: 2021-07-16 16:29:39.966227
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '4dd258579fce'
down_revision = '6947016cfc24'
bra... | singnet/snet-marketplace-service | contract_api/alembic/versions/4dd258579fce_offchain_service_config_table_added.py | .py | 824aacbbb0833b0c | 7.64 | 18 |
"""create banner and cta
Revision ID: 5ae9b3bdc7ce
Revises: a5b328b4edec
Create Date: 2021-02-04 16:21:07.677755
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '5ae9b3bdc7ce'
down_revision = 'a5b328b4edec'
branch_labels = N... | singnet/snet-marketplace-service | contract_api/alembic/versions/5ae9b3bdc7ce_create_banner_and_cta.py | .py | 8f23f966a03bfc20 | 7.64 | 18 |
"""add_is_curated_for_org
Revision ID: 6947016cfc24
Revises: b7e01423560c
Create Date: 2021-06-20 22:40:33.901666
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '6947016cfc24'
down_revision = 'b7e01423560c'
branch_labels = ... | singnet/snet-marketplace-service | contract_api/alembic/versions/6947016cfc24_add_is_curated_for_org.py | .py | c8d52c54ef422bb1 | 7.64 | 18 |
"""consume_balance
Revision ID: 698ffdd6eeba
Revises: d8822b756c18
Create Date: 2019-11-14 13:17:05.359609
"""
from alembic import op
from sqlalchemy import text
# revision identifiers, used by Alembic.
revision = '698ffdd6eeba'
down_revision = 'd8822b756c18'
branch_labels = None
depends_on = None
def upgrade():
... | singnet/snet-marketplace-service | contract_api/alembic/versions/698ffdd6eeba_consume_balance.py | .py | df0f19fe7babd883 | 7.64 | 18 |
"""service_ media_ table_ create
Revision ID: a5b328b4edec
Revises: 698ffdd6eeba
Create Date: 2021-01-11 19:01:28.355682
"""
from alembic import op
from sqlalchemy import text
# revision identifiers, used by Alembic.
revision = 'a5b328b4edec'
down_revision = '698ffdd6eeba'
branch_labels = None
depends_on = None
d... | singnet/snet-marketplace-service | contract_api/alembic/versions/a5b328b4edec_service__media__table__create.py | .py | b2f237bb6e8b4a87 | 7.64 | 18 |
"""made demoComponent in seviceMetadata non nullable
Revision ID: b7e01423560c
Revises: 057da5046949
Create Date: 2021-05-25 14:46:06.899954
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'b7e01423560c'
down_revision = '057... | singnet/snet-marketplace-service | contract_api/alembic/versions/b7e01423560c_made_democomponent_in_sevicemetadata_.py | .py | d9bb93cf46b90ef8 | 7.64 | 18 |
"""baseline
Revision ID: d8822b756c18
Revises:
Create Date: 2019-09-18 14:33:54.629555
"""
from alembic import op
from sqlalchemy import text
# revision identifiers, used by Alembic.
revision = 'd8822b756c18'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
conn = op.get_bind()
c... | singnet/snet-marketplace-service | contract_api/alembic/versions/d8822b756c18_baseline.py | .py | 688c19b7cc05c41c | 7.64 | 18 |
from logging.config import fileConfig
from sqlalchemy import create_engine
from alembic import context
from iris.commons.models import Base
from iris.commons.settings import CommonSettings
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
... | dioptra-io/iris | alembic/env.py | .py | fe2cc26f511d87b9 | 7.59 | 14 |
"""probing statistics as dict
Revision ID: 03ddf61b5b3c
Revises: 8b783114dc9a
Create Date: 2022-01-11 19:00:16.273260
"""
import sqlmodel.sql.sqltypes
# revision identifiers, used by Alembic.
from sqlalchemy.dialects.postgresql import JSON
from alembic import op
revision = "03ddf61b5b3c"
down_revision = "8b783114d... | dioptra-io/iris | alembic/versions/03ddf61b5b3c_probing_statistics_as_dict.py | .py | a0d708c119e0b3e5 | 7.59 | 14 |
"""add creation_time to Measurement
Revision ID: 053cfa130101
Revises: 03ddf61b5b3c
Create Date: 2022-01-11 19:44:59.848230
"""
import sqlalchemy as sa
# revision identifiers, used by Alembic.
from sqlalchemy import func
from alembic import op
revision = "053cfa130101"
down_revision = "03ddf61b5b3c"
branch_labels ... | dioptra-io/iris | alembic/versions/053cfa130101_add_creation_time_to_measurement.py | .py | 3055f368ef3c08ed | 7.59 | 14 |
"""initial admin user
Revision ID: 2ea24c3da9ba
Revises: 16e55815e691
Create Date: 2022-01-10 17:00:33.649009
"""
import asyncio
import logging
from uuid import UUID
# revision identifiers, used by Alembic.
from fastapi_users.password import PasswordHelper
from sqlalchemy import text
from sqlalchemy.orm import Sessi... | dioptra-io/iris | alembic/versions/2ea24c3da9ba_initial_admin_user.py | .py | 35faef0a359f0269 | 7.59 | 14 |
"""add creation_time to UserTable
Revision ID: 2f6d40d1b807
Revises: 3bfd4e486e3f
Create Date: 2022-01-23 17:31:16.118882
"""
import sqlalchemy as sa
# revision identifiers, used by Alembic.
from sqlalchemy import func
from alembic import op
revision = "2f6d40d1b807"
down_revision = "3bfd4e486e3f"
branch_labels = ... | dioptra-io/iris | alembic/versions/2f6d40d1b807_add_creation_time_to_usertable.py | .py | 850cbb134f21910f | 7.59 | 14 |
"""use JSONB instead of JSON
Revision ID: 3bfd4e486e3f
Revises: 9dc1b96c99eb
Create Date: 2022-01-18 11:15:05.138792
"""
# revision identifiers, used by Alembic.
from sqlalchemy.dialects.postgresql import JSON, JSONB
from alembic import op
revision = "3bfd4e486e3f"
down_revision = "9dc1b96c99eb"
branch_labels = Non... | dioptra-io/iris | alembic/versions/3bfd4e486e3f_use_jsonb_instead_of_json.py | .py | e31f63722d7bb11f | 7.59 | 14 |
"""use JSON type for {agent,tool}_parameters
Revision ID: 5084010a40a4
Revises: e887befec67e
Create Date: 2022-01-18 10:31:33.181304
"""
import sqlmodel.sql.sqltypes
# revision identifiers, used by Alembic.
from sqlalchemy.dialects.postgresql import JSON
from alembic import op
revision = "5084010a40a4"
down_revisi... | dioptra-io/iris | alembic/versions/5084010a40a4_use_json_type_for_agent_tool__parameters.py | .py | 14c5245c69188017 | 7.59 | 14 |
"""add batch_size to MeasurementAgent
Revision ID: 8a9c14d43b43
Revises: 2f6d40d1b807
Create Date: 2022-05-25 10:13:35.407112
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "8a9c14d43b43"
down_revision = "2f6d40d1b807"
branch_labels = None
depends_on = None
... | dioptra-io/iris | alembic/versions/8a9c14d43b43_add_batch_size_to_measurementagent.py | .py | 6a9c8ffb33d2f8ba | 7.59 | 14 |
"""add user tag columns
Revision ID: 8b783114dc9a
Revises: 2ea24c3da9ba
Create Date: 2022-01-11 00:14:35.845955
"""
import sqlalchemy as sa
from sqlalchemy.orm import Session
from alembic import op
# revision identifiers, used by Alembic.
revision = "8b783114dc9a"
down_revision = "2ea24c3da9ba"
branch_labels = None... | dioptra-io/iris | alembic/versions/8b783114dc9a_add_user_tag_columns.py | .py | 417282733b6ea8b7 | 7.59 | 14 |
"""make measurement.tool non-nullable
Revision ID: 9dc1b96c99eb
Revises: 5084010a40a4
Create Date: 2022-01-18 10:35:38.662786
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "9dc1b96c99eb"
down_revision = "5084010a40a4"
branch_labels = None
depends_on = None
... | dioptra-io/iris | alembic/versions/9dc1b96c99eb_make_measurement_tool_non_nullable.py | .py | f73ba80c386d6f3c | 7.59 | 14 |
"""add database strategy
Revision ID: e887befec67e
Revises: 053cfa130101
Create Date: 2022-01-12 15:10:49.799336
"""
import fastapi_users_db_sqlalchemy
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
# revision identifiers, used by Alembic.
revision = "e887befec67e"
down_re... | dioptra-io/iris | alembic/versions/e887befec67e_add_database_strategy.py | .py | d7511a74f61c29b6 | 7.59 | 14 |
"""Agents settings."""
import logging
from enum import Enum
from pathlib import Path
from typing import Literal
from uuid import uuid4
from pydantic import model_validator
from iris.commons.settings import CommonSettings
class AgentSettings(CommonSettings):
"""Agent specific settings."""
AGENT_BACKEND: Li... | dioptra-io/iris | iris/agent/settings.py | .py | f1fee90597bc2064 | 7.59 | 14 |
import csv
import io
import subprocess
from iris.commons.logger import base_logger
def build_cmd(d):
for k, v in d.items():
if not isinstance(v, bool) or v:
yield "--" + k.replace("_", "-")
if not isinstance(v, bool):
yield str(v)
def mtr(destination, logger=base_logger,... | dioptra-io/iris | iris/agent/ttl.py | .py | c8193a83b387a1e1 | 7.59 | 14 |
"""Security management."""
import uuid
from fastapi import Depends, HTTPException, Request, status
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin
from fastapi_users.authentication import (
AuthenticationBackend,
BearerTransport,
CookieTransport,
JWTStrategy,
)
from fastapi_users.a... | dioptra-io/iris | iris/api/authentication.py | .py | af554fe76c99fe15 | 7.59 | 14 |
from collections.abc import Iterable
from ipaddress import IPv4Network, ip_network
from iris.commons.models import Tool, ToolParameters
PROBE_SIZE_GB = 100 / 1e9
"""Conservative estimate on the size of an IPv6 probe."""
# TODO: Move this function to diamond-miner.
def count_probes(targets: Iterable[str], prefix_len... | dioptra-io/iris | iris/commons/cost.py | .py | 05b4e796688763f4 | 7.59 | 14 |
from collections.abc import Iterable
from io import TextIOWrapper
from math import ceil
from typing import IO
from iris.commons.utils import zstd_stream_reader, zstd_stream_reader_text
DEFAULT_ESTIMATE_MAX_LINES = 1000
def estimate_line_size(f: IO[bytes], *, max_lines: int = DEFAULT_ESTIMATE_MAX_LINES):
"""
... | dioptra-io/iris | iris/commons/filesplit.py | .py | 4a3b62e3b78166de | 7.59 | 14 |
import json
import pydantic
import sqlmodel
from sqlalchemy import types
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import DeclarativeMeta, declarative_base, registry
from pydantic import ConfigDict
Base: DeclarativeMeta = declarative_base() # type: ignore
class BaseModel(pydantic.BaseMod... | dioptra-io/iris | iris/commons/models/base.py | .py | 668db1c3f85152d2 | 7.59 | 14 |
from typing import Generic, TypeVar
from pydantic import BaseModel, AnyHttpUrl, NonNegativeInt
from starlette.datastructures import URL
T = TypeVar("T")
class Paginated(BaseModel, Generic[T]):
"""
>>> url = URL("http://localhost:8000/test")
>>> results = [1, 2, 3, 4]
>>> p = Paginated.from_results(u... | dioptra-io/iris | iris/commons/models/pagination.py | .py | c30b609b5148577a | 7.59 | 14 |
#!/usr/bin/env python3
"""
Provenance tracking inspired by the ctapipe approach.
"""
import atexit
from contextlib import contextmanager
from datetime import datetime
from functools import lru_cache
from importlib import import_module
from importlib.metadata import distributions
import json
import os
import platform
i... | tamasgal/thepipe | thepipe/provenance.py | .py | 52d5a5ebad6107a0 | 7.59 | 14 |
# -*- coding: utf-8 -*-
# Filename: tools.py
"""
Manipulating time and so...
"""
from contextlib import contextmanager
from datetime import datetime
import os
import re
import time
from timeit import default_timer as timer
import sys
try:
import resource # linux/macos
except ImportError:
import psutil # win... | tamasgal/thepipe | thepipe/tools.py | .py | aead45d65a62faa2 | 7.59 | 14 |
import logging
from aiohttp import web
from flaat import AuthWorkflow
from flaat.aio import Flaat
from flaat.exceptions import FlaatException
from flaat.requirements import CheckResult
from flaat.requirements import get_claim_requirement
from flaat.requirements import get_vo_requirement
from flaat.user_infos import Us... | indigo-dc/flaat | examples/example_aio.py | .py | cc22a544e40d14ae | 7.57 | 13 |
# This code is distributed under the MIT License
import base64
from dataclasses import dataclass
import logging
from typing import Optional, List
import jwt
from flaat.exceptions import FlaatUnauthenticated
from flaat.issuers import IssuerConfig
logger = logging.getLogger(__name__)
# Expand this list in a sensible... | indigo-dc/flaat | flaat/access_tokens.py | .py | a60f093390ca5009 | 7.57 | 13 |
# pylint: disable=redefined-outer-name
import logging
import pytest
from aiohttp import web
from flaat.aio import Flaat
from flaat.test_env import FLAAT_TRUSTED_OPS_LIST, User, get_status_kwargs_list
flaat = Flaat()
flaat.set_trusted_OP_list(FLAAT_TRUSTED_OPS_LIST)
DECORATORS = User(flaat).get_named_decorators()
... | indigo-dc/flaat | flaat/aio/aio_test.py | .py | b82d6c15d44eb44f | 8.07 | 13 |
"""These tests are nothing AIO specific, but we can only test them with a framework.
We therefore picked AIO as an example.
FIXME The environment overrides in here are crude and will not work if run concurrently!
"""
import os
from typing import Optional
import pytest
from aiohttp import web
from flaat import ENV_V... | indigo-dc/flaat | flaat/aio/overrides_test.py | .py | e504ba03ce1338de | 7.07 | 13 |
from cachetools import LRUCache, TTLCache
from flaat.user_infos import UserInfos
class UserInfoCache(LRUCache):
"""This caches user_infos for access tokens for an unspecified time.
Before yielding UserInfos, the validity of user infos is checked."""
def __getitem__(self, key):
def _fail(msg):
... | indigo-dc/flaat | flaat/caches.py | .py | 4d3ef6fe4fe69984 | 7.57 | 13 |
import logging
from dataclasses import dataclass
from typing import List, Union
from flaat.requirements import REQUIREMENT, HasSubIss, Satisfied, Unsatisfiable
logger = logging.getLogger(__name__)
LOG_LEVEL_OVERRIDES = {
"requests_cache": logging.WARN,
"urllib3": logging.WARN,
"asyncio": logging.WARN,
}
... | indigo-dc/flaat | flaat/config.py | .py | bead4aa83f974a47 | 7.57 | 13 |
from typing import Any, Optional
class FlaatException(Exception):
"""
An error occured inside flaat. The cause can be misconfiguration
or other not user related errors.
This exception will cause a response with status 500 if unhandled.
"""
name = "Error"
status_code = 500
data: Option... | indigo-dc/flaat | flaat/exceptions.py | .py | 1adaecb401e34e0f | 7.57 | 13 |
# type: ignore
# ignore all pyright errors in this file
import json
import logging
from typing import List
from flaat import BaseFlaat, config
from flask import current_app, request
from flask.wrappers import Response
logger = logging.getLogger(__name__)
# Standard Flask Extension, see:
# https://flask.palletsproj... | indigo-dc/flaat | flaat/flask/__init__.py | .py | d79653d840b62b21 | 7.57 | 13 |
# Standard flask pytest fixture, see:
# https://flask.palletsprojects.com/en/2.1.x/testing/
# pylint: disable=redefined-outer-name
import functools
import copy
from flaat import issuers
from pytest_cases import fixture
@fixture(scope="session", params=["flaat.test_env"])
def configuration(request):
return reques... | indigo-dc/flaat | flaat/flask/conftest.py | .py | 93d96900b6929add | 8.07 | 13 |
"""
This module contains classes to express diverse requirements which a user needs to satisfy in order to use a view function.
The convenience functions :meth:`get_claim_requirement` and :meth:`get_vo_requirement` are recommended to construct individual requirements.
If you want to combine multiple requirements use ... | indigo-dc/flaat | flaat/requirements.py | .py | f88bb019f85e789c | 7.57 | 13 |
import logging
import os
from typing import Callable, List, Optional
import liboidcagent
from attr import dataclass
from dotenv import dotenv_values
from flaat import AuthWorkflow, BaseFlaat
from flaat.exceptions import FlaatException
from flaat.requirements import (
CheckResult,
HasClaim,
get_claim_requi... | indigo-dc/flaat | flaat/test_env.py | .py | 122ef8954d8cf09d | 8.07 | 13 |
from json import JSONEncoder
import logging
from time import time
from typing import Any, Optional
logger = logging.getLogger(__name__)
class UserInfos:
"""Infos about an access token and the user it belongs to.
This class acts like a dictionary with regards to claims.
So `infos["foo"]` will give you the... | indigo-dc/flaat | flaat/user_infos.py | .py | 63e141801ec5984d | 7.57 | 13 |
import datetime
import socket
from pandaharvester import commit_timestamp, panda_pkg_info
from pandaharvester.harvesterbody.agent_base import AgentBase
from pandaharvester.harvesterconfig import harvester_config
from pandaharvester.harvestercore import core_utils
from pandaharvester.harvestercore.command_spec import C... | HSF/harvester | pandaharvester/harvesterbody/command_manager.py | .py | 2d23247231b4d251 | 7.5 | 9 |
import multiprocessing
import re
import subprocess
import traceback
import psutil
from pandaharvester.harvesterbody.agent_base import AgentBase
from pandaharvester.harvesterbody.cred_manager import CredManager
from pandaharvester.harvesterconfig import harvester_config
from pandaharvester.harvestercore import core_ut... | HSF/harvester | pandaharvester/harvesterbody/service_monitor.py | .py | 8809d32e1e4f5dd1 | 7.5 | 9 |
"""
This script will be executed at container startup
- It will retrieve the proxy and panda queue from the environment
- It will download the pilot wrapper from github and execute it
- It will upload the pilot logs to panda cache at the end
post-multipart code was taken from: https://github.com/haiwen/webapi-examples... | HSF/harvester | pandaharvester/harvestercloud/pilots_starter.py | .py | c60f7d0f0e26d50a | 7.5 | 9 |
"""
Base class to communicate with WMS
"""
import abc
from pandaharvester.harvestercore import core_utils
# logger
_logger = core_utils.setup_logger("communicator")
# base class for communication with WMS
class BaseCommunicator(metaclass=abc.ABCMeta):
# constructor
def __init__(self):
pass
# ... | HSF/harvester | pandaharvester/harvestercommunicator/base_communicator.py | .py | 4ff924851c6c1843 | 7.5 | 9 |
"""
Cache class
"""
from .spec_base import SpecBase
class CacheSpec(SpecBase):
# attributes
attributesWithTypes = ("mainKey:text primary key", "subKey:text", "data:blob", "lastUpdate:timestamp")
# constructor
def __init__(self):
SpecBase.__init__(self)
| HSF/harvester | pandaharvester/harvestercore/cache_spec.py | .py | cdbf667ce50269ba | 7 | 9 |
"""
Command spec class: a panda poller will retrieve commands from panda server and store cache them internally
"""
from .spec_base import SpecBase
class CommandSpec(SpecBase):
# attributes
attributesWithTypes = ("command_id:integer primary key", "command:text", "receiver:text", "params:blob", "ack_requested... | HSF/harvester | pandaharvester/harvestercore/command_spec.py | .py | a03100dfcee119d7 | 8 | 9 |
"""
interface to give limited database access to plugins
"""
import logging
import os
import threading
from pandaharvester.harvesterconfig import harvester_config
from .db_proxy_pool import DBProxyPool
class DBInterface(object):
# constructor
def __init__(self):
self.dbProxy = DBProxyPool()
# ... | HSF/harvester | pandaharvester/harvestercore/db_interface.py | .py | 89d6287b289051de | 7.5 | 9 |
"""
dialog class
"""
import datetime
from .spec_base import SpecBase
class DiagSpec(SpecBase):
# attributes
attributesWithTypes = (
"diagID:integer primary key autoincrement",
"moduleName:text / index",
"identifier:text",
"creationTime:timestamp / index",
"lockTime:t... | HSF/harvester | pandaharvester/harvestercore/diag_spec.py | .py | ccc18abfd432d40b | 8 | 9 |
"""
Event spec class
"""
from .spec_base import SpecBase
class EventSpec(SpecBase):
# attributes
attributesWithTypes = (
"eventRangeID:text / index",
"PandaID:integer / index",
"eventStatus:text",
"coreCount:integer",
"cpuConsumptionTime:integer",
"subStatus:t... | HSF/harvester | pandaharvester/harvestercore/event_spec.py | .py | 544a2fbf91dcde70 | 8 | 9 |
import collections
import datetime
import json
import os
import pickle
import socket
import time
from calendar import timegm
from threading import get_ident
from pandaharvester.harvesterconfig import harvester_config
from pandaharvester.harvestercore import core_utils
from pandaharvester.harvestercore.db_interface imp... | HSF/harvester | pandaharvester/harvestercore/fifos.py | .py | 36658084b959a0f9 | 7.5 | 9 |
"""
File spec class
"""
from .spec_base import SpecBase
class FileSpec(SpecBase):
# file type
AUX_INPUT = "aux_input"
# attributes
attributesWithTypes = (
"fileID:integer primary key autoincrement",
"PandaID:integer / index",
"taskID:integer",
"lfn:text / index",
... | HSF/harvester | pandaharvester/harvestercore/file_spec.py | .py | aee37ca74c8648fb | 8 | 9 |
"""
Relationship between job and worker
"""
from .spec_base import SpecBase
# relationship spec
class JobWorkerRelationSpec(SpecBase):
# attributes
attributesWithTypes = (
"PandaID:integer / index",
"workerID:integer / index",
"relationType:text",
)
# constructor
def __i... | HSF/harvester | pandaharvester/harvestercore/job_worker_relation_spec.py | .py | ea65ddee9d2a69da | 7.5 | 9 |
"""
Panda Queue class
"""
from .spec_base import SpecBase
class PandaQueueSpec(SpecBase):
# attributes
attributesWithTypes = (
"queueName:text / index",
"nQueueLimitJob:integer",
"nQueueLimitWorker:integer",
"maxWorkers:integer",
"jobFetchTime:timestamp / index",
... | HSF/harvester | pandaharvester/harvestercore/panda_queue_spec.py | .py | eeda387aa5266702 | 8 | 9 |
from pilot.common.errorcodes import ErrorCodes as PilotErrorCodesObj
from pilot.util import auxiliary as PilotAux
class PilotErrors(PilotErrorCodesObj):
"""Pilot error handling"""
pilot_error_msg = PilotErrorCodesObj._error_messages
pilot_error_msg.update(
{
# can have additional erro... | HSF/harvester | pandaharvester/harvestercore/pilot_errors.py | .py | 541c735550f9ea92 | 7.5 | 9 |
"""
Process lock class
"""
from .spec_base import SpecBase
class ProcessLockSpec(SpecBase):
# attributes
attributesWithTypes = ("processName:text primary key", "lockedBy:text", "lockTime:timestamp")
# constructor
def __init__(self):
SpecBase.__init__(self)
| HSF/harvester | pandaharvester/harvestercore/process_lock_spec.py | .py | 36b0548d260e881a | 7 | 9 |
from __future__ import annotations
import random
import string
import unicodedata
import zipfile
from pathlib import Path
from typing import TYPE_CHECKING, Any
import torch
import wget # type: ignore[import-untyped]
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from torch.utils.... | TylerYep/ai-toolkit | ai_toolkit/datasets/dataset_rnn.py | .py | 5c8257b5babc78ab | 7.64 | 18 |
from torch import nn
class DenseNet(nn.Module):
"""Neural network"""
def __init__(self, input_shape):
super().__init__()
self.input_shape = input_shape
hidden_sizes = [128, 64]
output_size = 10
self.model = nn.Sequential(
nn.Linear(784, hidden_sizes[0]),
... | TylerYep/ai-toolkit | ai_toolkit/models/dense.py | .py | 52787266539182cd | 7.64 | 18 |
from efficientnet_pytorch import EfficientNet as ENet # type: ignore[import-untyped]
from torch import nn
class EfficientNet(nn.Module):
"""Neural network"""
def __init__(self, input_shape, num_classes=23, pretrained=True, b=0):
super().__init__()
self.input_shape = input_shape
model... | TylerYep/ai-toolkit | ai_toolkit/models/efficient_net.py | .py | 2d3c53094eab9a31 | 7.64 | 18 |
from torch import nn
from torchvision.models.detection import ( # type: ignore[import-untyped]
maskrcnn_resnet50_fpn,
)
from torchvision.models.detection.faster_rcnn import ( # type: ignore[import-untyped]
FastRCNNPredictor,
)
from torchvision.models.detection.mask_rcnn import ( # type: ignore[import-untyped... | TylerYep/ai-toolkit | ai_toolkit/models/maskrcnn.py | .py | 0436b9c59b61464f | 7.64 | 18 |
from __future__ import annotations
import random
import shutil
from pathlib import Path
from typing import TYPE_CHECKING, Any
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader
if TYPE_CHECKING:
from collections.abc import Iterator
from torch.optim import lr_schedul... | TylerYep/ai-toolkit | ai_toolkit/util.py | .py | d41fcbf416d85316 | 7.64 | 18 |
import sys
import warnings
from collections.abc import Iterator
from typing import Any
import torch
import torchinfo
from torch import nn
from torch.optim.optimizer import Optimizer
from ai_toolkit.args import Arguments
tqdm: Any
if "google.colab" in sys.modules:
from tqdm import tqdm_notebook as tqdm
else:
... | TylerYep/ai-toolkit | ai_toolkit/verify.py | .py | f32dafec1d6b4f0a | 7.64 | 18 |
from __future__ import annotations
import matplotlib.pyplot as plt
import torch
from torch import nn
from .viz_utils import rearrange, save_figure
def compute_saliency(inputs: torch.Tensor, run_name: str) -> None:
# Deprecated
assert inputs.grad is not None
saliency = inputs.grad.data
saliency, _ = ... | TylerYep/ai-toolkit | ai_toolkit/visualizations/saliency.py | .py | 14980031b6b8cee9 | 7.64 | 18 |
from pathlib import Path
import matplotlib.pyplot as plt
import torch
# import torchvision.transforms as T
def save_figure(run_name: str, img_name: str) -> None:
plt.tight_layout(pad=True)
if run_name:
plt.savefig(Path(f"{run_name}/{img_name}"))
plt.clf()
else:
plt.show()
def r... | TylerYep/ai-toolkit | ai_toolkit/visualizations/viz_utils.py | .py | 7ef205a795f03b84 | 7.64 | 18 |
"""Constants for component."""
import logging
from time import sleep
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_PORT, CONF_RESOURCES, CONF_SCAN_INTERVAL
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity... | golles/Home-Assistant-Sensor-MC66C | custom_components/mc66c/sensor.py | .py | 66b4c85208bea44c | 7.63 | 17 |
#!/usr/bin/env python
# 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, software
... | anarkiwi/pipette | test_pipette.py | .py | 80f0ca82f01f5280 | 8.06 | 12 |
import pytest
def pytest_addoption(parser):
parser.addoption('--run-slow', action='store_true', default=False,
help="run slow tests")
def pytest_configure(config):
config.addinivalue_line('markers', 'slow: mark test as slow to run')
def pytest_collection_modifyitems(config, items):
... | sweetpea-org/sweetpea-py | acceptance/conftest.py | .py | 9dc4733f6d24d6a2 | 7.06 | 12 |
import pytest
from sweetpea import *
from acceptance import assert_atmostkinarow, shuffled_design_sample
# Simple Factors
color = Factor("color", ["red", "blue"])
motion = Factor("motion", ["up", "down"])
task = Factor("task", ["color", "motion"])
# Response Definition
def response_left(task, color, motion):
... | sweetpea-org/sweetpea-py | acceptance/test_task_switching_simple.py | .py | 6391b480813622f9 | 7.06 | 12 |
"""
Container isolation for student code execution.
When enabled via [Container] in config.toml, every call routed through
cmd_exec runs inside a Docker container with bounded resources and only
the repo (rw), the project's tests dir (ro), and Digital.jar (ro, for
the Java image) bind-mounted in.
One container is kep... | usfca-cs-tools/autograder | src/autograder/actions/container.py | .py | 2b89f508a1d82479 | 7.45 | 7 |
from pathlib import Path
from .util import SafeConfig, load_toml, fatal
"""
Example file format:
[project04]
[[project04.dates]]
suffix = "due"
date = "2025-03-11"
percentage = 1.0
[[project04.dates]]
suffix = "late1wk"
date = "2025-03-18"
percentage = 0.5
"""
class Date(SafeConfig):
"""
Date is an elemen... | usfca-cs-tools/autograder | src/autograder/actions/dates.py | .py | 75be9faafd348000 | 7.45 | 7 |
"""
github.py uses the GitHub REST API to get the result of a GitHub action workflow
"""
import json
from io import BytesIO
from zipfile import ZipFile
from .git import *
from .server import Server
from .util import *
class GithubConfig(SafeConfig):
def __init__(self, cfg):
self.host_name = 'api.github.... | usfca-cs-tools/autograder | src/autograder/actions/github.py | .py | 9f933e73e53c851b | 7.45 | 7 |
"""
server.py is a base class for REST servers like Canvas and Github
"""
import json
from pprint import PrettyPrinter
import requests
import urllib.error
from urllib.error import HTTPError, URLError
from .util import *
class Server:
def __init__(self, host_name, token, verbose):
self.host_name = host_na... | usfca-cs-tools/autograder | src/autograder/actions/server.py | .py | 7c8567a874c2c874 | 7.45 | 7 |
"""
util.py is the "junk drawer" of code which is shared by multiple modules
"""
import sys
import tomlkit
class OutputLimitExceeded(Exception):
pass
class SafeConfig(object):
def safe_update(self, src):
# Only copy values from src when the key is in dest
# Prevents namespace pollution from T... | usfca-cs-tools/autograder | src/autograder/actions/util.py | .py | 56c9e2f022bc7f93 | 7.45 | 7 |
"""Unit tests for the Container abstraction in actions/container.py.
These cover pure-Python logic — path translation and Dockerfile-platform
parsing — so they don't need a Docker daemon. Lifecycle methods (start,
close, wrap) that shell out to `docker` are not tested here; mocking the
subprocess layer adds brittlenes... | usfca-cs-tools/autograder | tests/test_container.py | .py | d6b0607c5642c1a5 | 7.95 | 7 |
from pathlib import Path
import os
import pytest
from autograder.actions.config import Args
from autograder.actions.test import Test, TestCase
from tests.helpers import write_mini_repo, write_tests_repo
def make_args(project: str):
return Args({
'action': 'test',
'by_date': False,
'exec_c... | usfca-cs-tools/autograder | tests/test_testcase_and_runner.py | .py | 8e583c5a459b0555 | 7.95 | 7 |
"""Application path resolution and legacy-path deprecation tracking.
Resolves configuration file locations across the supported lookup
precedence (CLI flag > ``RUSHTI_DIR`` env var > legacy CWD > ``config/``)
and tracks which legacy paths have been used so a deprecation warning
can be emitted once logging is initializ... | cubewise-code/rushti | src/rushti/app_paths.py | .py | 6e4a6918f913290b | 7.56 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.