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 |
|---|---|---|---|---|---|---|
"""NSW Rural Fire Service - Fire Danger - Binary Sensor."""
from __future__ import annotations
import logging
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
f... | exxamalte/home-assistant-custom-components-nsw-rural-fire-service-fire-danger | custom_components/nsw_rural_fire_service_fire_danger/binary_sensor.py | .py | 21c3bc92f4081f01 | 7.59 | 14 |
"""Config flow to configure the NSW Rural Fire Service Fire Danger integration."""
from __future__ import annotations
from typing import Any
from homeassistant import config_entries
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant, callback
from homeassistant.data_entry... | exxamalte/home-assistant-custom-components-nsw-rural-fire-service-fire-danger | custom_components/nsw_rural_fire_service_fire_danger/config_flow.py | .py | 437b5a6ab0902825 | 7.59 | 14 |
"""NSW Rural Fire Service - Fire Danger - Entity."""
from __future__ import annotations
from abc import abstractmethod
import logging
from typing import Any
from homeassistant.core import callback
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo
fr... | exxamalte/home-assistant-custom-components-nsw-rural-fire-service-fire-danger | custom_components/nsw_rural_fire_service_fire_danger/entity.py | .py | 08489d6759c40834 | 7.59 | 14 |
"""NSW Rural Fire Service - Fire Danger - Sensor."""
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helper... | exxamalte/home-assistant-custom-components-nsw-rural-fire-service-fire-danger | custom_components/nsw_rural_fire_service_fire_danger/sensor.py | .py | c461d898db830d0f | 7.59 | 14 |
"""Configuration for NSW Rural Fire Service - Fire Danger tests."""
from homeassistant import loader
from homeassistant.const import CONF_SCAN_INTERVAL
import pytest
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.nsw_rural_fire_service_fire_danger.const import (
CO... | exxamalte/home-assistant-custom-components-nsw-rural-fire-service-fire-danger | tests/nsw_rural_fire_service_fire_danger/conftest.py | .py | 59d644accc3c6653 | 8.09 | 14 |
#!/usr/bin/env python3
"""Generate the bundled completion catalog from an installed Stata tree.
No executable scraper or interactive Stata session is required. The selection
policy is deliberately reproducible and reviewable:
* documented ado programs require a program declaration and either a
same-named ``.sthlp`... | sergiocorreia/sublime-stata | misc/generate_stata_catalog.py | .py | b21c19b6546dbb85 | 7.5 | 9 |
import numpy as np
import h5py
import scipy.io as sio
import cv2
from os.path import join
from args import args
class Flickr:
def __init__(self):
self.MEAN_PIX = join(
args.data_path, "avgpix.{}.npy".format(args.dataset))
self.LABELS = join(args.data_path, "labels.mat")
self.IM... | iTomxy/ml-template | data/flickr.py | .py | 2f07493b24e23425 | 7.42 | 6 |
from os.path import join
import numpy as np
# import h5py
import scipy.io as sio
import cv2
# from PIL import Image
from args import *
class NUS_WIDE:
def __init__(self,):
split_path = join("split", args.dataset)
self.LABELS = join(args.data_path, "nus-wide-tc21-lall.mat")
self.IMAGES = jo... | iTomxy/ml-template | data/nuswide.py | .py | c04e6da3a5532c55 | 7.42 | 6 |
import numpy as np
import pickle
import cv2
from os.path import join
from args import args
class VOC2007:
def __init__(self, zero_as=0):
"""zero_as: in {0, 1}
- 0: treat difficult as negative
- 1: treat difficult as positive
"""
self.LABELS = join(args.data_path, "labels.l... | iTomxy/ml-template | data/voc2007.py | .py | 04fa96925f1198c4 | 7.42 | 6 |
# evaluate.py
import numpy as np
from scipy.optimize import linear_sum_assignment
import sklearn.metrics as metrics
"""
clustering evaluation metrics
"""
def calc_cost_matrix(y_true, y_assign, n_classes, n_clusters):
"""calculate cost matrix W
Input:
y_true: [n], in {0, ..., n_classes - 1}
y_a... | iTomxy/ml-template | evaluate/cluster.py | .py | 2ec49e1bcca01082 | 7.42 | 6 |
import math
import numpy as np
import torch
"""
confusion matrix based metrics, suits classification and semanticsegmentation.
"""
def confusion_matrix(pred, y, num_classes, ignore_index=-1):
"""Compute confusion matrix (TP, TN, FP, FN) for multi-class classification/segmentation,
based on PyTorch tensors, ca... | iTomxy/ml-template | evaluate/cm.py | .py | 6e2f81da435c1c7f | 7.42 | 6 |
import numpy as np
def prfa(y_true, y_pred):
"""Precision, Recall, F1, Accuracy
- micro: OP, OR, OF1
- macro: CP, CR, CF1
input:
- y_true: [n, c], ground-truth, in {0, 1}
- y_pred: [n, c], prediction, in {0, 1}
output:
- OP, OR, OF1, CP, CR, CF1, acc
"""
true = (y_true > 0.5).a... | iTomxy/ml-template | evaluate/retrieval/_PRF1.py | .py | 65ba70d46c871a35 | 7.42 | 6 |
import copy
import numpy as np
def mAHP(Dist, Rel, k=-1):
"""mean Average Hierarchical Precision
AHP@k = 1/k * [ sum_i {HP@i} - 1/2 * (HP@1 + HP@k) ]
Input:
Dist: distance matrix
Rel: relevance matrix
k: mAP@k, int or int tuple/list
default `-1` means mAP@ALL
ref:
... | iTomxy/ml-template | evaluate/retrieval/_mAHP.py | .py | 02f7daf0f0a42ff6 | 7.42 | 6 |
import copy
import numpy as np
def mAP(Dist, Sim, k=-1):
"""mean Average Precision
Input:
Dist: distance matrix
Sim: 0/1 similarity matrix
k: mAP@k, int or int tuple/list
default `-1` means mAP@ALL
ref:
- https://blog.csdn.net/HackerTom/article/details/89309665
"... | iTomxy/ml-template | evaluate/retrieval/_mAP.py | .py | 15a7bd1b58aa0a05 | 7.42 | 6 |
import copy
import numpy as np
def nDCG(Dist, Rel, k=-1):
"""Normalized Discounted Cumulative Gain
Input:
Dist: [n, m], Hamming distance matrix
Rel: [n, m], relevance mattrix, in {0, 1, 2, ...}
k: nDCG@k, int or int tuple/list
default `-1` means nDCG@ALL
ref:
- https... | iTomxy/ml-template | evaluate/retrieval/_nDCG.py | .py | 2a9bb41e9f3c9742 | 7.42 | 6 |
# import packaging.version
import warnings
import numpy as np
import medpy.metric.binary as mmb
from monai.networks.utils import one_hot
from monai.metrics import DiceMetric, MeanIoU, GeneralizedDiceScore, ConfusionMatrixMetric, HausdorffDistanceMetric, SurfaceDistanceMetric
"""
Wrap segmentation metrics implemented b... | iTomxy/ml-template | evaluate/semantic_seg.py | .py | ea21717eadd6b695 | 7.42 | 6 |
import torch
import torch.nn.functional as F
class NDCGrs_loss(torch.autograd.Function):
"""lower bound of tie-aware NDCG
X: [n, bit], raw hash logit BEFORE activation like tanh/sigmoid
L: [n, c], labels, if `sparse` then [n]
n_bin: # of bins
delta_scale: scaling factor for the \Delta parameter
... | iTomxy/ml-template | losses/pytorch/NDCGrs_loss.py | .py | be9752197c3f2735 | 7.42 | 6 |
import torch
import torch.nn.functional as F
from wheel import *
"""Ref:
https://omoindrot.github.io/triplet-loss
https://blog.csdn.net/hustqb/article/details/80361171#commentBox
https://blog.csdn.net/hackertom/article/details/103374313
"""
def _triplet_mask(L, L2=None, sparse=False):
if L2 is None:
L2 ... | iTomxy/ml-template | losses/pytorch/triplet_loss.py | .py | cca7476c36a344d1 | 7.42 | 6 |
import tensorflow as tf
from wheel import *
def histogram_loss(X, L, R=151):
"""hisgogram loss
X: [n, d], feature WITHOUT L2 norm
L: [n, c], label
R: scalar, num of estimating point, same as the paper
"""
delta = 2. / (R - 1) # step
# t = (t_1, ..., t_R)
t = tf.lin_space(-1., 1., R)[:... | iTomxy/ml-template | losses/tensorflow/histogram_loss.py | .py | 22ea8684d867d6b4 | 7.42 | 6 |
import tensorflow as tf
from wheel import *
from args import args
"""Ref:
https://omoindrot.github.io/triplet-loss
https://blog.csdn.net/hustqb/article/details/80361171#commentBox
https://blog.csdn.net/hackertom/article/details/103374313
"""
def _triplet_mask(L, L2=None, sparse=False):
"""M(i,j,k) = 1 iff:
... | iTomxy/ml-template | losses/tensorflow/triplet_loss.py | .py | 5b6dfb86c9651252 | 7.42 | 6 |
import random
import numpy as np
import cv2
# import albumentations as A
"""image transforms/augmentations
use them as you do with those torchvision.transforms,
and likewise, they process SINGLE image of shape [H, W, C].
input: numpy.ndarray (maybe reading by cv2)
output: numpy.ndarray
references:
- https://pytorch... | iTomxy/ml-template | pre_process.py | .py | e51dd8359699c5b4 | 7.42 | 6 |
import scipy.io as sio
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
"""Ref:
- https://zhuanlan.zhihu.com/p/29786939
- https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py
- https://pytorch.org/docs/stable/nn.html#zeropad2d
- https://github.com/tensorflow... | iTomxy/ml-template | pytorch/cnnf.py | .py | b5f2583bc879e4f8 | 7.42 | 6 |
import numpy as np
import tensorflow as tf
import cnnf
import losses
from args import *
from wheel import *
class Some_Model:
"""descriptions"""
def __init__(self):
self.in_images = tf.placeholder(
"float32", [None, 224, 224, 3], name="in_images")
self.in_labels = tf.placeholder(
... | iTomxy/ml-template | tensorflow/tf1.12/models.py | .py | 4394a4e6b7a3f8df | 7.42 | 6 |
import tensorflow as tf
from tensorflow import keras as K
from tensorflow.keras import layers as L
import scipy.io as sio
import numpy as np
class CNN_F(K.Model):
"""CNN-F / VGG-F"""
def __init__(self, weight_file):
super(CNN_F, self).__init__()
layers = sio.loadmat(weight_file)["net"][0][0][... | iTomxy/ml-template | tensorflow/tf2.1/cnnf.py | .py | 2b1e15ef03fe0a35 | 7.42 | 6 |
import pickle
import numpy as np
import scipy.special as scsp
import tensorflow as tf
import tensorflow.keras as K
from args import *
from wheel import *
def get_A(adj_file, tau=0.4):
"""tau: threashold of Eq (7)
https://github.com/Megvii-Nanjing/ML-GCN/blob/master/util.py#L291
"""
with open(adj_file,... | iTomxy/ml-template | tensorflow/tf2.1/mlgcn.py | .py | 98fde190ccdaa037 | 7.42 | 6 |
import random
# import numpy as np
# import cv2
import tensorflow as tf
import tensorflow.keras as K
import tensorflow.keras.layers as L
"""image transforms/augmentations
use them as you do with those torchvision.transforms,
and likewise, they process SINGLE image of shape [H, W, C].
input: numpy.ndarray or tf.Tenso... | iTomxy/ml-template | tensorflow/tf2.1/pre_process.py | .py | d494b78db181f06b | 7.42 | 6 |
from argparse import Action, ArgumentParser, Namespace
import copy, os, json, importlib.util, inspect, types, warnings
from typing import Any, Optional, Sequence, Tuple, Union
import yaml
# Reserved Keys
# FROM https://github.com/open-mmlab/mmengine/blob/main/mmengine/config/config.py
BASE_KEY = '_base_' # import ano... | iTomxy/ml-template | utils/config.py | .py | e113446c28f07d43 | 7.42 | 6 |
import os, os.path as osp
import cv2
import numpy as np
import nibabel as nib
import SimpleITK as sitk
from nibabel.orientations import axcodes2ornt, ornt_transform, apply_orientation
from PIL import Image
def crop(img, blank=(255, 255, 255)):
"""remove blank edge of an image
Input:
img: (H, W[, C]), ... | iTomxy/ml-template | utils/image.py | .py | 7b6d86330a701d83 | 7.42 | 6 |
import os
import re
import sys
from pathlib import Path
from typing import Final, NoReturn
from sh import Command, CommandNotFound
class Constants:
"""All constants"""
DIST_PATH: Final[Path] = Path("dist")
DISTRIBUTIONS_TARBALL_PATH: Final[Path] = Path("distributions") / "tarball"
DISTRIBUTIONS_TARB... | techcode-io/temply | scripts/utils.py | .py | dfe45d2756424a98 | 7.45 | 7 |
from pathlib import Path
import click
import jinja2
from jinja2 import DictLoader, Environment, FileSystemLoader
from . import __version__
from .filters import from_json, from_yaml, get_environment, to_json, to_yaml
from .loaders import ChainLoader, DotenvLoader, EnvdirLoader, EnvLoader, JsonFileLoader
class Templa... | techcode-io/temply | src/temply/cli.py | .py | 9eb603af6a979f5a | 7.45 | 7 |
"""Some simple tests/example for the Home Assistant client."""
import argparse
import asyncio
import logging
import sys
from contextlib import suppress
from aiohttp import ClientSession
from hass_client import HomeAssistantClient
from hass_client.models import Event
LOGGER = logging.getLogger()
def get_arguments(... | music-assistant/python-hass-client | example.py | .py | 941280bc9c93c22b | 7.66 | 20 |
"""Exceptions for hass-client."""
class BaseHassClientError(Exception):
"""Base Hass Client exception."""
class TransportError(BaseHassClientError):
"""Exception raised to represent transport errors."""
def __init__(self, message: str, error: Exception | None = None) -> None:
"""Initialize a tr... | music-assistant/python-hass-client | hass_client/exceptions.py | .py | bc8eabbb546f092a | 7.66 | 20 |
"""Models used for messages to/from the HA Websocket API."""
from __future__ import annotations
from typing import Any, Final, NotRequired, TypedDict
MESSAGE_TYPE_AUTH: Final[str] = "auth"
MESSAGE_TYPE_AUTH_REQUIRED: Final[str] = "auth"
class AuthRequiredMessage(TypedDict):
"""
Message received in the auth... | music-assistant/python-hass-client | hass_client/models.py | .py | ceb131b5fab42518 | 7.66 | 20 |
"""Various helpers and utilities."""
from __future__ import annotations
import asyncio
import urllib.error
import urllib.parse
import urllib.request
from typing import TYPE_CHECKING
from aiohttp import ClientSession
if TYPE_CHECKING:
from hass_client.models import TokenDetails
def get_websocket_url(url: str) ... | music-assistant/python-hass-client | hass_client/utils.py | .py | 439972bcd3639c0b | 7.66 | 20 |
"""Tests for hass-client exceptions."""
from hass_client.exceptions import (
ConnectionFailed,
ConnectionFailedDueToLargeMessage,
TransportError,
)
def test_connection_failed_without_error() -> None:
"""Test ConnectionFailed falls back to the generic message."""
exc = ConnectionFailed()
asser... | music-assistant/python-hass-client | tests/test_exceptions.py | .py | 738e4128b4cd7d94 | 8.16 | 20 |
"""
An example extractor that logs messages at various levels.
"""
from cognite.extractorutils.unstable.configuration.models import ExtractorConfig, IntervalConfig, TimeIntervalConfig
from cognite.extractorutils.unstable.core.base import Extractor, StartupTask, TaskContext
from cognite.extractorutils.unstable.core.run... | cognitedata/python-extractor-utils | cognite/examples/unstable/extractors/simple_extractor/main.py | .py | 8a245ebe12d7a950 | 7.57 | 13 |
# Copyright 2020 Cognite AS
#
# 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 writ... | cognitedata/python-extractor-utils | cognite/extractorutils/_inner_util.py | .py | 8a25bc9e0b5e603f | 7.57 | 13 |
# Copyright 2023 Cognite AS
#
# 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 writ... | cognitedata/python-extractor-utils | cognite/extractorutils/configtools/_util.py | .py | 983629d1b5bde5df | 7.57 | 13 |
# Copyright 2020 Cognite AS
#
# 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 writ... | cognitedata/python-extractor-utils | cognite/extractorutils/metrics.py | .py | b0d1e703e935f67f | 7.57 | 13 |
import logging
import threading
from abc import ABC, abstractmethod
from cognite.extractorutils._inner_util import _resolve_log_level
from cognite.extractorutils.threading import CancellationToken
RETRY_BACKOFF_FACTOR = 1.5
RETRY_MAX_DELAY = 60
RETRY_DELAY = 1
RETRIES = 10
class _BaseStateStore(ABC):
def __init... | cognitedata/python-extractor-utils | cognite/extractorutils/statestore/_base.py | .py | cc430f00f0774497 | 8.07 | 13 |
"""
State store implementations that use hashing to track changes.
This module provides two main classes for state management:
- ``RawHashStateStore``: A state store that uses CDF RAW to store and persist states based on a hash of the data.
- ``LocalHashStateStore``: A state store that uses a local JSON file to store ... | cognitedata/python-extractor-utils | cognite/extractorutils/statestore/hashing.py | .py | bfb867e8b8cb948c | 7.07 | 13 |
# ruff: noqa: ANN401
# TODO: the state stores should be generic over the type of state, not just Any.
# Copyright 2020 Cognite AS
#
# 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
#
# ... | cognitedata/python-extractor-utils | cognite/extractorutils/statestore/watermark.py | .py | 62002ff4bb325467 | 7.07 | 13 |
"""
Module that provides additional threading utilities.
"""
import logging
import signal
from threading import Condition
from time import time
from types import FrameType
class CancellationToken:
"""
Abstraction for a hierarchical cancellation token.
Using this you can create hierarchies of cancellatio... | cognitedata/python-extractor-utils | cognite/extractorutils/threading.py | .py | 0c679efd4ec07c73 | 7.57 | 13 |
"""
Module containing functions and classes for loading configuration files.
"""
import json
from enum import Enum
from io import StringIO
from pathlib import Path
from typing import Any, TextIO, TypeVar
from cognite.client import CogniteClient
from cognite.client.exceptions import CogniteAPIError
from pydantic impor... | cognitedata/python-extractor-utils | cognite/extractorutils/unstable/configuration/loaders.py | .py | 9b4a9d04cfdbdfc7 | 7.57 | 13 |
"""Bounded binary reader for point-in-time log file uploads."""
import io
from typing import BinaryIO
class BoundedReader:
"""
Wraps a binary file handle and limits reads to a byte count captured at snapshot time.
Implements ``__len__`` so ``requests.utils.super_len()`` bypasses ``os.fstat()``
and d... | cognitedata/python-extractor-utils | cognite/extractorutils/unstable/core/_bounded_reader.py | .py | 9c248109f08050be | 7.57 | 13 |
"""
Temporary holding place for DTOs against Extraction Pipelines 2.0 until it's in the SDK.
Jira ticket: https://cognitedata.atlassian.net/browse/EDGE-493
"""
from enum import Enum
from typing import Annotated, Any, Literal, Optional
from annotated_types import Len
from humps import camelize
from pydantic import Ba... | cognitedata/python-extractor-utils | cognite/extractorutils/unstable/core/_dto.py | .py | 916afbf25f25f77f | 7.57 | 13 |
"""
This module defines the base classes for custom actions in the extractor framework.
"""
import logging
from collections.abc import Callable
from typing import TYPE_CHECKING, Generic
from cognite.extractorutils.unstable.configuration.models import ConfigType
from cognite.extractorutils.unstable.core._dto import Ac... | cognitedata/python-extractor-utils | cognite/extractorutils/unstable/core/actions.py | .py | 4e8d630053ed60fc | 7.57 | 13 |
"""
This module defines the Error and ErrorLevel classes for reporting errors in extractors.
"""
import logging
from enum import Enum
from types import TracebackType
from typing import TYPE_CHECKING
from uuid import uuid4
from typing_extensions import assert_never
from cognite.extractorutils.util import now
if TYPE... | cognitedata/python-extractor-utils | cognite/extractorutils/unstable/core/errors.py | .py | c7a20a94835576c0 | 7.57 | 13 |
# Copyright 2023 Cognite AS
#
# 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 writ... | cognitedata/python-extractor-utils | cognite/extractorutils/uploader/_base.py | .py | a10aeed703f064f2 | 7.57 | 13 |
"""
Upload queue for (legacy) assets.
"""
# Copyright 2023 Cognite AS
#
# 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 requ... | cognitedata/python-extractor-utils | cognite/extractorutils/uploader/assets.py | .py | e857625ae6f25809 | 7.57 | 13 |
"""
Module for uploading data modeling instances to CDF.
"""
from collections.abc import Callable
from types import TracebackType
from typing import Any
from cognite.client import CogniteClient
from cognite.client.data_classes.data_modeling import EdgeApply, NodeApply
from cognite.extractorutils.threading import Can... | cognitedata/python-extractor-utils | cognite/extractorutils/uploader/data_modeling.py | .py | 1631921486f0fb48 | 7.57 | 13 |
"""
Upload queue for (legacy) events.
"""
# Copyright 2023 Cognite AS
#
# 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 requ... | cognitedata/python-extractor-utils | cognite/extractorutils/uploader/events.py | .py | 3d55e65f289c6303 | 7.57 | 13 |
"""
Upload queue for RAW.
"""
# Copyright 2023 Cognite AS
#
# 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 appl... | cognitedata/python-extractor-utils | cognite/extractorutils/uploader/raw.py | .py | 82d4c90c6e6e9bb0 | 7.57 | 13 |
"""
This module provides a mechanism to handle file upload failures by logging details to a newline delimited JSON file.
"""
from collections.abc import Iterator
from datetime import datetime, timezone
import jsonlines
class FileErrorMapping:
"""
A class to represent a mapping of file name to its error reas... | cognitedata/python-extractor-utils | cognite/extractorutils/uploader/upload_failure_handler.py | .py | 9d7c3d21570ec71b | 7.57 | 13 |
"""
DEPRECATED. Use the normal base class and instantiate the upload queues manually.
A module containing a version of the Extractor class with pre-defined upload queues.
"""
# Copyright 2022 Cognite AS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... | cognitedata/python-extractor-utils | cognite/extractorutils/uploader_extractor.py | .py | fbd6848b946e1835 | 7.57 | 13 |
# -*- coding: utf-8 -*-
# Copyright 2018 Canonical Ltd.
#
# 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 l... | openstack-charmers/zaza-openstack-tests | setup.py | .py | 05e5a2d5fe0eb995 | 7.45 | 7 |
# Copyright 2020 Canonical Ltd.
#
# 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 writin... | openstack-charmers/zaza-openstack-tests | unit_tests/charm_tests/test_mysql.py | .py | fcceb3d4761dd72b | 7.95 | 7 |
# Copyright 2020 Canonical Ltd.
#
# 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 writin... | openstack-charmers/zaza-openstack-tests | unit_tests/charm_tests/test_rabbitmq_server.py | .py | b8e94be9beb43b95 | 7.95 | 7 |
# Copyright 2020 Canonical Ltd.
#
# 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 writin... | openstack-charmers/zaza-openstack-tests | unit_tests/charm_tests/test_tempest.py | .py | 46994628bf2c17b3 | 7.95 | 7 |
# Copyright 2026 Canonical Ltd.
#
# 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 writin... | openstack-charmers/zaza-openstack-tests | unit_tests/test_configure_guest.py | .py | 8005eefd8cb3dfe3 | 7.95 | 7 |
# Copyright 2024 Canonical Ltd.
#
# 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 writin... | openstack-charmers/zaza-openstack-tests | unit_tests/test_openstack.py | .py | 25c092c06aba9f48 | 7.95 | 7 |
# Copyright 2018 Canonical Ltd.
#
# 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 writin... | openstack-charmers/zaza-openstack-tests | unit_tests/utils.py | .py | 1b36d7203584c7aa | 7.95 | 7 |
# Copyright 2018 Canonical Ltd.
#
# 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 writin... | openstack-charmers/zaza-openstack-tests | zaza/openstack/__init__.py | .py | e44d75ad2665793b | 7.45 | 7 |
#!/usr/bin/env python3
# Copyright 2019 Canonical Ltd.
#
# 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 la... | openstack-charmers/zaza-openstack-tests | zaza/openstack/charm_tests/aodh/tests.py | .py | 6e2712fee37d35b3 | 7.95 | 7 |
#!/usr/bin/env python3
# Copyright 2019 Canonical Ltd.
#
# 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 la... | openstack-charmers/zaza-openstack-tests | zaza/openstack/charm_tests/ceilometer/tests.py | .py | cdc558e62c1b20c4 | 7.95 | 7 |
# Copyright 2021 Canonical Ltd.
#
# 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 writin... | openstack-charmers/zaza-openstack-tests | zaza/openstack/charm_tests/ceph/dashboard/setup.py | .py | 3080a5107c686aba | 7.95 | 7 |
from dataclasses import dataclass, field, fields
from abc import ABC
"""
The only exception to lots of the common headers etc in
the Axona file collection is the cut file, dealt with here
When converting data from KiloSort/ OE to Axona format there
might be a problem with the number of clusters. Axona limits
you to... | rhayman/ephysiopy | src/ephysiopy/axona/file_headers.py | .py | 0b08347177cbf3c7 | 7.5 | 9 |
from ephysiopy.axona import axonaIO
import numpy as np
import warnings
class TetrodeDict(dict):
"""
A dictionary-like object that returns a Tetrode object when
a key is requested. The Tetrode object is created on the fly
if it does not already exist. The Tetrode object is created
using the axonaIO... | rhayman/ephysiopy | src/ephysiopy/axona/tetrode_dict.py | .py | c1d6788262e54047 | 7.5 | 9 |
import numpy as np
from pycircstat2 import Circular, circ_plot
from pycircstat2.descriptive import (
circ_mean,
circ_std,
circ_dispersion,
circ_kurtosis,
)
from pycircstat2.hypothesis import rayleigh_test, omnibus_test
class HeadDirectionCalcs:
def __init__(self, head_directions: np.ma.MaskedArray... | rhayman/ephysiopy | src/ephysiopy/common/directionalcalcs.py | .py | e67ea4ac7780d759 | 7.5 | 9 |
import numpy as np
from scipy import optimize
from scipy.stats import norm
from astropy.stats.circstats import rayleightest
from dataclasses import dataclass
def circ_r(alpha, w=None, d=0, axis=0):
"""
Computes the mean resultant vector length for circular data.
Args:
alpha (array or list): Sampl... | rhayman/ephysiopy | src/ephysiopy/common/statscalcs.py | .py | dd59274b195cbdfa | 7.5 | 9 |
import numpy as np
import os
from ephysiopy.openephys2py import OESettings
from ephysiopy.io.recording import OpenEphysNWB
from scipy import signal
class OE2Numpy(object):
"""
Converts openephys data recorded in the nwb format into numpy files.
Notes
-----
Only exports the LFP and TTL files at th... | rhayman/ephysiopy | src/ephysiopy/format_converters/OE_numpy.py | .py | eccba10d02e93db3 | 7.5 | 9 |
import numpy as np
from pathlib import Path
from scipy.signal import butter, filtfilt
from ephysiopy.common.utils import memmapBinaryFile
from ephysiopy.io.recording import TrialInterface as Trial
bit_volts = 0.1949999928474426 # available in the structure.oebin file
def get_raw_cluster_spikes(trial: Trial, cluster... | rhayman/ephysiopy | src/ephysiopy/openephys2py/raw_data.py | .py | c1ade1d16abab981 | 7.5 | 9 |
import pytest
import numpy as np
from pathlib import Path
import os
from ephysiopy.common.ephys_generic import PosCalcsGeneric
from ephysiopy.common.utils import BinnedData, VariableToBin, MapType, ClusterID
from ephysiopy.io.recording import AxonaTrial
@pytest.fixture
def basic_xy():
"""
Returns a random 2D ... | rhayman/ephysiopy | src/ephysiopy/tests/conftest.py | .py | c66051c937ab74e9 | 8 | 9 |
#!/usr/bin/env python3
"""
Indian Railway Station Names from Wikipedia
Scrapes railway station names from Wikipedia's list and attempts to fetch
multilingual names from corresponding Wikipedia articles in regional languages.
This provides real, validated station names from public sources.
Usage:
python scrape_wi... | in-rolls/indicate | data/railway_stations/scrape_wikipedia_stations.py | .py | 56b2c43710d262b1 | 7.63 | 17 |
#!/usr/bin/env python3
"""
Wikipedia Interwiki Link Scraper - Generalized
Extracts transliteration pairs from Wikipedia by mining interwiki links.
When the same article exists in multiple language editions, the titles
provide natural transliteration pairs for proper nouns.
This is a generalized version that works on ... | in-rolls/indicate | data/wikipedia_interwiki/scrape_wikipedia_interwiki.py | .py | 3f4aeb8602551c6c | 7.63 | 17 |
#!/usr/bin/env python3
"""
Basic LLM transliteration examples for the indicate package.
Before running these examples, set your API key:
export OPENAI_API_KEY=your-key
# OR
export ANTHROPIC_API_KEY=your-key
# OR
export GOOGLE_API_KEY=your-key
"""
from indicate import IndicLLMTransliterator, detect... | in-rolls/indicate | examples/basic_llm_usage.py | .py | b94ad777bbc27ad6 | 7.63 | 17 |
#!/usr/bin/env python3
"""
File processing examples with safe handling and JSON output.
This example demonstrates the production-ready file handling features
of the indicate package, including backup, resume, and structured output.
"""
import json
import tempfile
from pathlib import Path
from indicate.file_utils imp... | in-rolls/indicate | examples/file_processing.py | .py | 09c3abc54cd46f36 | 7.63 | 17 |
#!/usr/bin/env python3
"""
Large Dataset Processing with Checkpointing
This example shows how to process large DataFrames with automatic checkpointing
for reliability and the ability to resume interrupted processing.
Requirements:
pip install indicate pandas tqdm pyarrow
Features:
- Automatic checkpointing t... | in-rolls/indicate | examples/large_dataset_with_checkpoints.py | .py | 0171ca6a1205dcaf | 7.63 | 17 |
"""Cross-source adjudication: turning raw claims into a ranked, tiered corpus.
The corpus does not assert one canonical romanization. It asserts a *ranked*
list with provenance and a confidence tier, because "official transliteration"
has no single registry behind it -- Survey of India's 1.4 million ground-verified
na... | in-rolls/indicate | gazetteer/adjudicate.py | .py | 2af3c6047cb92a68 | 7.63 | 17 |
"""Stage 3: assemble harvested claims into the published corpus, and report on it.
Run::
uv run python -m gazetteer.build --lang hindi
Reads every redistributable source's stage-2 TSV, drops implausible pairs,
adjudicates the rest into ranked candidates with confidence tiers, joins the
stage-1 frequency evidence... | in-rolls/indicate | gazetteer/build.py | .py | 0a876c80012b9b05 | 7.63 | 17 |
"""Stage 4: is the corpus actually right? Score it against a neutral reference.
Run::
uv run python -m gazetteer.conviction --lang hindi
``gazetteer/build.py`` reports coverage, source agreement and contamination.
Those say the corpus is *internally* coherent. None of them says it is correct.
This does, by scori... | in-rolls/indicate | gazetteer/conviction.py | .py | 50276dc4c8757d3d | 7.63 | 17 |
"""Token frequency mining: deciding which keys are worth looking up.
The gazetteer strategy rests on one empirical fact: Indic name and place tokens
are severely Zipf-distributed, so a small table captures most real-world token
mass. Measured over 4M rows of the Punjab electoral roll, the top 23
``elector_name`` types... | in-rolls/indicate | gazetteer/frequency.py | .py | eb15e5323ec48ab7 | 7.63 | 17 |
"""Harvest bilingual name pairs from the repo's own permissively-licensed data.
Two corpora qualify for the bundle. ``data/affidavits.csv`` holds candidate
names as declared on election affidavits, in Devanagari and Latin side by side.
``data/players_with_hindi_names.json`` holds editorially-maintained cricketer
names... | in-rolls/indicate | gazetteer/harvest_corpus.py | .py | 1d6b2f7a86eaf246 | 7.63 | 17 |
"""Harvest India-scoped bilingual labels from Wikidata (CC0).
Wikidata is the highest value-per-effort source: labels in an Indic language and
in English live on the same entity, so the join is free, and CC0 places no
conditions on redistribution.
**The India scope is a correctness condition, not an optimization.** A... | in-rolls/indicate | gazetteer/harvest_wikidata.py | .py | 46aa815dfa668b9e | 7.63 | 17 |
"""Stage 1: mine token frequency from real corpora to produce the key list.
Run::
uv run --group train python -m gazetteer.mine_frequency --lang punjabi
uv run --group train python -m gazetteer.mine_frequency --lang hindi
Writes ``gazetteer/build/freq/<lang>.tsv`` (the key list) and
``<lang>.coverage.json`` ... | in-rolls/indicate | gazetteer/mine_frequency.py | .py | 7d76a15103f96457 | 7.63 | 17 |
"""Reject candidates that are translations rather than romanizations.
:mod:`gazetteer.plausibility` catches pairs whose *lengths* cannot correspond.
It cannot catch a pair whose length is perfectly ordinary and whose meaning is
simply the wrong relationship. Wikidata labels an entity in every language it
has, so an un... | in-rolls/indicate | gazetteer/phonetic.py | .py | 6b70b1538709f0dc | 7.63 | 17 |
"""Reject candidate pairs that cannot be transliterations of each other.
Positional alignment fires whenever two labels happen to have the same token
count, which occasionally pairs a one-letter Devanagari initial with an English
word: ``के``->``administrative``, ``जे``->``227j``, ``भारत``->
``deindustrialization``. T... | in-rolls/indicate | gazetteer/plausibility.py | .py | c5a5e2096e0551ee | 7.63 | 17 |
"""The candidate-row schema shared by every harvester and the adjudicator.
A harvester's whole job is to turn some source into rows of this shape. Keeping
the schema in one place, with validation at construction, means provenance is
always checkable: a row cannot claim a source that is not registered, and a
Latin side... | in-rolls/indicate | gazetteer/records.py | .py | 72edc8f086d6bf0f | 7.63 | 17 |
"""Fast script detection for corpus tokens.
``EDGE_NOISE`` and ``strip_edge_noise`` are re-exported from
:mod:`indicate.normalize`: the shipped package needs them for query-time keying,
and this build-only package is excluded from the wheel, so they cannot live here.
``indicate.indic_utils.detect_indic_script`` alrea... | in-rolls/indicate | gazetteer/script.py | .py | 1cb9e1cc9a714d26 | 7.63 | 17 |
"""The public transliteration API: one function, any supported direction.
``indicate.transliterate(text)`` detects the script, picks the language pair, and
runs the default engine chain. Everything else is a keyword::
transliterate("राजशेखर चिंतालपति") # auto-detected Hindi
transliterate("ਰ... | in-rolls/indicate | indicate/api.py | .py | de001b7f77645a3e | 7.63 | 17 |
"""Command line interface.
One transliteration command, because the language and the backend are arguments
rather than separate programs::
indicate transliterate "राजशेखर चिंतालपति"
indicate transliterate "ਰਵਿ ਸ਼ਰਮਾ" --from punjabi --engine lookup
indicate transliterate --input names.txt --output roman.tx... | in-rolls/indicate | indicate/cli.py | .py | 9a9df9f65129d119 | 7.63 | 17 |
from __future__ import annotations
import torch
from torch import nn
from torch.nn import functional as F # noqa: N812 - torch convention
class Decoder(nn.Module):
"""LSTM decoder with Luong (dot-product) attention.
Mirrors the original Keras model: the attention query is a linear
projection of the tar... | in-rolls/indicate | indicate/decoder.py | .py | 69591c55d5903bbb | 7.63 | 17 |
from __future__ import annotations
import torch
from torch import nn
class Encoder(nn.Module):
"""LSTM encoder: embedding -> LSTM.
Returns the full output sequence (for attention) and the final
``(hidden, cell)`` state used to initialise the decoder.
"""
def __init__(self, vocab_size: int, embe... | in-rolls/indicate | indicate/encoder.py | .py | ec721898b48770c7 | 7.63 | 17 |
"""Backends, and the order they are tried in.
A word is resolved by the first backend that will answer it. ``lookup`` reads a
table, ``model`` decodes with the local seq2seq weights, ``llm`` asks a provider.
The chain is ordinary data::
("lookup", "model") # the default: table, then decode the tail
... | in-rolls/indicate | indicate/engine.py | .py | 13865566d19d102e | 7.63 | 17 |
"""Safe file handling utilities for transliteration operations."""
from __future__ import annotations
import json
import os
import shutil
import tempfile
import time
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, ClassVar
from .logging import get_logger
logger = get_logger()
c... | in-rolls/indicate | indicate/file_utils.py | .py | 17e79f73afddbd36 | 7.63 | 17 |
"""Script detection and text-shape helpers for Indic input.
The language, script and alias tables these functions used to carry are now in
:mod:`indicate.languages`; there had been four overlapping copies. These are the
thin, text-facing wrappers around them.
"""
from __future__ import annotations
from .languages im... | in-rolls/indicate | indicate/indic_utils.py | .py | 5ac8b14cadc1a09b | 7.63 | 17 |
"""What this install can transliterate, and how it knows.
One registry replaces four overlapping tables that had grown up separately:
``IndicLLMTransliterator.INDIC_LANGUAGES`` plus three dicts inside
``indic_utils`` (script ranges, script-to-language, the Indic-script set). They
agreed by maintenance rather than by c... | in-rolls/indicate | indicate/languages.py | .py | 257809ae1da62f20 | 7.63 | 17 |
"""LLM-based transliteration for Indic languages using LiteLLM."""
from __future__ import annotations
import json
import os
from typing import Any, ClassVar
from litellm import completion
from .logging import get_logger
def _response_text(response: Any) -> str:
"""Extract the message text from a non-streaming... | in-rolls/indicate | indicate/llm_indic.py | .py | 9d7711ddd0bf752a | 7.63 | 17 |
"""Fast word-level lookup: answer from a table, decode only the tail.
On the Punjab electoral roll a table built from ``data/punjabi.csv.gz`` answers
**99.1% of token mass**, so the decoder handles 0.9% of the work. Measured back
to back on one machine (``training/bench_lookup.py``, warm filesystem cache;
absolute val... | in-rolls/indicate | indicate/lookup.py | .py | baf684850de2c3ea | 7.63 | 17 |
"""Canonical key normalization for gazetteer lookup.
Gazetteer keys must be produced identically when the corpus is built and when it
is queried, so this module is the single definition of the ladder. Both the
builder under ``gazetteer/`` and the runtime import from here; nothing
re-implements it.
Lookup keys come in... | in-rolls/indicate | indicate/normalize.py | .py | 23dfca72e24d1c94 | 7.63 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.