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
"""Tests for container scheduler""" import os import stat import pytest # type: ignore import shlex import tempfile from panpath import PanPath from unittest.mock import patch, MagicMock from xqute.defaults import JobStatus from xqute.schedulers.container_scheduler import ContainerScheduler @pytest.fixture(scope="...
pwwang/xqute
tests/test_container_scheduler.py
.py
ba3d1c49b7482704
7
9
"""Default settings and utilities for xqute Attributes: DEFAULT_WORKDIR_NAME: The default work directory name for jobs to save the metadata DEFAULT_ERROR_STRATEGY: The default strategy when there is error happened DEFAULT_NUM_RETRIES: Default number of retries when DEFAULT_ERROR_STRATEGY is...
pwwang/xqute
xqute/defaults.py
.py
87c1732eeb139f34
7.5
9
"""Job to execute""" from __future__ import annotations import shlex from typing import Any, Tuple from .defaults import JobStatus from .utils import logger, CommandType from .path import SpecPath class Job: """The class for job Attributes: cmd: The command index: The index of the job ...
pwwang/xqute
xqute/job.py
.py
42e4981471efc443
7.5
9
"""The scheduler to run jobs via containers""" from __future__ import annotations import asyncio import os import shlex import shutil from pathlib import Path from typing import List, Sequence from ..job import Job from ..path import SpecPath from ..defaults import DEFAULT_WORKDIR_NAME, JOBCMD_WRAPPER_LANG from .loc...
pwwang/xqute
xqute/schedulers/container_scheduler.py
.py
410414418456f282
7.5
9
"""The scheduler to run jobs locally""" import asyncio import os import shlex from ..defaults import JobStatus from ..job import Job from ..scheduler import Scheduler def _pid_exists(pid: int) -> bool: """Check if a process with a given pid exists""" try: os.kill(pid, 0) except Exception: # pra...
pwwang/xqute
xqute/schedulers/local_scheduler.py
.py
70cff3432b26e92a
7.5
9
"""The scheduler to run jobs on SGE""" import asyncio import hashlib from ..job import Job from ..scheduler import Scheduler class SgeScheduler(Scheduler): """The sge scheduler Attributes: name: The name of the scheduler job_class: The job class Args: qsub: path to qsub command...
pwwang/xqute
xqute/schedulers/sge_scheduler.py
.py
baff02cb5529a3cd
7.5
9
"""The scheduler to run jobs on Slurm""" import asyncio import hashlib from ..job import Job from ..scheduler import Scheduler class SlurmScheduler(Scheduler): """The Slurm scheduler Attributes: name: The name of the scheduler job_class: The job class Args: sbatch: path to sbat...
pwwang/xqute
xqute/schedulers/slurm_scheduler.py
.py
79a435bb77c5943c
7.5
9
"""The scheduler to run jobs on SSH""" from __future__ import annotations import asyncio import shlex from panpath import CloudPath from ...schedulers.local_scheduler import LocalScheduler from ...job import Job from ...defaults import SLEEP_INTERVAL_CLOUD_FILE_CHECK from ...utils import logger from .client import...
pwwang/xqute
xqute/schedulers/ssh_scheduler/scheduler.py
.py
b3bdbfe3622053d0
7.5
9
"""The xqute module""" from __future__ import annotations import asyncio import functools import signal from collections import deque from typing import TYPE_CHECKING, Any, List, Mapping, Type from .defaults import ( DEFAULT_WORKDIR_NAME, DEFAULT_ERROR_STRATEGY, DEFAULT_NUM_RETRIES, DEFAULT_SCHEDULER...
pwwang/xqute
xqute/xqute.py
.py
126eed84bc42fd38
7.5
9
import click import shortuuid import datetime import subprocess from enum import Enum from psycopg2 import sql from psycopg2.extras import execute_values from app import db from app import get_db_cursor from saved_scenario import SavedScenario from saved_scenario import save_raw_scenario_to_db from util import safe_co...
ourresearch/jump-api
create_consortial_package.py
.py
db43bc61c047d6d1
7.63
17
# coding: utf-8 import click from admin_actions import add_institution, add_ror, add_user @click.group() def cli(): """ Create institutions, users and add ROR IDs. Note: Quotes are required around any flag inputs with spaces. Examples: python init.py --help python init.py inst --help python init.py inst...
ourresearch/jump-api
init.py
.py
39d4b2a8def9df03
7.63
17
import os import ast import json from datetime import datetime from datetime import date from kids.cache import cache import click import requests import pandas as pd import gspread # intercom API details intercom_base = "https://api.intercom.io" key = os.getenv("INTERCOM_API_KEY") auth = {"Authorization": "Bearer "...
ourresearch/jump-api
intercom_drip.py
.py
730e1c8aa7eb3ea8
7.63
17
#!/usr/bin/env python """Wrapper for Django's command-line utility for administrative tasks.""" import os import sys import logging from time import sleep try: from django.db.migrations.executor import MigrationExecutor from django.db.utils import ConnectionHandler, DEFAULT_DB_ALIAS except ImportError as exc: ...
WikipediaLibrary/externallinks
django_wait_for_migrations.py
.py
b0e96e1745680628
7.54
11
from typing import Type from django.db import models from extlinks.aggregates.management.helpers import AggregateArchiveCommand from extlinks.aggregates.models import LinkAggregate class Command(AggregateArchiveCommand): """ This command archives data from the 'aggregates_linkaggregate' table. """ he...
WikipediaLibrary/externallinks
extlinks/aggregates/management/commands/archive_link_aggregates.py
.py
daa6acdd467bba5e
7.04
11
from typing import Type from django.db import models from extlinks.aggregates.management.helpers import AggregateArchiveCommand from extlinks.aggregates.models import PageProjectAggregate class Command(AggregateArchiveCommand): """ This command archives data from the 'aggregates_pageprojectaggregate' table. ...
WikipediaLibrary/externallinks
extlinks/aggregates/management/commands/archive_pageproject_aggregates.py
.py
ed309256c8acd0fd
7.54
11
from typing import Type from django.db import models from extlinks.aggregates.management.helpers import AggregateArchiveCommand from extlinks.aggregates.models import UserAggregate class Command(AggregateArchiveCommand): """ This command archives data from the 'aggregates_useraggregate' table. """ he...
WikipediaLibrary/externallinks
extlinks/aggregates/management/commands/archive_user_aggregates.py
.py
944e2762d4bc2c82
7.04
11
from datetime import date, timedelta, datetime from extlinks.common.management.commands import BaseCommand from django.core.management.base import CommandError from django.db import transaction, close_old_connections from django.db.models import Count, Q from django.db.models.functions import Cast from django.db.model...
WikipediaLibrary/externallinks
extlinks/aggregates/management/commands/fill_link_aggregates.py
.py
3a99476e6d92e68b
7.54
11
from datetime import date, timedelta, datetime import logging from extlinks.common.management.commands import BaseCommand from django.core.management.base import CommandError from django.db import transaction, close_old_connections from django.db.models import Count, Q from django.db.models.functions import Cast from ...
WikipediaLibrary/externallinks
extlinks/aggregates/management/commands/fill_pageproject_aggregates.py
.py
abc4f8989d9ce0f5
7.54
11
import calendar, datetime, logging from typing import Any, Dict, List, Optional, Tuple from dateutil.relativedelta import relativedelta from django.core.management.base import CommandError, CommandParser from django.db.models.aggregates import Sum from django.db.models.expressions import F from extlinks.aggregates.m...
WikipediaLibrary/externallinks
extlinks/aggregates/management/commands/fill_top_organisations_totals.py
.py
19782d2f80f22894
7.54
11
import calendar, datetime, logging from typing import Any, Dict, List, Optional, Tuple from dateutil.relativedelta import relativedelta from django.core.management.base import CommandError, CommandParser from django.db.models.aggregates import Sum from django.db.models.expressions import F from extlinks.aggregates.m...
WikipediaLibrary/externallinks
extlinks/aggregates/management/commands/fill_top_projects_totals.py
.py
defa6075b5cbe2a9
7.54
11
import calendar, datetime, logging from typing import Any, Dict, List, Optional, Tuple from dateutil.relativedelta import relativedelta from django.core.management.base import CommandError, CommandParser from django.db.models.aggregates import Sum from django.db.models.expressions import F from extlinks.aggregates.m...
WikipediaLibrary/externallinks
extlinks/aggregates/management/commands/fill_top_users_totals.py
.py
f51286987e633137
7.54
11
from datetime import date, timedelta, datetime from extlinks.common.management.commands import BaseCommand from django.core.management.base import CommandError from django.db import transaction, close_old_connections from django.db.models import Count, Q from django.db.models.functions import Cast from django.db.model...
WikipediaLibrary/externallinks
extlinks/aggregates/management/commands/fill_user_aggregates.py
.py
eef957b9ad50a6be
7.54
11
import datetime import gzip import logging import os from abc import ABC, abstractmethod from collections import defaultdict from dateutil.relativedelta import relativedelta from typing import List, Optional, Type, cast from django.core import serializers from django.core.management import call_command from django.co...
WikipediaLibrary/externallinks
extlinks/aggregates/management/helpers/aggregate_archive_command.py
.py
53ec0bd0044fb613
7.54
11
import datetime import gzip import itertools import json import logging import os import re from typing import Callable, Dict, Hashable, Iterable, List, Optional, Set from django.core.cache import cache from django.db.models import Q from extlinks.common.helpers import extract_queryset_filter from extlinks.common.sw...
WikipediaLibrary/externallinks
extlinks/aggregates/storage.py
.py
ff9ef43666c70510
7.54
11
import calendar from datetime import date, timedelta from itertools import islice from typing import Any, Dict from django.db.models import Avg, Q from django.db.models.functions import TruncMonth from logging import getLogger logger = getLogger("django") def get_month_average(average_data, check_date): for av...
WikipediaLibrary/externallinks
extlinks/common/helpers.py
.py
76b912c5c26d38a8
7.54
11
from django.core.management.base import BaseCommand as DjangoBaseCommand from filelock import FileLock import inspect import logging from os import remove from os.path import basename import sys from tenacity import Retrying, stop_after_attempt, wait_exponential logger = logging.getLogger("django") class BaseCommand...
WikipediaLibrary/externallinks
extlinks/common/management/commands/__init__.py
.py
fc1ba0f246b693f6
7.54
11
import logging import json from functools import lru_cache import getpass import platform from yasf import sf_separate log = logging.getLogger(__name__) @lru_cache() def get_user_name() -> str: return getpass.getuser() @lru_cache() def get_computer_name() -> str: return platform.node() try: # user m...
jamesabel/balsa
balsa/aws_cloudwatch_logs.py
.py
8dcfa80dbd7c9ebc
7.42
6
from typing import Union from datetime import datetime from logging import Formatter, LogRecord class BalsaFormatter(Formatter): """ Format time in ISO 8601 """ def formatTime(self, record: LogRecord, datefmt: Union[str, None] = None) -> str: if datefmt is not None: # an explicit ...
jamesabel/balsa
balsa/formatter.py
.py
98fc8c2b0e720f2a
7.42
6
import time import logging import os import threading from tobool import to_bool_strict from . import __application_name__ use_mttkinter = to_bool_strict(os.environ.get(f"{__application_name__}_USE_MTTKINTER", True)) # in case the user doesn't want to use mttkinter (multi-threaded tkinter) mttkinter_imported = Fal...
jamesabel/balsa
balsa/guihandler.py
.py
6dc4af0812c52728
7.42
6
from enum import Enum import logging class HandlerType(Enum): Console = 1 File = 2 DialogBox = 3 Callback = 4 Sentry = 5 StringList = 6 AWSCloudWatch = 7 class BalsaNullHandler(logging.NullHandler): """ Hook in a callback function. For example, this can be used to set the proces...
jamesabel/balsa
balsa/handlers.py
.py
29bf5d9ba7a8cca4
7.42
6
from datetime import datetime import re import logging import json from logging import getLogger from yasf import structured_sentinel import dateutil.parser from balsa.__version__ import __application_name__ log = getLogger(__application_name__) # timestamp - name - [processName -] fileName - lineNumber - function...
jamesabel/balsa
balsa/structured.py
.py
3a71078d70715c04
7.42
6
from typing import List import win32gui def _dialog_enum_callback(hwnd: int, dialogs: List[int]) -> None: """ Callback used by EnumWindows. Checks if the given window is a visible dialog (#32770) and contains an "OK" button among its children. """ if win32gui.IsWindowVisible(hwnd): class_n...
jamesabel/balsa
test_balsa/popup_window.py
.py
99792f67773b2e04
7.92
6
from pathlib import Path import logging import time import pyautogui import pytest from balsa import Balsa, __author__ from .popup_window import is_popup_dialog_with_ok # The fail-safe aborts pyautogui calls when the mouse is in a screen corner - where users naturally park the cursor while GUI tests run. # These te...
jamesabel/balsa
test_balsa/tst_balsa.py
.py
aab31a6a01472f57
7.92
6
#!/usr/bin/env python '''Extract a knowledge graph from a long public-domain book with a *local* LLM. Companion code for "Building and working knowledge graphs with Onya and LLMs". This is the woven, runnable version of the fragments in the "Setup", "Steering without a sampler", "Chunking", and "Checkpoint it" section...
uogbuji/techwriting
loom-deeptech/onya-kg-llm-analysis/equiano_extract.py
.py
420dc1aa9cd2c1aa
7.54
11
#!/usr/bin/env python '''Download and pre-process *The Interesting Narrative of the Life of Olaudah Equiano* (1789) into a clean plain-text file the assessment harness (and the article) can reuse without re-fetching. Preprocessing: - strip the Project Gutenberg license header/footer - trim the book's own front mat...
uogbuji/techwriting
loom-deeptech/onya-kg-llm-analysis/model_assessment/fetch_equiano.py
.py
a59ab8ab2aea741b
7.54
11
'''WordLoom prompt loading for the assessment harness. Prompts live in loom TOML files beside this module (`prompts/*.loom.toml`), never inline in Python — so they can be reviewed, diffed, and swapped without touching code, and prompt experiments can be kept as separate files on disk. See https://github.com/OoriData/W...
uogbuji/techwriting
loom-deeptech/onya-kg-llm-analysis/model_assessment/prompts/__init__.py
.py
b459ec9be365b013
7.54
11
'''WordLoom prompt loading for the extraction pipeline. Prompts live in loom TOML files beside this module (`prompts/*.loom.toml`), never inline in Python — so they can be reviewed, diffed, and swapped without touching code, and prompt experiments can be kept as separate files on disk. See https://github.com/OoriData/...
uogbuji/techwriting
loom-deeptech/onya-kg-llm-analysis/prompts/__init__.py
.py
9ad5811f601af1b8
7.54
11
import sys import json import string import random population = ' ' + string.ascii_lowercase def preprocess_frequencies(frequencies, order): '''Compile simple mapping from N-grams to frequencies into data structures to help compute the probability of state transitions to complete an N-gram Arguments: ...
uogbuji/techwriting
patternai/generate_letters_strategy1.py
.py
413b6ed634b696b7
7.54
11
import sys import json import string import random POPULAR_NGRAM_COUNT = 10000 #Population is all the possible items that can be generated population = ' ' + string.ascii_lowercase def preprocess_frequencies(frequencies, order): '''Compile simple mapping from N-grams to frequencies into data structures to help c...
uogbuji/techwriting
patternai/generate_letters_strategy2.py
.py
b9e78eaa5b6711dc
7.54
11
import sys import json import string import random POPULAR_NGRAM_COUNT = 10000 def preprocess_frequencies(frequencies, order): '''Compile simple mapping from N-grams to frequencies into data structures to help compute the probability of state transitions to complete an N-gram Arguments: frequenc...
uogbuji/techwriting
patternai/generate_words.py
.py
7a9e9bb3d31f0a0a
7.54
11
import asyncio import aiohttp from urllib.parse import urlparse #List of URLs to process URLS = [ 'http://web.textfiles.com/computers/macbeth95', 'https://www.gutenberg.org/files/1342/1342-0.txt', #Pride and Prejudice 'http://web.textfiles.com/humor/zenerror.txt', 'http://artscene.textfiles.com/history...
uogbuji/techwriting
presentation/iterator-workshop/s6_web_word_count_lab.py
.py
799287e63045c58d
7.54
11
"""A collection command line arguments.""" class Argument: """Just a wrapper around :meth:`argparse.ArgumentParser.add_argument`. So, except the ``completer`` keyword argument all positional and keywork arguments are the same as :meth:`argparse.ArgumentParser.add_argument`. :param completer: see `ar...
pylover/easycli
easycli/argument.py
.py
de923aaf7eee3ee3
7.63
17
from abc import ABCMeta from .argument import Argument class Command(metaclass=ABCMeta): """Abstract base class for all commands.""" #: List of both :class:`.Command` class or instance of :class:`.Argument` __arguments__ = [] #: str, command name __command__ = None #: List of aliases for t...
pylover/easycli
easycli/command.py
.py
cbacc8d32cb097d8
7.63
17
import sys import argparse from os import path from .command import Command class Root(Command): """base class for the CLI entry point. .. code-block:: import sys from easycli import Root, ... class Git(Root): __help__ = 'git help message' __completion__ = True...
pylover/easycli
easycli/root.py
.py
dca938259204ae8a
7.63
17
import logging import random import warnings from multiprocessing import cpu_count from typing import TYPE_CHECKING import numpy as np from numpy.typing import ArrayLike, NDArray from ._ncollpyde import ( TriMeshWrapper, _configure_threadpool, _index, _precision, ) if TYPE_CHECKING: import meshio...
clbarnes/ncollpyde
python/ncollpyde/main.py
.py
0253798a97c5b48a
7.56
12
from multiprocessing import cpu_count import meshio import numpy as np import pytest from ncollpyde import Volume SAMPLES_PER_DIM = 10 PADDING = 0.2 ITERATIONS = 20 CPU_COUNT = cpu_count() CONTAINS_SERIAL = "containment serial" INTERSECTION_SERIAL = "intersection serial" CONTAINS_PARALLEL = "containment parallel" IN...
clbarnes/ncollpyde
tests/test_bench.py
.py
eaa1cd33b7191d24
8.06
12
#!/usr/bin/env python3 """Test label filtering functionality with pytest.""" import pytest from content_resolver.config_manager import ConfigManager def create_test_settings(labels_filter=None): """Create test settings for ConfigManager.""" return { "configs": "test_configs", "output": "outpu...
fedora-eln/content-resolver
test_label_filtering.py
.py
dfe7e4e5de61d520
7.98
8
''' Default logger is a bit meh, see 'test'/run this file for a demo TODO name 'klogging' to avoid possible conflict with default 'logging' module TODO shit. too late already? maybe use fallback & deprecate ''' def test() -> None: import logging import sys from collections.abc import Callable M: Call...
karlicoss/bleanser
src/bleanser/core/ext/logging.py
.py
e4ee95173f567c92
7.6
15
from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path from typing import Any from bleanser.core.processor import ( BaseNormaliser, Normalised, sort_file, unique_file_in_tempdir, ) class ExtractObjectsNormaliser(BaseNormaliser): """ This is meant t...
karlicoss/bleanser
src/bleanser/core/modules/extract.py
.py
b9cb7219a2fb1dfd
7.6
15
from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path import orjson from bleanser.core.processor import ( BaseNormaliser, Normalised, sort_file, unique_file_in_tempdir, ) # imports for convenience -- they are used in other modules from bleanser.core.utils...
karlicoss/bleanser
src/bleanser/core/modules/json.py
.py
dcd6a13a4ba5d370
7.6
15
""" Helpers for processing sqlite databases """ from __future__ import annotations import re import shutil import sqlite3 import subprocess from collections.abc import Iterator, Sequence from contextlib import closing, contextmanager from pathlib import Path from sqlite3 import Connection from typing import Literal ...
karlicoss/bleanser
src/bleanser/core/modules/sqlite.py
.py
5d453a26df79f628
7.6
15
from __future__ import annotations import hashlib from pathlib import Path import more_itertools import pytest from ....tests.common import TESTDATA, actions, skip_if_no_data from ..binary import BinaryNormaliser def via_md5(path: Path) -> list[Path]: files = sorted(path.iterdir()) def _file_hash(p: Path)...
karlicoss/bleanser
src/bleanser/core/modules/tests/binary.py
.py
a83e518ae2e8b115
7.1
15
from __future__ import annotations import sqlite3 from pathlib import Path from typing import Any import pytest from ...common import Keep, Prune from ...processor import compute_groups, compute_instructions, groups_to_instructions from ..sqlite import SqliteNormaliser, _checked_db, _postprocess_dump_hex, _postproce...
karlicoss/bleanser
src/bleanser/core/modules/tests/sqlite.py
.py
a17917928b22762b
8.1
15
"""Property-based checks for FileSet's line-set algebra.""" from __future__ import annotations from contextlib import ExitStack from pathlib import Path from tempfile import TemporaryDirectory from hypothesis import example, given, settings from hypothesis import strategies as st from ..processor import FileSet # ...
karlicoss/bleanser
src/bleanser/core/tests/fileset_properties.py
.py
64ba869e8b5107cb
8.1
15
from collections.abc import Iterator, Sequence from contextlib import contextmanager from pathlib import Path import pytest from ..common import Group, Keep, Prune from ..processor import BaseNormaliser, FileSet, Normalised, compute_groups, groups_to_instructions from ..utils import total_dir_size def test_fileset(...
karlicoss/bleanser
src/bleanser/core/tests/processor.py
.py
45d0746f76ada285
8.1
15
""" Property-based tests for the pruning algorithm in bleanser.core.processor. model_keep is a small reference implementation of the current grouping semantics, operating directly on sets. Hypothesis generates synthetic export histories and materialises them as files. The real compute_instructions, FileSet, sort, diff...
karlicoss/bleanser
src/bleanser/core/tests/processor_properties.py
.py
69d1bdce0b668580
8.1
15
"""Safety assertions shared by serial and process-pool processor properties.""" from __future__ import annotations from collections.abc import Sequence from pathlib import Path from ..common import Instruction, Keep, Prune from ..processor import assert_instruction_structure # One snapshot is the set of lines in it...
karlicoss/bleanser
src/bleanser/core/tests/processor_property_checks.py
.py
406a98b46907e2a5
7.1
15
"""Property tests for source-file and process-pool safety guarantees.""" from __future__ import annotations from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path from tempfile import TemporaryDirectory import pytest from hypothesis import example, given, settings from hy...
karlicoss/bleanser
src/bleanser/core/tests/processor_safety_properties.py
.py
df084614cb68febb
8.1
15
import logging import os import sys from logging.handlers import TimedRotatingFileHandler from pathlib import Path from . import assets, events, replication, time_series from ._version import __version__ def configure_logger(log_level: str = "INFO", log_path: Path = None) -> None: """Configure the logging to std...
cognitedata/cognite-replicator
cognite/replicator/__init__.py
.py
5682fea45fc9ba9d
7.45
7
#!/usr/bin/env python3 DESC=""" This script converts filter data from the older CSV format into the YAML format used by the newer camera parameter system. The CSV data itself may have been generated from a Markdown table by genfilters.py, but should consist of name,position,cwl,fwhm,transmission (in any order). """ i...
AU-ExoMars/PCOT
cameras/convert_from_csv.py
.py
22928ef11a64a12e
7.42
6
from typing import Union from pathlib import Path import numpy as np from pds4_tools.reader.general_objects import StructureList from pds4_tools.reader.table_objects import TableStructure class MultiData: """Provide access to a list's given structure's data via index key notation.""" def __init__(self, struc...
AU-ExoMars/PCOT
dist/proctools/src/proctools/products/adapters.py
.py
3750908193cc21a8
7.42
6
import logging from pathlib import Path from typing import ClassVar, Dict, Optional, Union import pds4_tools from lxml import etree from passthrough import Template from pds4_tools.reader.general_objects import StructureList from pds4_tools.reader.label_objects import Label class LabelMeta: """Single-layer XML e...
AU-ExoMars/PCOT
dist/proctools/src/proctools/products/dataproduct.py
.py
59ac671d40adb902
7.42
6
import logging from pathlib import Path from typing import List, Optional, Union from xml.parsers.expat import ExpatError from . import DataProduct class ProductLoader: """PDS4 product loader and manager. This class keeps track of whether a loaded product has been requested (used). A report of unused pr...
AU-ExoMars/PCOT
dist/proctools/src/proctools/products/loader.py
.py
6aca90f3d2a5eb40
7.42
6
from passthrough.extensions.pt.datetime import PDSDatetime class ApplicableCameraMixin: """Allow `DataProduct`s to evaluate applicability based on `psa:Sub-Instrument`. Note: both products must be able to resolve the "camera" meta key, which is not defined in DataProduct's base map (but is for instance m...
AU-ExoMars/PCOT
dist/proctools/src/proctools/products/mixins.py
.py
a1031b16368679d2
7.42
6
import hashlib import numpy as np from pathlib import Path class BayerSlice: """The `BayerSlice` class carries `slice` attributes targeting individual Bayer channels for a given pattern and (subframe) origin offset. Attributes: r: `slice` identifying red channel pixels g1: `slice` identif...
AU-ExoMars/PCOT
dist/proctools/src/proctools/products/util.py
.py
4b112fe173ddafba
7.42
6
""" A Markdown extension for rendering blocks delineated by multiple @-signs as alerts. I'm not using exclamation marks because the (not as good) admonishment extension uses those. Format: @@@ tag DO NOT START WITH A BLANK LINE!!!! some blocks of text which will have their markdown parsed @@@ Tags are in classNameDi...
AU-ExoMars/PCOT
mkdocs/alert.py
.py
46c51b68be078a40
7.42
6
""" A Markdown extension which converts images into lightboxes. To use, put an extra ! in front of the text description of an image: ![The PCOT user interface](app.png) becomes ![!The PCOT user interface](app.png) This was adapted from https://github.com/g-provost/lightgallery-markdown and some of the options don'...
AU-ExoMars/PCOT
mkdocs/lightbox.py
.py
1d503dd385beac95
7.42
6
#!/usr/bin/env python """ This is an example script to show how you might possibly arrange and collect flatfield files into groups for processing. What we want to end up with is a directory of files for each filter which we can process. This script: * Finds all image files * Extracts their filter position a...
AU-ExoMars/PCOT
scripts/flatfield/collate_flats.py
.py
32d16bd3d177546c
7.42
6
import importlib import os import traceback try: import pcot.macros as macros except AttributeError as e: traceback.print_exc() print(""" This error MAY mean that you should turn off Qt Compatible debugging in PyCharm. It's a bug https://youtrack.jetbrains.com/issue/PY-50959 """) exit(0) i...
AU-ExoMars/PCOT
src/pcot/__init__.py
.py
9458e902d07ff955
7.42
6
""" This is the file which creates and runs the PCOT user interface """ import os from pathlib import Path from PySide2 import QtWidgets from PySide2.QtCore import QCommandLineParser, QCommandLineOption import logging import os import getpass import sys import pcot.config import pcot.ui.mainwindow from pcot.document ...
AU-ExoMars/PCOT
src/pcot/app.py
.py
64a39c5f318c1143
7.42
6
""" This package handles and contains assets, usually strings but some binaries. """ import importlib import io import pkgutil from PySide2.QtGui import QIcon def getAssetAsString(fn, package="pcot.assets"): """Find a file in the assets package and return its contents as a string, assuming it is utf-8 encoded"""...
AU-ExoMars/PCOT
src/pcot/assets/__init__.py
.py
ed77d6bfa86d388a
7.42
6
""" Contains types used in defining the target for calibration. """ from dataclasses import dataclass from typing import Tuple class Patch: """ Base class for patches """ pass @dataclass class CircularPatch(Patch): x: float # x coordinate of centre in mm y: float # y coordinate of centre in ...
AU-ExoMars/PCOT
src/pcot/calib/target.py
.py
50c10063067a47d3
7.42
6
""" This package deals with camera data: filters, flatfield data and so on. It also deals with reflectance target data. """ import logging import os.path from pathlib import Path from typing import Set, List from pcot.cameras.reflectances import Reflectance logger = logging.getLogger(__name__) # dictionary of Camera...
AU-ExoMars/PCOT
src/pcot/cameras/__init__.py
.py
d6d3f8097c80e75b
7.42
6
import csv import math import os.path import warnings from pathlib import Path from typing import List, Optional import numpy as np from scipy.interpolate import RegularGridInterpolator from skimage.data import camera from pcot import ui from pcot.cameras.filtresponse import FilterResponse from pcot.documentsettings ...
AU-ExoMars/PCOT
src/pcot/cameras/filters.py
.py
33714ef489eb1b64
7.42
6
"""Image normalisation stuff for canvases. This takes an image and an RGB image and generates a normalised RGB image. It can't just produce an RGB image because the incoming image might be "premapped" by another node. It will also: - only consider a rectangle of the image if required - TODO ignore "bad" pixels...
AU-ExoMars/PCOT
src/pcot/canvasnormalise.py
.py
304eb538441d866e
7.42
6
""" Configuration data system, also handles hooks for plugins """ import getpass import logging import os from collections import deque from pathlib import Path from typing import Optional, List import yaml from PySide2 import QtWidgets from pcot.parameters.taggedaggregates import TaggedDictType, Maybe, TaggedDict, T...
AU-ExoMars/PCOT
src/pcot/config.py
.py
4dc1609571041e40
7.42
6
# pylint: disable=C0209 """ Upload new images to S3. See requirements in imagesUpload.sh. """ import logging import os import time import boto3 DATA_PATH = 'images_upload.txt' IMAGES_FOLDER = '/mnt/volume_postgres/cards/English/' LOG_PATH = 'images_upload.log' LOG_LIMIT = 5000 S3_BUCKET = 'dragncards-lotrlcg' S3_P...
seastan/lotr-lcg-set-generator
DragnCards/images_upload.py
.py
30c57b819a0e1fa6
7.52
10
# pylint: disable=C0209 # -*- coding: utf8 -*- """ Get aggregated statistics about player cards being playtested. """ from datetime import datetime import logging import os import sys import psycopg2 from psycopg2 import extras DRAGNCARDS_USER = 'postgres' DRAGNCARDS_PASSWORD = 'postgres' DRAGNCARDS_HOST = '127.0.0.1...
seastan/lotr-lcg-set-generator
DragnCards/player_cards_stat.py
.py
e0118bb3b7f014d0
7.52
10
# pylint: disable=W0703,C0209 # -*- coding: utf8 -*- """ Check redundant playtesting sets. """ from email.header import Header import json import logging import os import re import time import uuid import yaml from lotr import list_dragncards_files, run_cmd, UUID_REGEX DATA_PATH = os.path.join('Data', 'check_playte...
seastan/lotr-lcg-set-generator
check_playtesting_sets.py
.py
bd12de94afcb0be5
8.02
10
# pylint: disable=C0209 """ Create mail file from the script arguments. """ from email.header import Header import json import os.path import re import sys import time import uuid MAILS_PATH = 'mails' def is_non_ascii(value): """ Check whether the string is ASCII only or not. """ return not all(ord(c) < ...
seastan/lotr-lcg-set-generator
create_mail.py
.py
6f0826104f998c8c
7.52
10
# pylint: disable=C0209 # -*- coding: utf8 -*- """ Download RingsDB statistics. """ from email.header import Header import json import logging import os import re import time import uuid import requests ERROR_SUBJECT_TEMPLATE = 'Download RingsDB Stat Cron ERROR: {}' LOG_PATH = 'download_ringsdb_stat.log' LOG_LEVEL =...
seastan/lotr-lcg-set-generator
download_ringsdb_stat.py
.py
5daad4638612026e
7.52
10
# pylint: disable=W0703,C0209 # -*- coding: utf8 -*- """ Monitor uploading images to S3 on the DragnCards host. """ from email.header import Header import json import logging import os import re import time import uuid import yaml from lotr import monitor_images_upload DISCORD_CONF_PATH = 'discord.yaml' ALERT_SUBJE...
seastan/lotr-lcg-set-generator
monitor_images_upload.py
.py
9964e80f9b1ea8f4
7.52
10
# pylint: disable=W0703,C0209 """ Monitor MakePlayingCards URL format. """ from email.header import Header import json import logging import os import re import time import uuid import requests ALERT_SUBJECT_TEMPLATE = 'MPC URL Format Monitor ALERT: {}' ERROR_SUBJECT_TEMPLATE = 'MPC URL Format Monitor ERROR: {}' LOG...
seastan/lotr-lcg-set-generator
monitor_mpc_url_format.py
.py
c52a164247492d9b
7.52
10
# pylint: disable=W0703,C0209,C0301 """ Monitor remote pipeline. """ from email.header import Header import hashlib import json import logging import os import re import subprocess import time import uuid import warnings import requests import yaml import common ALERT_SUBJECT_TEMPLATE = 'LotR Remote Pipeline Monito...
seastan/lotr-lcg-set-generator
monitor_remote_pipeline.py
.py
822029b995c0ecb5
7.52
10
# pylint: disable=W0703,C0209 """ Monitor Wordpress web-site. """ from email.header import Header import json import logging import os import re import time import uuid import warnings import requests ALERT_SUBJECT_TEMPLATE = 'LotR Wordpress Monitor ALERT: {}' ERROR_SUBJECT_TEMPLATE = 'LotR Wordpress Monitor ERROR: ...
seastan/lotr-lcg-set-generator
monitor_wordpress_site.py
.py
20e461959dc6e94b
7.52
10
# pylint: disable=C0209 """ A wrapper around `run_after_se.py` for remote execution. """ import logging import os import uuid import yaml from lotr import CONFIGURATION_PATH, LOG_LIMIT import run_after_se LOG_FILE = 'run_after_se_remote.log' def init_logging(): """ Init logging. """ with open(CONFIGUR...
seastan/lotr-lcg-set-generator
run_after_se_remote.py
.py
d4db4f167e994705
7.52
10
# pylint: disable=C0209 """ A wrapper around `run_before_se.py` for remote execution. """ import logging import os import time import uuid import yaml from lotr import CONFIGURATION_PATH, LOG_LIMIT import run_before_se LOG_FILE = 'run_before_se_remote.log' RETRY_SLEEP_TIME = 300 SANITY_CHECK_ERROR_SLEEP_TIME = 3600...
seastan/lotr-lcg-set-generator
run_before_se_remote.py
.py
8558827ced09d62c
7.52
10
""" Base class for subcommands under ``reclib.run``. """ import argparse class Subcommand: """ An abstract class representing subcommands for reclib.run. If you wanted to (for example) create your own custom `special-evaluate` command to use like ``reclib special-evaluate ...`` you would create ...
p-null/reclib
reclib/commands/subcommand.py
.py
eb1a72b87b28a538
7.45
7
""" Utilities for working with the local dataset cache. """ import json import logging import os import shutil import tempfile from functools import wraps from hashlib import sha256 from pathlib import Path from typing import Optional, Tuple, Union, IO, Callable, Set from urllib.parse import urlparse import boto3 imp...
p-null/reclib
reclib/common/file_utils.py
.py
22c02cdc66fca6cb
7.45
7
""" A logger that maintains logs of both stdout and stderr when models are run. """ import os from typing import TextIO def replace_cr_with_newline(message: str): """ TQDM and requests use carriage returns to get the training line to update for each batch without adding more lines to the terminal output....
p-null/reclib
reclib/common/tee_logger.py
.py
ad4c32ef6db52199
7.45
7
# pylint: disable=invalid-name,protected-access import logging import os import pathlib import shutil import tempfile from unittest import TestCase from reclib.common.checks import log_pytorch_version_info TEST_DIR = tempfile.mkdtemp(prefix="reclib_tests") class RecLibTestCase(TestCase): # pylint: disable=too-many...
p-null/reclib
reclib/common/testing/test_case.py
.py
c06cae9ca825b2d5
7.95
7
""" :class:`~reclib.common.tqdm.Tqdm` wraps tqdm so we can add configurable global defaults for certain tqdm parameters. """ from tqdm import tqdm as _tqdm # This is neccesary to stop tqdm from hanging # when exceptions are raised inside iterators. # It should have been fixed in 4.2.1, but it still # occurs. # TODO(M...
p-null/reclib
reclib/common/tqdm.py
.py
dbc54b28276ca0ff
7.45
7
""" Various utilities that don't fit anwhere else. """ import importlib import json import logging import os import pkgutil import random import subprocess import sys from itertools import zip_longest, islice from typing import Any, Callable, Dict, List, Tuple, TypeVar, Iterable, Iterator try: import resource exce...
p-null/reclib
reclib/common/util.py
.py
63dc066304f5adbb
7.45
7
""" A :class:`~Batch` represents a collection of ``Instance`` s to be fed through a model. """ import logging from collections import defaultdict from typing import Dict, List, Union, Iterator, Iterable import numpy import torch from reclib.common.checks import ConfigurationError from reclib.common.util import ensur...
p-null/reclib
reclib/data/dataset.py
.py
93f58411d1701436
7.45
7
import numpy as np import pandas as pd import torch.utils.data class MovieLens20MDataset(torch.utils.data.Dataset): """ MovieLens 20M Dataset Data preparation treat samples with a rating less than 3 as negative samples Parameters ---------- dataset_path: ``string`` MovieLens ...
p-null/reclib
reclib/data/dataset_readers/movielens.py
.py
86f74ab35043febd
7.45
7
from typing import Dict, Generic, TypeVar import torch DataArray = TypeVar("DataArray", torch.Tensor, Dict[str, torch.Tensor]) class Field(Generic[DataArray]): """ A ``Field`` is some piece of a data instance that ends up as an tensor in a model (either as an input or an output). Data instances are jus...
p-null/reclib
reclib/data/fields/field.py
.py
03e689de0f7a1ccd
7.45
7
from typing import Dict, MutableMapping, Mapping from reclib.data.fields.field import Field class Instance(Mapping[str, Field]): """ An ``Instance`` is a collection of :class:`~reclib.data.fields.field.Field` objects, specifying the inputs and outputs to some model. We don't make a distinction betwee...
p-null/reclib
reclib/data/instance.py
.py
58d9482c1ca4915b
7.45
7
import logging from typing import Dict, Union import torch from torch.utils.data import DataLoader from reclib.data.dataset import Batch from reclib.data.fields import MetadataField logger = logging.getLogger(__name__) TensorDict = Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]] def add_epoch_number(batch...
p-null/reclib
reclib/data/iterators/data_iterator.py
.py
a46ffce92751d2b2
7.45
7
""" Helper functions for archiving models and restoring archived models. """ import atexit import json import logging import os import shutil import tarfile import tempfile from typing import NamedTuple, Dict, Any from torch.nn import Module from reclib.common.checks import ConfigurationError from reclib.common.file...
p-null/reclib
reclib/models/archival.py
.py
bc19b6d75f85ffa6
7.45
7
import torch from reclib.modules import AttentionalFactorizationLayer from reclib.modules.embedders import LinearEmbedder, Embedding class AttentionalFactorizationMachine(torch.nn.Module): """ This implements Attentional Factorization Machine from '"Attentional Factorization Machines: Learning the Weight...
p-null/reclib
reclib/models/attentional_factorization_machine.py
.py
d6c29a42b8908b09
7.45
7