text
stringlengths
213
32.3k
import json from django.urls import reverse import weblate.machinery from weblate.trans.tests.test_views import FixtureTestCase from weblate.utils.classloader import load_class class JSViewsTest(FixtureTestCase): """Testing of AJAX/JS views.""" @staticmethod def ensure_dummy_mt(): """Ensure we...
import re from haffmpeg.tools import FFVersion import voluptuous as vol from homeassistant.const import ( ATTR_ENTITY_ID, CONTENT_TYPE_MULTIPART, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from ho...
import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity from homeassistant.components.media_player.const import ( SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PREVIOUS_TRACK, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, ) from homeassista...
from app.database.model import WebHook, Collaborator from sqlalchemy.sql.expression import false # 具有只读权限 def has_readonly_auth(user_id, webhook_id): return has_admin_auth(user_id, webhook_id) or \ has_collaborator_auth(user_id, webhook_id) # 是否有创建者权限 def has_admin_auth(user_id, webhook_id): ret...
from django.contrib import admin from weblate.fonts.models import FontOverride from weblate.wladmin.models import WeblateModelAdmin class FontAdmin(WeblateModelAdmin): list_display = ["family", "style", "project", "user"] search_fields = ["family", "style"] list_filter = [("project", admin.RelatedOnlyFi...
from mongoengine.fields import Document from mongoengine.fields import EmbeddedDocument from mongoengine.fields import EmbeddedDocumentListField from mongoengine.fields import ListField from mongoengine.fields import StringField class EntityValue(EmbeddedDocument): value = StringField(required=True) synonyms...
import json import logging import plexapi.exceptions import requests.exceptions from homeassistant.components.media_player import DOMAIN as MP_DOMAIN, MediaPlayerEntity from homeassistant.components.media_player.const import ( MEDIA_TYPE_MOVIE, MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO, ...
from homeassistant.components.cover import CoverEntity from . import ( ATTR_DISCOVER_CONFIG, ATTR_DISCOVER_DEVICES, DATA_TELLSTICK, DEFAULT_SIGNAL_REPETITIONS, TellstickDevice, ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Tellstick covers.""" if di...
from __future__ import unicode_literals import os from lib.fun.fun import cool from lib.fun.decorator import magic from lib.data.data import pyoptions def handler_magic(*args): """[file]""" args = list(args[0]) if len(args) >= 2: path = args[1] else: exit(pyoptions.CRLF + cool.fuchs...
from tqdm import tqdm from matchzoo.engine.base_preprocessor import BasePreprocessor from matchzoo import DataPack from .chain_transform import chain_transform from .build_vocab_unit import build_vocab_unit from . import units tqdm.pandas() class NaivePreprocessor(BasePreprocessor): """ Naive preprocessor....
from io import open import subprocess from flask import current_app from lemur.utils import mktempfile, mktemppath from lemur.plugins.bases import ExportPlugin from lemur.plugins import lemur_openssl as openssl from lemur.common.utils import get_psuedo_random_string, parse_certificate from lemur.common.defaults impo...
import datetime from homeassistant.components import geonetnz_quakes from homeassistant.components.geo_location import ATTR_SOURCE from homeassistant.components.geonetnz_quakes import DEFAULT_SCAN_INTERVAL, DOMAIN, FEED from homeassistant.components.geonetnz_quakes.geo_location import ( ATTR_DEPTH, ATTR_EXTER...
import os import re import sys import fnmatch import os.path # for command line options and supported environment variables, please # see the end of 'setupinfo.py' if (2, 7) != sys.version_info[:2] < (3, 5): print("This lxml version requires Python 2.7, 3.5 or later.") sys.exit(1) try: from setuptools i...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile import unittest from absl import flags from absl.testing import absltest FLAGS = flags.FLAGS flags.DEFINE_integer('test_id', 0, 'Which test to run.') class HelperTest(absltest.Te...
from __future__ import print_function import logging import urllib2 import kerberos as krb class GssapiAuthError(Exception): """raised on error during authentication process""" import re RGX = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I) def get_negociate_value(headers): for authreq in headers.get...
import io import json from typing import Any, Dict, Optional from urllib.parse import parse_qsl from multidict import CIMultiDict, MultiDict from homeassistant.const import HTTP_OK class MockStreamReader: """Small mock to imitate stream reader.""" def __init__(self, content: bytes) -> None: """Ini...
from flask_script import Manager import sys from lemur.constants import SUCCESS_METRIC_STATUS from lemur.plugins.lemur_acme.acme_handlers import AcmeDnsHandler from lemur.dns_providers.service import get_all_dns_providers, set_domains from lemur.extensions import metrics, sentry manager = Manager( usage="Iterat...
import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_MONITORED_CONDITIONS import homeassistant.helpers.config_validation as cv from homeassistant.helpers.icon import icon_for_battery_level from . import DATA_RAINCLOUD, ICON_MAP, SEN...
from __future__ import division from builtins import str from builtins import range import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import proj3d import matplotlib.animation as animation import matplotlib.patches as patches from .._shared.helpers import * matplotlib.rcParams['pdf.fonttype'...
import json from homeassistant import config_entries from homeassistant.components.ozw.const import DOMAIN from tests.async_mock import Mock, patch from tests.common import MockConfigEntry async def setup_ozw(hass, entry=None, fixture=None): """Set up OZW and load a dump.""" hass.config.components.add("mqt...
import tensornetwork as tn from tensornetwork.backend_contextmanager import _default_backend_stack import pytest import numpy as np def test_contextmanager_simple(): with tn.DefaultBackend("tensorflow"): a = tn.Node(np.ones((10,))) b = tn.Node(np.ones((10,))) assert a.backend.name == b.backend.name def...
import tarfile import os.path as op import os from ...utils import _fetch_file, verbose, _check_option from ..utils import _get_path, logger, _do_path_update @verbose def data_path(dataset='evoked', path=None, force_update=False, update_path=True, verbose=None): u"""Get path to local copy of the hi...
import unittest from trashcli.fstab import FakeFstab class TestFakeFstab(unittest.TestCase): def setUp(self): self.fstab = FakeFstab() def test_default(self): assert ["/"] == self.filter_only_mount_points("/") def test_it_should_accept_fake_mount_points(self): self.fstab.add_mo...
import lakeside from homeassistant.components.switch import SwitchEntity def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Eufy switches.""" if discovery_info is None: return add_entities([EufySwitch(discovery_info)], True) class EufySwitch(SwitchEntity): """Re...
from datetime import timedelta import pytest from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.sonarr.const import DOMAIN from homeassistant.const import ( ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT, DATA_GIGABYTES, STATE_UNAVAILABLE, ) from homeassistant.help...
from pysmartthings import ATTRIBUTES, CAPABILITIES, Attribute, Capability from homeassistant.components.binary_sensor import ( DEVICE_CLASSES, DOMAIN as BINARY_SENSOR_DOMAIN, ) from homeassistant.components.smartthings import binary_sensor from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_...
from homeassistant.core import State from tests.common import async_mock_service async def test_reproducing_states(hass, caplog): """Test reproducing NEW_NAME states.""" hass.states.async_set("NEW_DOMAIN.entity_off", "off", {}) hass.states.async_set("NEW_DOMAIN.entity_on", "on", {"color": "red"}) t...
import logging import subprocess import threading from kalliope.core.NeuronModule import NeuronModule, MissingParameterException logging.basicConfig() logger = logging.getLogger("kalliope") class AsyncShell(threading.Thread): """ Class used to run an asynchrone Shell command .. notes:: Impossible to ge...
from collections import defaultdict import logging import voluptuous as vol from homeassistant.const import CONF_NAME from homeassistant.core import callback from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.util.decorator import Registry from .const...
import unittest import tensorflow as tf import numpy as np from kerastuner.tuners import RandomSearch class TestKerasTuner(unittest.TestCase): def test_search(self): def build_model(hp): x_train = np.random.random((100, 28, 28)) y_train = np.random.randint(10, size=(100, 1)) ...
import functools from io import BytesIO from tornado import httputil from tornado.httpclient import HTTPResponse from vcr.errors import CannotOverwriteExistingCassetteException from vcr.request import Request def vcr_fetch_impl(cassette, real_fetch_impl): @functools.wraps(real_fetch_impl) def new_fetch_imp...
from django.conf.urls import url from django.contrib import admin from django.db.models.fields import Field, FieldDoesNotExist from django.forms import widgets from django.http import HttpResponse from django.template.loader import select_template from django.urls import reverse, NoReverseMatch from django.utils.html ...
import importlib import sys from kombu.exceptions import reraise def symbol_by_name(name, aliases=None, imp=None, package=None, sep='.', default=None, **kwargs): """Get symbol by qualified name. The name should be the full dot-separated path to the class:: modulename.ClassName ...
from datetime import datetime import math from random import Random import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity import homeassistant....
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl.testing import parameterized from compare_gan import datasets from compare_gan import test_utils from compare_gan.gans import consts as c from compare_gan.gans import loss_lib ...
from homeassistant.const import ( SERVICE_ALARM_ARM_AWAY, SERVICE_ALARM_ARM_CUSTOM_BYPASS, SERVICE_ALARM_ARM_HOME, SERVICE_ALARM_ARM_NIGHT, SERVICE_ALARM_DISARM, SERVICE_ALARM_TRIGGER, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_CUSTOM_BYPASS, STATE_ALARM_ARMED_HOME, STATE_ALARM_A...
import hashlib import os import random import string import unittest from docker_registry.core import compat import docker_registry.wsgi as wsgi data_dir = os.path.join(os.path.dirname(__file__), "data") class TestCase(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__...
import pytest import rumps # do this hacky thing notifications = rumps._notifications notify = notifications.notify _clicked = notifications._clicked on_notification = notifications.on_notification Notification = notifications.Notification class NSUserNotificationCenterMock: def __init__(self): self.ns...
import io import logging import subprocess import urllib.parse from smart_open import utils logger = logging.getLogger(__name__) SCHEME = 'hdfs' URI_EXAMPLES = ( 'hdfs:///path/file', 'hdfs://path/file', ) def parse_uri(uri_as_string): split_uri = urllib.parse.urlsplit(uri_as_string) assert split_...
import numpy as np from chainer import cuda from chainercv.links.model.faster_rcnn.utils.bbox2loc import bbox2loc from chainercv.transforms.image.resize import resize from chainercv.utils.bbox.bbox_iou import bbox_iou class ProposalTargetCreator(object): """Assign ground truth classes, bounding boxes and masks...
import asyncio import base64 import collections from contextlib import suppress from datetime import timedelta import hashlib import logging import os from random import SystemRandom from aiohttp import web import async_timeout import attr import voluptuous as vol from homeassistant.components import websocket_api f...
import pathlib import pytest from qutebrowser.browser.webengine import spell from qutebrowser.config import configdata from scripts import dictcli def afrikaans(): return dictcli.Language( code='af-ZA', name='Afrikaans (South Africa)', remote_filename='af-ZA-3-0.bdic') def english(): ...
from .trash import TopTrashDirRules from .trash import TrashDirs from .trash import Harvester from .trash import EX_OK from .trash import Parser from .trash import PrintHelp from .trash import PrintVersion from .trash import EX_USAGE from .trash import ParseTrashInfo import os import sys def main(argv = sys.argv, ...
SNOWSQL_INSTALL_LOCATION = '~/bin' SNOWSQL_VERSION = '1.2.5' SNOWSQL_DOWNLOAD_URL = 'https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/snowsql-%s-linux_x86_64.bash' % SNOWSQL_VERSION def AptInstall(vm): """Installs snowsql on the Debian VM.""" vm.Install('curl') vm.Install('unzip') v...
import os import pytest from molecule import state from molecule import util @pytest.fixture def _instance(config_instance): return state.State(config_instance) def test_state_file_property(_instance): x = os.path.join(_instance._config.scenario.ephemeral_directory, 'state.yml') ...
import numpy as np import unittest import chainer from chainer import initializers from chainer import testing from chainer.testing import attr from chainercv.links.model.ssd import Normalize @testing.parameterize(*testing.product({ 'shape': [(5, 5), (25, 25), (5, 25)], 'n_channel': [1, 10], 'eps': [1e...
import re class Warnings: """Extract warnings from GCC's output Analyzes compiler output and classifies warnings. """ _warning_pattern_map = { 'antiquated': ' antiquated', 'deprecated': ' deprecated', 'unused_func': ' defined but not used', 'isoc': ' ISO C', ...
import numpy from dedupe import predicates from .base import FieldType class PriceType(FieldType): _predicate_functions = [predicates.orderOfMagnitude, predicates.wholeFieldPredicate, predicates.roundTo1] type = "Price" @staticmethod def compar...
import os import os.path import cherrypy localDir = os.path.dirname(__file__) curpath = os.path.normpath(os.path.join(os.getcwd(), localDir)) class HTTPErrorDemo(object): # Set a custom response for 403 errors. _cp_config = {'error_page.403': os.path.join(curpath, 'custom_error.html')} ...
import os import sys from types import ModuleType from flexx import ui, app, event THIS_DIR = os.path.dirname(os.path.abspath(__file__)) DOC_DIR = os.path.abspath(os.path.join(THIS_DIR, '..')) OUTPUT_DIR = os.path.join(DOC_DIR, 'ui') created_files = [] def main(): pages = {} class_names = [] layo...
import tablib from core.models import Book from django.test import TestCase from import_export import instance_loaders, resources class CachedInstanceLoaderTest(TestCase): def setUp(self): self.resource = resources.modelresource_factory(Book)() self.dataset = tablib.Dataset(headers=['id', 'name...
from datetime import date import pytest import voluptuous as vol import homeassistant.components.workday.binary_sensor as binary_sensor from homeassistant.setup import setup_component from tests.async_mock import patch from tests.common import assert_setup_component, get_test_home_assistant FUNCTION_PATH = "homeas...
import threading import copy from mlpatches import base class ThreadLocalVar(object): """creates a proxy to a thread-local version of passee var.""" # todo: maybe add lock? def __init__(self, var): self.__var = var self.__local = threading.local() self.__setattr__ = self.__setatt...
import logging from homeassistant.components.cover import CoverEntity from homeassistant.const import CONF_DEVICES, STATE_OPEN from homeassistant.core import callback from . import ( CONF_AUTOMATIC_ADD, CONF_DATA_BITS, CONF_SIGNAL_REPETITIONS, DEFAULT_SIGNAL_REPETITIONS, SIGNAL_EVENT, RfxtrxC...
import sys import pathlib import yaml import astroid from pylint import interfaces, checkers from pylint.checkers import utils OPTIONS = None FAILED_LOAD = False class ConfigChecker(checkers.BaseChecker): """Custom astroid checker for config calls.""" __implements__ = interfaces.IAstroidChecker name...
import sys from subprocess import check_call as sh def convert_nb(nbname): # Execute the notebook sh(["jupyter", "nbconvert", "--to", "notebook", "--execute", "--inplace", "--ExecutePreprocessor.timeout=60", nbname + ".ipynb"]) # Convert to .rst for Sphinx sh(["jupyter", "nbconvert", "--to", "rst", nbname + ...
import copy import unittest from absl import flags from perfkitbenchmarker.configs import benchmark_config_spec from perfkitbenchmarker.providers.aws import snowflake from tests import pkb_common_test_case _TEST_RUN_URI = 'fakeru' _AWS_ZONE_US_EAST_1A = 'us-east-1a' _BASE_SNOWFLAKE_SPEC = {'type': 'snowflake_aws'} ...
from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from tests.async_mock import patch async def test_delete_script(hass, hass_client): """Test deleting a script.""" with patch.object(config, "SECTIONS", ["script"]): await async_setup_component(hass,...
import configparser import logging import os import re import sqlite3 import sys from threading import local from acdcli.utils.conf import get_conf from .cursors import * from .format import FormatterMixin from .query import QueryMixin from .schema import SchemaMixin from .sync import SyncMixin logger = logging.get...
from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import Mock from mock import patch from diamond.collector import Collector from phpfpm import PhpFpmCollector ########################################################################## class TestPhpFpmColle...
import io import operator import contextlib from typing import TYPE_CHECKING, BinaryIO, IO, Iterator, Optional, Union, cast import pkg_resources from PyQt5.QtCore import (qVersion, QEventLoop, QDataStream, QByteArray, QIODevice, QFileDevice, QSaveFile, QT_VERSION_STR, ...
from pytest import mark from cerberus import errors from cerberus.tests import assert_fail, assert_normalized, assert_success @mark.parametrize( ("test_function", "document"), [ (assert_success, {'a_nullable_integer': None}), (assert_success, {'a_nullable_integer': 3}), (assert_succe...
import json from homeassistant.components.brother.const import DOMAIN from homeassistant.const import CONF_HOST, CONF_TYPE from tests.async_mock import patch from tests.common import MockConfigEntry, load_fixture async def init_integration(hass) -> MockConfigEntry: """Set up the Brother integration in Home Ass...
import logging import pyzerproc from homeassistant import config_entries from homeassistant.helpers import config_entry_flow from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def _async_has_devices(hass) -> bool: """Return if there are devices that can be discovered.""" try: d...
from pyinsteon.groups import ( CO_SENSOR, DOOR_SENSOR, HEARTBEAT, LEAK_SENSOR_WET, LIGHT_SENSOR, LOW_BATTERY, MOTION_SENSOR, OPEN_CLOSE_SENSOR, SENSOR_MALFUNCTION, SMOKE_SENSOR, TEST_SENSOR, ) from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, ...
import os import xml.dom.minidom as dom import roslib.exceptions # stack.xml and manifest.xml have the same internal tags right now REQUIRED = ['author', 'license'] ALLOWXHTML = ['description'] OPTIONAL = ['logo', 'url', 'brief', 'description', 'status', 'notes', 'depend', 'rosdep', 'export', 'review', ...
import pyfnip import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, LightEntity, ) from homeassistant.const import CONF_DEVICES, CONF_HOST, CONF_NAME, CONF_PORT import homeassistant.helpers.config_validation as cv CONF_DRIVER = "dr...
import io import logging import os.path import urllib.parse try: import requests except ImportError: MISSING_DEPS = True from smart_open import bytebuffer, constants import smart_open.utils DEFAULT_BUFFER_SIZE = 128 * 1024 SCHEMES = ('http', 'https') logger = logging.getLogger(__name__) _HEADERS = {'Acce...
import pytest import xarray from xarray import concat, merge from xarray.backends.file_manager import FILE_CACHE from xarray.core.options import OPTIONS, _get_keep_attrs from xarray.tests.test_dataset import create_test_data def test_invalid_option_raises(): with pytest.raises(ValueError): xarray.set_op...
from pymelcloud import DEVICE_TYPE_ATA, DEVICE_TYPE_ATW from pymelcloud.atw_device import Zone from homeassistant.const import ( DEVICE_CLASS_TEMPERATURE, ENERGY_KILO_WATT_HOUR, TEMP_CELSIUS, ) from homeassistant.helpers.entity import Entity from . import MelCloudDevice from .const import DOMAIN ATTR_ME...
import logging from pysignalclirestapi import SignalCliRestApi, SignalCliRestApiError import voluptuous as vol from homeassistant.components.notify import ( ATTR_DATA, PLATFORM_SCHEMA, BaseNotificationService, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) ...
from mlpatches import base class Popen2Patch(base.ModulePatch): """the patch for the popen2 module.""" PY2 = True PY3 = False relpath = "popen2.py" name = "popen2" class SubprocessPatch(base.ModulePatch): """the patch for the subprocess module.""" PY2 = True PY3 = False # uses unic...
from homeassistant.components.nws.const import DOMAIN from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN from tests.common import MockConfigEntry from tests.components.nws.const import NWS_CONFIG async def test_unload_entry(hass, mock_simple_nws): """Test that nws setup with config yaml.""" ...
import os from absl import flags from perfkitbenchmarker import beam_benchmark_helper from perfkitbenchmarker import dpb_service from perfkitbenchmarker import errors from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers import gcp flags.DEFINE_string('dpb_dataflow_staging_location', None, ...
import io import os import pytest import nikola.plugins.command.init from nikola import __main__ from nikola.utils import makedirs from .helper import append_config, cd from .test_empty_build import ( # NOQA test_archive_exists, test_avoid_double_slash_in_rss, test_check_files, test_check_links, ...
import time from time import sleep import random import logging from threading import Lock, local from requests.exceptions import RequestException from .common import * logger = logging.getLogger(__name__) class BackOffRequest(object): """Wrapper for requests that implements timed back-off algorithm https...
from smart_open import open def read_bytes(url, limit): bytes_ = [] with open(url, 'rb') as fin: for i in range(limit): bytes_.append(fin.read(1)) return bytes_ def test(benchmark): # # This file is around 850MB. # url = ( 's3://commoncrawl/crawl-data/CC-MAI...
import pytest from redbot.pytest.economy import * @pytest.mark.asyncio async def test_bank_register(bank, ctx): default_bal = await bank.get_default_balance(ctx.guild) assert default_bal == (await bank.get_account(ctx.author)).balance async def has_account(member, bank): balance = await bank.get_balanc...
from homeassistant.components.climate.const import SUPPORT_TARGET_TEMPERATURE from tests.components.homekit_controller.common import ( Helper, setup_accessories_from_file, setup_test_accessories, ) async def test_lennox_e30_setup(hass): """Test that a Lennox E30 can be correctly setup in HA.""" ...
import pytest from homeassistant.components import owntracks from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_component MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1,...
import logging from typing import List, Optional import voluptuous as vol from homeassistant.components.media_player import ( DEVICE_CLASS_RECEIVER, DEVICE_CLASS_TV, MediaPlayerEntity, ) from homeassistant.components.media_player.const import ( MEDIA_TYPE_APP, MEDIA_TYPE_CHANNEL, SUPPORT_BROW...
from .utils import STRING_TYPE, logger, NO_VALUE ###{standalone class LarkError(Exception): pass class ConfigurationError(LarkError, ValueError): pass def assert_config(value, options, msg='Got %r, expected one of %s'): if value not in options: raise ConfigurationError(msg % (value, options...
from abc import ABC, abstractmethod from asyncio import gather from collections.abc import Mapping import logging import pprint from typing import List, Optional from aiohttp.web import json_response from homeassistant.components import webhook from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_SUPPOR...
import logging from pybotvac import Account, Neato, Vorwerk from pybotvac.exceptions import NeatoLoginException, NeatoRobotException import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_PASSWORD, CONF_USERNAME # pylint: disable=unused-import from .const import CONF_...
from functools import reduce from typing import Set from django.db.models import Q from weblate.machinery.base import BatchStringMachineTranslation, get_machinery_language from weblate.trans.models import Unit from weblate.utils.state import STATE_TRANSLATED class WeblateTranslation(BatchStringMachineTranslation):...
from typing import Any, Dict from twentemilieu import ( WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, TwenteMilieu, TwenteMilieuConnectionError, ) from homeassistant.components.twentemilieu.const import DATA_UPDATE, DOMAIN from homeassistant.config_entri...
import unittest import logging import numpy as np # for arrays, array broadcasting etc. from gensim.models import ldaseqmodel from gensim.corpora import Dictionary from gensim.test.utils import datapath class TestLdaSeq(unittest.TestCase): # we are setting up a DTM model and fitting it, and checking topic-word...
import requests.exceptions from homeassistant import config_entries, setup from homeassistant.components.flume.const import DOMAIN from homeassistant.const import ( CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_PASSWORD, CONF_USERNAME, ) from tests.async_mock import MagicMock, patch def _get_mocked_flum...
import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.websocket_api.decorators import ( async_response, require_admin, ) from homeassistant.core import callback from homeassistant.helpers.area_registry import async_get_registry WS_TYPE_LIST = "config/area_r...
from datetime import timedelta from unittest import mock from requests.exceptions import HTTPError from homeassistant.components.binary_sensor import DOMAIN from homeassistant.components.fritzbox.const import DOMAIN as FB_DOMAIN from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_FRIENDLY_NAME, STA...
import unittest import numpy as np import numpy.testing as np_test from scipy.special import beta from scipy.stats import multivariate_normal from pgmpy.factors.distributions import CustomDistribution class TestCustomDistribution(unittest.TestCase): def pdf1(self, x, y): return np.power(x, 1) * np.powe...
import json from datetime import date, datetime from decimal import Decimal from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.utils import datetime_safe, timezone from django.utils.dateparse import parse_duration from django.utils.encoding import force_str, smart_str ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import unittest from absl import flags from perfkitbenchmarker import sample from perfkitbenchmarker import test_util from perfkitbenchmarker.linux_packages import memtier FLAGS = flags.FLAGS FLAG...
from __future__ import print_function import sys import argparse import time def main(args): ap = argparse.ArgumentParser() ap.add_argument('job_ids', nargs='+', type=int, help='ID of a running job') ns = ap.parse_args(args) _stash = globals()['_stash'] """:type : StaSh""" for job_id in ns...
from __future__ import absolute_import import unittest # These tests check that error handling in the Pyrex code is # complete. # It is likely that if there are errors, instead of failing the code # will simply crash. import sys, gc, os.path from lxml import etree from .common_imports import HelperTestCase class...
from __future__ import print_function, unicode_literals, division import sys import codecs import io import argparse from collections import defaultdict # hack for python2/3 compatibility from io import open argparse.open = open def create_parser(): parser = argparse.ArgumentParser( formatter_class=arg...
from datetime import timedelta from requests.exceptions import HTTPError from homeassistant.components.climate.const import ( ATTR_CURRENT_TEMPERATURE, ATTR_HVAC_MODE, ATTR_HVAC_MODES, ATTR_MAX_TEMP, ATTR_MIN_TEMP, ATTR_PRESET_MODE, ATTR_PRESET_MODES, DOMAIN, HVAC_MODE_HEAT, H...
import io import logging import os import re import sys from more_itertools import always_iterable import cherrypy from cherrypy._cperror import format_exc, bare_error from cherrypy.lib import httputil # ------------------------------ Request-handling def setup(req): from mod_python import apache # Run ...
from datetime import date, datetime, timedelta import logging from pytrafikverket import TrafikverketTrain import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_API_KEY, CONF_NAME, CONF_WEEKDAY, DEVICE_CLASS_TIMESTAMP, WEEKDAYS...
import importlib import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, LightEntity, ) from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv import homea...