text stringlengths 213 32.3k |
|---|
import io
import os
import lxml
import pytest
from nikola import __main__
from .helper import cd, patch_config
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
)
def test_... |
from homeassistant.components.roku.const import DOMAIN
from homeassistant.config_entries import SOURCE_SSDP, SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SOURCE
from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT,
RESULT_TYPE_CREATE_ENTRY,
RESULT_TYPE_FORM,
)
from homeas... |
from marshmallow import fields, post_dump
from lemur.schemas import PluginInputSchema, PluginOutputSchema
from lemur.common.schema import LemurInputSchema, LemurOutputSchema
class SourceInputSchema(LemurInputSchema):
id = fields.Integer()
label = fields.String(required=True)
description = fields.String(... |
from kalliope.core.Models.settings.SettingsEntry import SettingsEntry
class Stt(SettingsEntry):
"""
This Class is representing a Speech To Text (STT) element with name and parameters
.. note:: must be defined in the settings.yml
"""
def __init__(self, name=None, parameters=None):
super(... |
import logging
import W800rf32 as w800
import voluptuous as vol
from homeassistant.const import (
CONF_DEVICE,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import dispatcher_send
DATA_W800RF32 = "data_w8... |
import mock
from docker_registry.lib import cache
from tests.base import TestCase
class TestCache(TestCase):
def setUp(self):
self.cache = mock.MagicMock(
host='localhost', port=1234, db=0, password='pass')
def tearDown(self):
cache.redis_conn = None
cache.cache_prefix ... |
from homeassistant.components.image_processing import ImageProcessingEntity
async def async_setup_platform(
hass, config, async_add_entities_callback, discovery_info=None
):
"""Set up the test image_processing platform."""
async_add_entities_callback([TestImageProcessing("camera.demo_camera", "Test")])
... |
import os
from copy import copy
from nikola.plugin_categories import Task
from nikola import utils
def update_deps(post, lang, task):
"""Update file dependencies as they might have been updated during compilation.
This is done for example by the ReST page compiler, which writes its
dependencies into a ... |
import logging
from urllib.parse import ParseResult, urlparse
from requests.exceptions import HTTPError, Timeout
from sunwatcher.solarlog.solarlog import SolarLog
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_NAME
from homeassistant.core import Home... |
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import Config, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from .account import StarlineAccount
from .const import (
CONF_SCAN_INTERVAL,
DEFAULT_SCAN_INTERVAL,
DOMAIN,
PLAT... |
from __future__ import absolute_import
import sys
import unittest
from .common_imports import HelperTestCase, etree
DOC_NAME = b'libxml2:xmlDoc'
DESTRUCTOR_NAME = b'destructor:xmlFreeDoc'
class ExternalDocumentTestCase(HelperTestCase):
def setUp(self):
try:
import ctypes
from c... |
import os
import unittest
from perfkitbenchmarker.traces import mpstat
class MpstatTestCase(unittest.TestCase):
def setUp(self):
super(MpstatTestCase, self).setUp()
path = os.path.join(
os.path.dirname(__file__), '../data', 'mpstat_output.txt')
with open(path) as fp:
self.contents = fp... |
from datetime import timedelta
import logging
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_API_KEY,
CONF_BASE,
CONF_NAME,
CONF_QUOTE,
HTTP_OK,
)
import homeassistant.helpers.config... |
from django.db import migrations
def update_expired(apps, schema_editor):
Billing = apps.get_model("billing", "Billing")
Billing.objects.using(schema_editor.connection.alias).filter(state=2).update(
state=1
)
class Migration(migrations.Migration):
dependencies = [
("billing", "0003... |
import logging
import os
import socket
import unittest
import vcr
from vcr import config
from vcr.stubs import VCRHTTPSConnection
from pyVmomi import SoapAdapter
def tests_resource_path(local_path=''):
this_file = os.path.dirname(os.path.abspath(__file__))
return os.path.join(this_file, local_path)
# Full... |
import copy
from plexapi.exceptions import BadRequest, NotFound
from requests.exceptions import ConnectionError, RequestException
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.components.media_player.const import (
ATTR_MEDIA_CONTENT_ID,
ATTR_MEDIA_CONTENT_TYPE,
... |
import asyncio
from datetime import datetime, timedelta
import logging
from time import monotonic
from typing import Awaitable, Callable, Generic, List, Optional, TypeVar
import urllib.error
import aiohttp
import requests
from homeassistant.core import CALLBACK_TYPE, HassJob, HomeAssistant, callback
from homeassista... |
from pygal.graph.graph import Graph
from pygal.util import alter, decorate, ident, swap
class Bar(Graph):
"""Bar graph class"""
_series_margin = .06
_serie_margin = .06
def _bar(self, serie, parent, x, y, i, zero, secondary=False):
"""Internal bar drawing function"""
width = (self.v... |
import numpy as np
from jax import config
import pytest
import tensornetwork
import tensornetwork.linalg.krylov
import tensornetwork.linalg.initialization
from tensornetwork.tests import testing_utils
# pylint: disable=no-member
config.update("jax_enable_x64", True)
sparse_backends = ["numpy", "jax"]
@pytest.mark.p... |
from flask_script import Manager
from lemur.policies import service as policy_service
manager = Manager(usage="Handles all policy related tasks.")
@manager.option("-d", "--days", dest="days", help="Number of days before expiration.")
@manager.option("-n", "--name", dest="name", help="Policy name.")
def create(days... |
import tensorflow as tf
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
fr... |
import mock
import pysensu_yelp
import pytest
from paasta_tools import check_flink_services_health
from paasta_tools import check_services_replication_tools
from paasta_tools.check_flink_services_health import check_under_registered_taskmanagers
from paasta_tools.utils import compose_job_id
check_flink_services_heal... |
from homeassistant.components import persistent_notification
from homeassistant.core import HomeAssistant
DOMAIN = "safe_mode"
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Safe Mode component."""
persistent_notification.async_create(
hass,
"Home Assistant is runnin... |
import argparse
from collections import OrderedDict
from flask import Flask, render_template
from werkzeug.serving import run_simple
try:
from werkzeug.middleware.dispatcher import DispatcherMiddleware
except ImportError:
from werkzeug.wsgi import DispatcherMiddleware
from flasgger import __version__
from fl... |
import numpy as np
from tensornetwork.block_sparse.index import Index
from tensornetwork.block_sparse.blocksparsetensor import _randn, _random
from tensornetwork.block_sparse.blocksparsetensor import BlockSparseTensor
from typing import Tuple, Type, Optional, Sequence
def ones(indices: Sequence[Index],
dtyp... |
import logging
import string
from absl import flags
from perfkitbenchmarker import disk
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.providers.cloudstack import util
FLAGS = flags.FLAGS
class CloudStackDisk(disk.BaseDisk):
"""Object representing a Cloudstack Disk."""
def __init__(self, disk_... |
from datetime import datetime
from homeassistant.const import EVENT_HOMEASSISTANT_START
from homeassistant.core import CoreState, State
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.restore_state import (
DATA_RESTORE_STATE_TASK,... |
import argparse
import sys
import time
from time import sleep
from typing import Optional
from typing import Sequence
from typing import Tuple
from paasta_tools import mesos_tools
from paasta_tools.frameworks.native_scheduler import create_driver
from paasta_tools.frameworks.native_scheduler import get_paasta_native_... |
from abc import ABC
import logging
from typing import Any, Dict, Optional
from pymodbus.exceptions import ConnectionException, ModbusException
from pymodbus.pdu import ExceptionResponse
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity
from homeassistant.const import ... |
import ast
import os
import sys
# =================== check if run inside pythonista ===================
IN_PYTHONISTA = sys.executable.find('Pythonista') >= 0
if IN_PYTHONISTA:
print("It appears that you are running this file using the pythonista app.")
print("The setup.py file is intended for the installa... |
VERSION = '7.1.0'
long_description = '''\
ReText is simple text editor that supports Markdown and reStructuredText
markup languages. It is written in Python using PyQt libraries.
It supports live preview, tabs, math formulas, export to various formats
including PDF and HTML.
For more details, please go to the `home... |
from distutils.version import LooseVersion
import numpy as np
import pandas as pd
import pytest
import xarray as xr
from xarray.core import formatting_html as fh
@pytest.fixture
def dataarray():
return xr.DataArray(np.random.RandomState(0).randn(4, 6))
@pytest.fixture
def dask_dataarray(dataarray):
pytes... |
import os.path as op
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_less
from mne.datasets.testing import data_path
from mne.io import read_raw_nirx
from mne.preprocessing.nirs import optical_density, scalp_coupling_index,\
beer_lambert_law
from mne.datasets import testi... |
from copy import deepcopy
import numpy as np
from scipy import linalg
from ..cov import Covariance, make_ad_hoc_cov
from ..forward.forward import is_fixed_orient, _restrict_forward_to_src_sel
from ..io.proj import make_projector, Projection
from ..minimum_norm.inverse import _get_vertno, _prepare_forward
from ..sour... |
from flask import current_app
from lemur import database
from lemur.certificates.models import Certificate
from lemur.common.utils import truthiness
from lemur.notifications.models import Notification
def create_default_expiration_notifications(name, recipients, intervals=None):
"""
Will create standard 30,... |
import unittest
import numpy as np
from chainer import testing
from chainercv.transforms import random_rotate
class TestRandomRotate(unittest.TestCase):
def test_random_rotate(self):
img = np.random.uniform(size=(3, 24, 24))
out, param = random_rotate(img, return_param=True)
k = param... |
from django.utils import timezone
from rest_framework import serializers
from shop.conf import app_settings
from shop.models.cart import CartModel
from shop.models.order import OrderModel
from shop.modifiers.pool import cart_modifiers_pool
from shop.rest.money import MoneyField
class OrderListSerializer(serializers.... |
from pysqueezebox import Server
from homeassistant import config_entries
from homeassistant.components.squeezebox.const import DOMAIN
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
HTTP_UNAUTHORIZED,
)
from homeassistant.data_entry_flow import (
RESULT_TY... |
import pytest
from shop.forms.checkout import ShippingAddressForm
from shop.views.address import AddressEditView
from shop.views.checkout import CheckoutViewSet
@pytest.mark.django_db
def test_customer_form(registered_customer, api_rf, empty_cart):
data = {
'customer': {
'salutation': "mr",
... |
import os
import sys
import logging
import argparse
import threading
import time
from queue import Queue
import Pyro4
from gensim import utils
logger = logging.getLogger(__name__)
# How many jobs (=chunks of N documents) to keep "pre-fetched" in a queue?
# A small number is usually enough, unless iteration over t... |
from asyncio import Future
from homeassistant.components.group.reproduce_state import async_reproduce_states
from homeassistant.core import Context, State
from tests.async_mock import patch
async def test_reproduce_group(hass):
"""Test reproduce_state with group."""
context = Context()
def clone_state... |
import copy
import json
import pytest
from homeassistant.components import switch
from homeassistant.const import ATTR_ASSUMED_STATE, STATE_OFF, STATE_ON
import homeassistant.core as ha
from homeassistant.setup import async_setup_component
from .test_common import (
help_test_availability_when_connection_lost,
... |
from collections import defaultdict
from typing import Callable
from typing import Dict
_autoscaling_components: Dict[str, Dict[str, Callable]] = defaultdict(dict)
def register_autoscaling_component(name, method_type):
def outer(autoscaling_method):
_autoscaling_components[method_type][name] = autoscal... |
import urwid
class Pudding(urwid.Widget):
_sizing = frozenset(['flow'])
def rows(self, size, focus=False):
return 1
def render(self, size, focus=False):
(maxcol,) = size
num_pudding = maxcol / len("Pudding")
return urwid.TextCanvas(["Pudding" * num_pudding], maxcol=maxcol... |
import logging
import secrets
from typing import Optional
from toonapi import Status, Toon, ToonError
from homeassistant.components.webhook import (
async_register as webhook_register,
async_unregister as webhook_unregister,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const impo... |
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.const import CONF_NAME
from . import PiHoleEntity
from .const import DATA_KEY_API, DATA_KEY_COORDINATOR, DOMAIN as PIHOLE_DOMAIN
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Pi-hole binary sen... |
from plumbum.commands.processes import CommandNotFound
from plumbum.commands.processes import ProcessExecutionError
from plumbum.commands.processes import ProcessTimedOut
class PopenAddons(object):
"""This adds a verify to popen objects to that the correct command is attributed when
an error is thrown."""
... |
from typing import List
import voluptuous as vol
from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_TYPE
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from . import ... |
import pickle
import random
from collections import deque
from copy import copy as shallow_copy
import pytest
from markupsafe import Markup
from jinja2.utils import consume
from jinja2.utils import generate_lorem_ipsum
from jinja2.utils import LRUCache
from jinja2.utils import missing
from jinja2.utils import object... |
from httplib2 import HTTPConnectionWithTimeout, HTTPSConnectionWithTimeout
from ..stubs import VCRHTTPConnection, VCRHTTPSConnection
class VCRHTTPConnectionWithTimeout(VCRHTTPConnection, HTTPConnectionWithTimeout):
_baseclass = HTTPConnectionWithTimeout
def __init__(self, *args, **kwargs):
"""I over... |
import logging
import aiohttp
from homeassistant.components.light import SUPPORT_BRIGHTNESS, LightEntity
from homeassistant.const import CONF_HOST
from homeassistant.exceptions import PlatformNotReady
from . import DATA_SISYPHUS
_LOGGER = logging.getLogger(__name__)
SUPPORTED_FEATURES = SUPPORT_BRIGHTNESS
async... |
import dbm
import json
import subprocess
import sys
def dbm_iter(db):
# try dictionary interface - ok in python2 and dumbdb
try:
return db.items()
except Exception:
# try firstkey/nextkey - ok for py3 dbm.gnu
def iter_gdbm(db):
k = db.firstkey()
while k is ... |
import numpy as np
from qstrader.portcon.order_sizer.order_sizer import OrderSizer
class LongShortLeveragedOrderSizer(OrderSizer):
"""
Creates a target portfolio of quantities for each Asset
using its provided weight and total equity available in the
Broker portfolio, leveraging up if necessary via ... |
import argparse
from sandman2 import get_app
def main():
"""Main entry point for script."""
parser = argparse.ArgumentParser(
description='Auto-generate a RESTful API service '
'from an existing database.'
)
parser.add_argument(
'URI',
help='Database URI in the for... |
from aiohttp import ClientSession
from google.oauth2.credentials import Credentials
from google_nest_sdm.auth import AbstractAuth
from homeassistant.helpers import config_entry_oauth2_flow
# See https://developers.google.com/nest/device-access/registration
class AsyncConfigEntryAuth(AbstractAuth):
"""Provide G... |
import numpy as np
import pytest
from tensornetwork.block_sparse.charge import (U1Charge, charge_equal,
BaseCharge)
from tensornetwork.block_sparse.index import Index
from tensornetwork.block_sparse.blocksparsetensor import (BlockSparseTensor,
... |
import argparse
import logging
import sys
from typing import Optional
from typing import Sequence
from typing import Tuple
from paasta_tools.kubernetes.application.controller_wrappers import Application
from paasta_tools.kubernetes.application.controller_wrappers import (
get_application_wrapper,
)
from paasta_to... |
import pytest
from PyQt5.QtCore import QUrl
pytest.importorskip('PyQt5.QtWebEngineCore')
from PyQt5.QtWebEngineCore import QWebEngineCookieStore
from PyQt5.QtWebEngineWidgets import QWebEngineProfile
from qutebrowser.browser.webengine import cookies
from qutebrowser.utils import urlmatch
@pytest.fixture
def filter_... |
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
BinarySensorEntity,
)
from . import DOMAIN as ZONEMINDER_DOMAIN
async def async_setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the ZoneMinder binary sensor platform."""
sensors = []
for ho... |
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
BinarySensorEntity,
)
from . import CONF_DOOR_WINDOW, HUB as hub
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Verisure binary sensors."""
sensors = []
hub.update_overview()
... |
import urwid
class SelectablePudding(urwid.Widget):
_sizing = frozenset(['flow'])
_selectable = True
def __init__(self):
self.pudding = "pudding"
def rows(self, size, focus=False):
return 1
def render(self, size, focus=False):
(maxcol,) = size
num_pudding = maxco... |
from wled import WLEDConnectionError
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.components.wled.const import (
ATTR_DURATION,
ATTR_FADE,
ATTR_TARGET_BRIGHTNESS,
ATTR_UDP_PORT,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_ICON,
SERVICE... |
from homeassistant.components.switch import SwitchEntity
from . import BleBoxEntity, create_blebox_entities
from .const import BLEBOX_TO_HASS_DEVICE_CLASSES
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up a BleBox switch entity."""
create_blebox_entities(
hass, config_... |
import inspect
import logging
class EffectSync(object):
"""
Class which deals with receiving effect events from other devices
"""
def __init__(self, parent, device_number):
self._logger = logging.getLogger('razer.device{0}.effect_sync'.format(device_number))
self._parent = parent
... |
from __future__ import division
import collections
import glob
import optparse
import os
import re
import sys
import textwrap
import disgen
from coverage.parser import PythonParser
from coverage.python import get_python_source
opcode_counts = collections.Counter()
class ParserMain(object):
"""A main for code... |
from inflection import underscore
from sqlalchemy import exc, func, distinct
from sqlalchemy.orm import make_transient, lazyload
from sqlalchemy.sql import and_, or_
from lemur.exceptions import AttrNotFound, DuplicateError
from lemur.extensions import db
def filter_none(kwargs):
"""
Remove all `None` value... |
import os
def boot(application, api_key, flavor, version):
# Configure bugsnag
if api_key:
try:
import bugsnag
import bugsnag.flask
root_path = os.path.abspath(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
bugsnag.config... |
import os
from optional_django import staticfiles
from .exceptions import ComponentSourceFileNotFound
from .render_server import render_server
def render_component(path, props=None, to_static_markup=False, renderer=render_server, request_headers=None, timeout=None):
if not os.path.isabs(path):
abs_path =... |
import numpy as np
import unittest
import chainer
from chainer import testing
from chainer.testing import attr
from chainercv.links import YOLOv2
@testing.parameterize(*testing.product({
'n_fg_class': [1, 5, 20],
}))
class TestYOLOv2(unittest.TestCase):
def setUp(self):
self.link = YOLOv2(n_fg_cla... |
import logging
import threading
from abc import ABC
from abc import abstractmethod
from time import sleep
from typing import Optional
from typing import Union
from kubernetes.client import V1beta1PodDisruptionBudget
from kubernetes.client import V1DeleteOptions
from kubernetes.client import V1Deployment
from kubernet... |
import os
import numpy as np
import pandas as pd
import pathos
from sklearn.base import BaseEstimator, TransformerMixin
class Ensembler(BaseEstimator, TransformerMixin):
def __init__(self, ensemble_predictors, type_of_estimator, ensemble_method='average', num_classes=None):
self.ensemble_predictors ... |
import re
from typing import Iterable, Tuple
from PyQt5.QtCore import Qt, QSortFilterProxyModel, QRegExp
from PyQt5.QtGui import QStandardItem, QStandardItemModel
from PyQt5.QtWidgets import QWidget
from qutebrowser.completion.models import util
from qutebrowser.utils import qtutils, log
class ListCategory(QSortFi... |
from typing import Dict, List
import voluptuous as vol
from homeassistant.components.device_automation.const import CONF_IS_OFF, CONF_IS_ON
from homeassistant.const import ATTR_DEVICE_CLASS, CONF_ENTITY_ID, CONF_FOR, CONF_TYPE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import c... |
import platform
import sys
from types import CodeType
from . import TemplateSyntaxError
from .utils import internal_code
from .utils import missing
def rewrite_traceback_stack(source=None):
"""Rewrite the current exception to replace any tracebacks from
within compiled template code with tracebacks that loo... |
import logging
import pytest
import hypothesis
from hypothesis import strategies
from qutebrowser.browser.webkit import http, rfc6266
@pytest.mark.parametrize('template', [
'{}',
'attachment; filename="{}"',
'inline; {}',
'attachment; {}="foo"',
"attachment; filename*=iso-8859-1''{}",
'atta... |
from binascii import hexlify, unhexlify
import logging
from serial import Serial, SerialException
import voluptuous as vol
from xbee_helper import ZigBee
import xbee_helper.const as xb_const
from xbee_helper.device import convert_adc
from xbee_helper.exceptions import ZigBeeException, ZigBeeTxFailure
from homeassist... |
from textwrap import wrap
from weblate.checks.format import BaseFormatCheck
from weblate.checks.models import CHECKS
from weblate.utils.management.base import BaseCommand
def sorter(check):
if isinstance(check, BaseFormatCheck):
pos = 1
elif check.name < "Formatted strings":
pos = 0
else... |
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from jbossapi import JbossApiCollector
###############################################################################
class TestJbossApiCollector(CollectorTestCase):
def setUp(self):
config = get_collec... |
import asyncio
from datetime import timedelta
from pyflunearyou import Client
from pyflunearyou.errors import FluNearYouError
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import callback
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassist... |
import logging
from omnilogic import LoginException, OmniLogic, OmniLogicException
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import callback
from homeassistant.helpers import aiohttp_client
from .const impor... |
from math import isclose
from arcam.fmj import DecodeMode2CH, DecodeModeMCH, IncomingAudioFormat, SourceCodes
import pytest
from homeassistant.components.media_player.const import (
ATTR_INPUT_SOURCE,
MEDIA_TYPE_MUSIC,
SERVICE_SELECT_SOURCE,
)
from homeassistant.const import ATTR_ENTITY_ID
from .conftes... |
from sqlalchemy import Column, Integer, String, Text
from sqlalchemy_utils import JSONType
from lemur.database import db
from lemur.plugins.base import plugins
class Destination(db.Model):
__tablename__ = "destinations"
id = Column(Integer, primary_key=True)
label = Column(String(32))
options = Colu... |
from __future__ import unicode_literals
from lib.data.data import pystrs
from lib.fun.decorator import magic
from lib.fun.fun import range_compatible
def pid8_magic(*args):
"""chinese id card last 8 digit"""
posrule = lambda _: str(_) if _ >= 10 else "0" + str(_)
# month
value1112 = " ".join(posrul... |
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
class JSONField(models.TextField):
"""JSON serializaed TextField."""
def __init__(self, **kwargs):
if "default" not in kwargs:
kwargs["default"] = {}
super().__init__(**kwargs)
... |
from __future__ import division
import unittest
import numpy as np
from chainer.backends import cuda
from chainer import testing
from chainer.testing import attr
from chainercv.utils import mask_to_bbox
@testing.parameterize(
{'mask': np.array(
[[[False, False, False, False],
[False, True, ... |
from datetime import timedelta
from pythinkingcleaner import Discovery, ThinkingCleaner
import voluptuous as vol
from homeassistant import util
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_HOST, PERCENTAGE
import homeassistant.helpers.config_validation as cv
from h... |
import socket
import struct
import numpy
VERSION = 1
PUT_HDR = 0x101
PUT_DAT = 0x102
PUT_EVT = 0x103
PUT_OK = 0x104
PUT_ERR = 0x105
GET_HDR = 0x201
GET_DAT = 0x202
GET_EVT = 0x203
GET_OK = 0x204
GET_ERR = 0x205
FLUSH_HDR = 0x301
FLUSH_DAT = 0x302
FLUSH_EVT = 0x303
FLUSH_OK = 0x304
FLUSH_ERR = 0x305
WAIT_DAT = 0x402
W... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import activations, initializers, regularizers
from tensorflow.keras.layers import Layer
from tensorflow.python.keras.utils import conv_utils #pylint: disable=no-name-in-module
from typing import List, Tuple, Text, Optional, Union
import numpy ... |
from Handler import Handler
from diamond.collector import get_hostname
import os
HAVE_SSL = True
try:
import ssl
except ImportError:
HAVE_SSL = False
try:
import mosquitto
except ImportError:
mosquitto = None
__author__ = 'Jan-Piet Mens'
__email__ = 'jpmens@gmail.com'
class MQTTHandler(Handler):
... |
from astral import Astral
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.util.dt as dt_util
DEFAULT_NAME = "Moon"
... |
try:
import dask
import dask.array
from dask.array.utils import meta_from_array
from dask.highlevelgraph import HighLevelGraph
except ImportError:
pass
import collections
import itertools
import operator
from typing import (
Any,
Callable,
DefaultDict,
Dict,
Hashable,
Iter... |
import getopt
import os
import re
import sys
import time
import cherrypy
from cherrypy import _cperror, _cpmodpy
from cherrypy.lib import httputil
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
AB_PATH = ''
APACHE_PATH = 'apache'
SCRIPT_NAME = '/cpbench/users/rdelon/apps/blog'
__all__ = ['ABSession... |
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_OCCUPANCY,
BinarySensorEntity,
)
from .const import _LOGGER, DOMAIN, ECOBEE_MODEL_TO_NAME, MANUFACTURER
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up ecobee binary (occupancy) sensors."""
data = hass.d... |
import os
from flask import Flask
from flask_testing import LiveServerTestCase
from kalliope.core import LifoManager
from kalliope.core.ConfigurationManager import BrainLoader
from kalliope.core.ConfigurationManager import SettingLoader
from kalliope.core.Models import Singleton
from kalliope.core.RestAPI.FlaskAPI i... |
import functools
import email.utils
import re
import builtins
from binascii import b2a_base64
from cgi import parse_header
from email.header import decode_header
from http.server import BaseHTTPRequestHandler
from urllib.parse import unquote_plus
import jaraco.collections
import cherrypy
from cherrypy._cpcompat impo... |
from homeassistant.components import axis
from homeassistant.components.axis.const import CONF_MODEL, DOMAIN as AXIS_DOMAIN
from homeassistant.const import (
CONF_DEVICE,
CONF_HOST,
CONF_MAC,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
)
from homeassistant.setup import async_setup_c... |
import os.path as op
import pytest
from mne import read_selection
from mne.io import read_raw_fif
from mne.utils import run_tests_if_main
test_path = op.join(op.split(__file__)[0], '..', 'io', 'tests', 'data')
raw_fname = op.join(test_path, 'test_raw.fif')
raw_new_fname = op.join(test_path, 'test_chpi_raw_sss.fif')... |
from __future__ import print_function, absolute_import
import sys
from functools import reduce
from .names import color_names, default_styles
from .styles import ColorNotFound
__all__ = ['ColorFactory', 'StyleFactory']
class ColorFactory(object):
"""This creates color names given fg = True/False. It usually wil... |
import os
import shutil
import uuid
from queue import Empty
import tempfile
from time import monotonic
from . import virtual
from kombu.exceptions import ChannelError
from kombu.utils.encoding import bytes_to_str, str_to_bytes
from kombu.utils.json import loads, dumps
from kombu.utils.objects import cached_property
... |
import doctest
import io
import sys, os, tempfile, shutil
from stat import S_IWRITE
from os.path import join
from logilab.common.testlib import TestCase, unittest_main, unittest
from logilab.common.fileutils import *
DATA_DIR = join(os.path.abspath(os.path.dirname(__file__)), 'data')
NEWLINES_TXT = join(DATA_DIR, '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.