code stringlengths 1 199k |
|---|
"""
Nexus
~~~~~
"""
try:
VERSION = __import__('pkg_resources') \
.get_distribution('nexus').version
except Exception:
VERSION = 'unknown'
from nexus.sites import NexusSite, site
from nexus.modules import NexusModule
__all__ = ('autodiscover', 'NexusSite', 'NexusModule', 'site')
LOADING = False
def autod... |
"""Model evaluation tools for TFGAN.
These methods come from https://arxiv.org/abs/1606.03498 and
https://arxiv.org/abs/1706.08500.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import sys
import tarfile
from six.moves import urllib
fro... |
"""Interface to TerminalInteractiveShell for PyDev Interactive Console frontend
for IPython 0.11 to 1.0+.
"""
from __future__ import print_function
import os
import codeop
from IPython.core.error import UsageError
from IPython.core.completer import IPCompleter
from IPython.core.interactiveshell import InteractiveShe... |
"""Tests for cond_v2."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import... |
model = H2ODeepWaterEstimator(epochs=100, image_shape=[28,28], backend="mxnet", network="user", network_definition_file="/path/to/lenet.json", network_parameters_file="/path/to/lenet-100epochs-params.txt") |
"""This script produces the expression parser."""
from __future__ import annotations
import argparse
import os
import subprocess
from . import common
from . import setup
_PARSER = argparse.ArgumentParser(
description="""
Run this script from the oppia root folder:
python -m scripts.create_expression_parser
The ... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
import re
from devlib.module import Module
class TripPoint(object):
def __init__(self, zone, _id):
self._id = _id
self.zone = zone
self.temp_node = 'trip_point_' + _id + '_temp'
self.type_node = 'trip_point_' + _id + '_type'
@property
def target(self):
return self.zon... |
"""
Support for Telldus Live.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/tellduslive/
"""
from datetime import datetime, timedelta
import logging
from homeassistant.const import (
ATTR_BATTERY_LEVEL, DEVICE_DEFAULT_NAME,
CONF_TOKEN, CONF_HOST... |
from lxml import etree
import webob
from nova.api.openstack.compute.plugins.v3 import flavor_disabled
from nova.compute import flavors
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes
FAKE_FLAVORS = {
'flavor 1': {
"flavorid": '1',
"name": ... |
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_... |
"""Tests for the `NoopElimination` optimization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.experimental.ops import optimization
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops impo... |
import struct
from . import packet_base
from . import packet_utils
class udp(packet_base.PacketBase):
"""UDP (RFC 768) header encoder/decoder class.
An instance has the following attributes at least.
Most of them are same to the on-wire counterparts but in host byte order.
__init__ takes the correspondi... |
"""Python context management helper."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class IdentityContextManager(object):
"""Returns an identity context manager that does nothing.
This is helpful in setting up conditional `with` statement as below:
... |
from PyObjCTools.TestSupport import *
from AppKit import *
try:
unicode
except NameError:
unicode = str
try:
long
except NameError:
long = int
class TestNSAttributedString (TestCase):
def testConstants(self):
self.assertIsInstance(NSFontAttributeName, unicode)
self.assertIsInstance(N... |
from twisted.python import usage
from ooni.templates import httpt
from ooni.utils import log
class UsageOptions(usage.Options):
optParameters = [ ['expectedBody', 'B',
'I’m just a happy little web server.\n',
'Expected body content from GET response'],
... |
"""
ViewSets are essentially just a type of class based view, that doesn't provide
any method handlers, such as `get()`, `post()`, etc... but instead has actions,
such as `list()`, `retrieve()`, `create()`, etc...
Actions are only bound to methods at the point of instantiating the views.
user_list = UserViewSet.as_... |
'''
=========================================================================
Program: Visualization Toolkit
Module: TestNamedColorsIntegration.py
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This ... |
import os.path
import sys
import in_generator
import make_runtime_features
import template_expander
class InternalRuntimeFlagsWriter(make_runtime_features.RuntimeFeatureWriter):
class_name = "InternalRuntimeFlags"
def __init__(self, in_file_path, enabled_conditions):
super(InternalRuntimeFlagsWriter, se... |
from __future__ import absolute_import, division, print_function
import logging
import numpy as np
from numpy.testing import assert_array_equal
import skbeam.core.mask as mask
logger = logging.getLogger(__name__)
def test_threshold_mask():
xdim = 10
ydim = 10
stack_size = 10
img_stack = np.random.randin... |
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
if 'djangocms_text_ckeditor' in settings.INSTALLED_APPS:
from djangocms_text_ckeditor.models import AbstractText
from djangocms_text_ckeditor.cms_plugins import TextPlugin
else:
try:
from cms.plugins.text.models... |
import pytest
from bravado_core.schema import get_format
from bravado_core.spec import Spec
@pytest.fixture
def int32_spec():
return {'type': 'integer', 'format': 'int32'}
@pytest.fixture
def int_spec():
return {'type': 'integer'}
def test_found(minimal_swagger_spec, int32_spec):
assert 'int32' == get_forma... |
from .. utils import TranspileTestCase, BuiltinTwoargFunctionTestCase
class DelattrTests(TranspileTestCase):
def test_minimal(self):
self.assertCodeExecution("""
class MyClass(object):
class_value = 42
def __init__(self, val):
self.value = val
... |
def barrier(*args):
return None
def getitem(x, key):
"""Like :func:`operator.getitem`, but allows setting key using partial
``partial(chunk.getitem, key=key)
"""
return x[key]
def foldby_combine2(combine, acc, x):
return combine(acc, x[1])
def groupby_tasks_group_hash(x, hash, grouper):
retu... |
"""XHR endpoint to fill in navbar fields."""
import json
from dashboard.common import request_handler
class NavbarHandler(request_handler.RequestHandler):
"""XHR endpoint to fill in navbar fields."""
def post(self):
template_values = {}
self.GetDynamicVariables(template_values, self.request.get('path'))
... |
from __future__ import print_function, division
exec("from sympy import *")
LT = laplace_transform
FT = fourier_transform
MT = mellin_transform
IFT = inverse_fourier_transform
ILT = inverse_laplace_transform
IMT = inverse_mellin_transform
from sympy.abc import x, s, a, b, c, d, t, y, z
nu, beta, rho = symbols('nu beta ... |
import numpy as np
def __adjusted_meshgrid(shape):
"""
Creates an adjusted meshgrid that accounts for odd image sizes. Linearly
interpolates the values. This meshgrid assumes 'ij' indexing - which is
due to the 1st dimension of an image being the y-dimension.
Parameters
----------
shape: tup... |
"""Utilities for making samples.
Consolidates a lot of code commonly repeated in sample applications.
"""
from __future__ import absolute_import
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = ['init']
import argparse
import os
from googleapiclient import discovery
from googleapiclient.http import build_h... |
"""
This bot unlinks a page on every page that links to it.
This script understands this command-line argument:
-namespace:n Number of namespace to process. The parameter can be used
multiple times. It works in combination with all other
parameters, except for the -start para... |
"""
This module contains the main interface to the botocore package, the
Session object.
"""
import copy
import logging
import os
import platform
from botocore import __version__
import botocore.configloader
import botocore.credentials
import botocore.client
from botocore.exceptions import ConfigNotFound, ProfileNotFou... |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
import Autodesk
clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.Elements)
import System.Reflection
import System.AppDomain
rAssembly = [x for x in System.AppDomain.CurrentDomain.GetAssemblies() if x.GetName().Name == 'RevitAP... |
import unittest
import os
from pymatgen import Molecule
from pymatgen.io.fiesta import FiestaInput, FiestaOutput
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files')
class FiestaInputTest(unittest.TestCase):
def setUp(self):
coords = [[0.000000, 0.000000, 0.000000],
... |
"""
Copyright (C) International Business Machines Corp., 2005
Author: Stefan Berger <stefanb@us.ibm.com>
Based on XenDomain.py by Dan Smith <danms@us.ibm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software... |
from Components.Converter.Converter import Converter
from enigma import iServiceInformation, iPlayableService
from Components.Element import cached
WIDESCREEN = [3, 4, 7, 8, 0xB, 0xC, 0xF, 0x10]
class SDGServiceInfo(Converter, object):
HAS_TELETEXT = 0
IS_MULTICHANNEL = 1
IS_CRYPTED = 2
IS_WIDESCREEN = 3
SUBSERVIC... |
import unittest
import tempfile
import os
from giscanner.sourcescanner import SourceScanner
two_typedefs_source = """
/**
* Spam:
*/
typedef struct _spam Spam;
/**
* Eggs:
*/
typedef struct _eggs Eggs;
"""
class Test(unittest.TestCase):
def setUp(self):
self.ss = SourceScanner()
tmp_fd, tmp_name... |
import os
from unittest import TestCase
from collections import namedtuple
from urlparse import urljoin
from mock import patch, Mock, ANY
from pulp_puppet.common import constants
from pulp_puppet.plugins.importers.directory import SynchronizeWithDirectory, DownloadListener
from pulp_puppet.common.sync_progress import S... |
import sys
from arachnid.core.metadata import spider_utility
from arachnid.core.image import ndimage_file
from arachnid.core.image import ndimage_interpolate
import glob
def decimate(input_files,output_file,bin_factor):
input_files = glob.glob(input_files)
print "processing %d files"%len(input_files)
img = ... |
import os, subprocess
import logging
from autotest.client import test
from autotest.client.shared import error
class perl_Text_ParseWords(test.test):
"""
Autotest module for testing basic functionality
of perl_Text_ParseWords
@author Charishma M <charism2@in.ibm.com>
"""
version = 1
nfail = ... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'network'}
DOCUMENTATION = '''
---
module: nxos_mtu
extends_documentation_fragment: nxos
version_added: "2.2"
deprecated: Deprecated in 2.3 use M(nxos_system)'s C(mtu) option.
short_descripti... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cstr, flt
import json, copy
from six import string_types
class ItemVariantExistsError(frappe.ValidationError): pass
class InvalidItemAttributeValueError(frappe.ValidationError): pass
class ItemTemplateCannotHaveStock(fra... |
from marionette_driver import By
from firefox_puppeteer.ui.about_window.deck import Deck
from firefox_puppeteer.ui.windows import BaseWindow, Windows
class AboutWindow(BaseWindow):
"""Representation of the About window."""
window_type = 'Browser:About'
dtds = [
'chrome://branding/locale/brand.dtd',
... |
import ssl
from weboob.browser import LoginBrowser, URL, need_login
from weboob.exceptions import BrowserIncorrectPassword
from .pages import LoginPage, AccountsPage, TransactionsPage
__all__ = ['GanAssurances']
class GanAssurances(LoginBrowser):
login = URL('/wps/portal/login.*',
'/wps/portal/inscr... |
from openquake.hazardlib.gsim.chiou_youngs_2008 import ChiouYoungs2008
from openquake.hazardlib.tests.gsim.utils import BaseGSIMTestCase
class ChiouYoungs2008TestCase(BaseGSIMTestCase):
GSIM_CLASS = ChiouYoungs2008
# First five tests use data ported from Kenneth Campbell
# tables for verifying NGA models, a... |
from paste.deploy.converters import asbool
from pylons import tmpl_context as c
from pylons import request
from pylons.decorators import validate
from pylons.controllers.util import abort
from adhocracy.lib import helpers as h
from adhocracy.lib.base import BaseController
from adhocracy.lib.templating import render, re... |
import sys
sys.path.insert(0, "") # for running from cmake
import pytest
from conftest import set_property, raises, make_session
import elliptics
io_flags = set((elliptics.io_flags.default,
elliptics.io_flags.append,
elliptics.io_flags.prepare,
elliptics.io_flags.commit,... |
"""
Unit tests for the function
:func:`iris.analysis.cartography.gridcell_angles`.
"""
import iris.tests as tests # isort:skip
from cf_units import Unit
import numpy as np
from iris.analysis.cartography import gridcell_angles
from iris.coords import AuxCoord
from iris.cube import Cube
from iris.tests.stock import lat_... |
'''Complete the current word before the cursor with words in the editor.
Each menu selection or shortcut key selection replaces the word with a
different word with the same prefix. The search for matches begins
before the target and moves toward the top of the editor. It then starts
after the cursor and moves down. It ... |
import eventlet
from eventlet import event, hubs, queue
import tests
def do_bail(q):
eventlet.Timeout(0, RuntimeError())
try:
result = q.get()
return result
except RuntimeError:
return 'timed out'
class TestQueue(tests.LimitedTestCase):
def test_send_first(self):
q = even... |
"""Support for the Environment Canada radar imagery."""
import datetime
from env_canada import ECRadar # pylint: disable=import-error
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_LATITUDE,
CONF_LONGITUD... |
from kubernetes.client import CustomObjectsApi
from kubernetes.client import CoreV1Api
from kubernetes.client.rest import ApiException
from .common import random_str
import base64
group = 'management.cattle.io'
version = 'v3'
namespace = 'local'
plural = 'clusterloggings'
clusterId = "local"
globalNS = "cattle-global-d... |
import httplib2
from apiclient.discovery import build
import urllib
import json
import csv
import matplotlib.pyplot as plt
API_KEY = '... add your own ...'
TABLE_ID = '... add your own ...'
API_KEY = 'AIzaSyCpZ1iLD_Id7epHtnkEgAYTXsk2uBUtGkk'
TABLE_ID = '1ymz3EtGdi4qKGMl5AxEFXtTlgk3tKi8iCpjTzvM'
try:
fp = open("data... |
"""DataFrames for ingesting and preprocessing data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.learn.python.learn.dataframe.dataframe import DataFrame
from tensorflow.contrib.learn.python.learn.dataframe.series import Predefine... |
"""This code example gets all line item creative associations (LICA) for a given
line item id. The statement retrieves up to the maximum page size limit of 500.
To create LICAs, run create_licas.py."""
__author__ = 'api.shamjeff@gmail.com (Jeff Sham)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings, assume
import numpy as np
from caffe2.python import core, workspace
import caffe... |
input = """
1 2 2 1 3 4
1 3 2 1 2 4
1 4 0 0
1 5 2 1 6 7
1 6 2 1 5 7
1 7 0 0
1 8 2 1 9 10
1 9 2 1 8 10
1 10 0 0
1 11 2 1 12 13
1 12 2 1 11 13
1 13 0 0
1 14 1 0 2
1 15 1 0 5
1 16 1 0 8
1 17 1 0 11
1 18 1 0 2
1 19 1 0 5
1 20 1 0 2
1 21 1 0 5
1 22 1 0 8
1 23 1 0 11
1 21 2 1 19 20
1 24 1 1 18
1 23 1 0 8
1 25 1 1 18
1 26 1 0... |
from django.contrib.admin.filterspecs import FilterSpec
from django.contrib.admin.options import IncorrectLookupParameters
from django.contrib.admin.util import quote
from django.core.paginator import Paginator, InvalidPage
from django.db import models
from django.db.models.query import QuerySet
from django.utils.encod... |
"""Policy engine for Horizon"""
import logging
import os.path
from django.conf import settings
from openstack_auth import utils as auth_utils
from oslo.config import cfg
from openstack_dashboard.openstack.common import policy
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
_ENFORCER = None
_BASE_PATH = getattr(settin... |
'''
urlresolver XBMC Addon
Copyright (C) 2016 Gujal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is dist... |
import tensorflow as tf
def create_model_graph(height, width, channels, num_labels):
"""
"""
graph = tf.Graph()
with graph.as_default():
input_p = tf.placeholder(tf.float32, [None, height, width, channels],
name='input')
label_p = tf.placeholder(tf.int32,... |
import warnings
from tempfile import NamedTemporaryFile
from airflow.exceptions import AirflowException
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.amazon.aws.operators.s3_list import S3ListOperator
from airflow.providers.google.cloud.hooks.gcs import GCSHook, _parse_gcs_url
from air... |
from __future__ import with_statement
import unittest
import random
import os
import shutil
import IECore
import IECoreGL
IECoreGL.init( False )
class TestPointsPrimitive( unittest.TestCase ) :
outputFileName = os.path.dirname( __file__ ) + "/output/testPoints.exr"
def testStateComponentsInstantiation( self ):
IECo... |
"""Real and complex elements. """
from __future__ import print_function, division
from sympy.core.compatibility import string_types
from sympy.polys.domains.domainelement import DomainElement
from sympy.utilities import public
from mpmath.ctx_mp_python import PythonMPContext, _mpf, _mpc, _constant
from mpmath.libmp imp... |
import os
import IECore
import Gaffer
import GafferUI
import GafferSceneUI # for alembic previews
class browser( Gaffer.Application ) :
def __init__( self ) :
Gaffer.Application.__init__( self )
self.parameters().addParameters(
[
IECore.PathParameter(
"initialPath",
"The path to browse to initiall... |
import re
from datetime import date
from django.core.validators import URLValidator
from django.forms import ValidationError
from django.utils.translation import get_language
import jinja2
from jingo import register
from mozillians.users import get_languages_for_locale
PARAGRAPH_RE = re.compile(r'(?:\r\n|\r|\n){2,}')
@... |
from __future__ import absolute_import, division, print_function
import numpy as np
from ._base import Ordination, OrdinationResults
from ._utils import corr, svd_rank, scale
class CCA(Ordination):
r"""Compute constrained (also known as canonical) correspondence
analysis.
Canonical (or constrained) correspo... |
"""
The :mod:`sklearn.naive_bayes` module implements Naive Bayes algorithms. These
are supervised learning methods based on applying Bayes' theorem with strong
(naive) feature independence assumptions.
"""
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.sparse import issparse
from .base import Bas... |
"""Boto translation layer for resumable uploads.
See https://cloud.google.com/storage/docs/resumable-uploads-xml
for details.
Resumable uploads will retry interrupted uploads, resuming at the byte
count completed by the last upload attempt. If too many retries happen with
no progress (per configurable num_retries param... |
import argparse
import json
import os
import sys
import tracing_project
from hooks import install
from paste import httpserver
from paste import fileapp
import webapp2
from webapp2 import Route, RedirectHandler
def _RelPathToUnixPath(p):
return p.replace(os.sep, '/')
class TestListHandler(webapp2.RequestHandler):
d... |
"""Test of RPCs made against gRPC Python's application-layer API."""
import itertools
import threading
import unittest
import logging
from concurrent import futures
import grpc
from grpc.framework.foundation import logging_pool
from tests.unit import test_common
from tests.unit import thread_pool
from tests.unit.framew... |
import numpy as np
import pytest
import pandas as pd
from pandas import (
Categorical,
DataFrame,
Index,
MultiIndex,
Series,
Timestamp,
concat,
merge,
)
import pandas._testing as tm
from pandas.tests.reshape.merge.test_merge import (
NGROUPS,
N,
get_test_data,
)
a_ = np.array... |
from azure.cli.testsdk import ScenarioTest, JMESPathCheck, ResourceGroupPreparer
class DocumentDBTests(ScenarioTest):
@ResourceGroupPreparer()
def test_create_database_account(self, resource_group):
name = self.create_random_name(prefix='cli', length=40)
self.cmd(
'az cosmosdb create... |
class Solution:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
# write your code here
if s == '' and dict == {}:
return True
lendict, lenlist = {}, []
for word in dict:
l = len(word)
if l in l... |
import sys
import unittest
from ctypes import *
class MemFunctionsTest(unittest.TestCase):
def test_memmove(self):
# large buffers apparently increase the chance that the memory
# is allocated in high address space.
a = create_string_buffer(1000000)
p = "Hello, World"
result ... |
from Converter import Converter
from time import localtime, strftime
from Components.Element import cached
class ClockToText(Converter, object):
DEFAULT = 0
WITH_SECONDS = 1
IN_MINUTES = 2
DATE = 3
FORMAT = 4
AS_LENGTH = 5
TIMESTAMP = 6
FULL = 7
SHORT_DATE = 8
LONG_DATE = 9
VFD = 10
# add: date, date as str... |
"""WebTag Unit Tests"""
pass |
import os
import sys
import subprocess
def where(exeName, searchPath=os.getenv("PATH")):
paths = searchPath.split(";" if sys.platform == "win32" else ":")
for path in paths:
candidatePath = os.path.join(path, exeName)
if os.path.exists(candidatePath):
return candidatePath
return ... |
"""
Functional utilities designed for pychan use cases.
"""
import exceptions
def applyOnlySuitable(func,*args,**kwargs):
"""
This nifty little function takes another function and applies it to a dictionary of
keyword arguments. If the supplied function does not expect one or more of the
keyword arguments, these ar... |
from spack import *
class RLpsolve(RPackage):
"""Interface to 'Lp_solve' v. 5.5 to Solve Linear/Integer Programs
Lp_solve is freely available (under LGPL 2) software for solving linear,
integer and mixed integer programs. In this implementation we supply a
"wrapper" function in C and some R functions th... |
import os
import ctypes
import mxnet as mx
from mxnet.base import SymbolHandle, check_call, _LIB, mx_uint, c_str_array, c_str
from mxnet.symbol import Symbol
import numpy as np
from mxnet.test_utils import assert_almost_equal
def test_subgraph_exe():
def _check_subgraph_exe1(sym, op_names):
"""Use the parti... |
"""The tests for the notify.group platform."""
import unittest
from unittest.mock import MagicMock, patch
from homeassistant.setup import setup_component
import homeassistant.components.notify as notify
from homeassistant.components.notify import group, demo
from homeassistant.util.async_ import run_coroutine_threadsaf... |
"""A test library providing dialogs for interacting with users.
``Dialogs`` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.
Lo... |
from autobahn.asyncio.websocket import WebSocketServerProtocol, \
WebSocketServerFactory
import asyncio
import json
class SlowSquareServerProtocol(WebSocketServerProtocol):
@asyncio.coroutine
def slowsquare(self, x):
if x > 5:
raise Exception("number too large... |
"""
Base classes for working with xmlrpc APIs
"""
import sys
from libcloud.utils.py3 import xmlrpclib
from libcloud.utils.py3 import httplib
from libcloud.common.base import Response, Connection
class ProtocolError(Exception):
pass
class ErrorCodeMixin(object):
"""
This is a helper for API's that have a wel... |
"""Device entity for Zigbee Home Automation."""
import logging
import time
from homeassistant.core import callback
from homeassistant.util import slugify
from .entity import ZhaEntity
from .const import POWER_CONFIGURATION_CHANNEL, SIGNAL_STATE_ATTR
_LOGGER = logging.getLogger(__name__)
BATTERY_SIZES = {
0: 'No bat... |
import os;
import ldap;
from common import *
if(os.name == 'nt'):
HOST_NAME = 'GARY-2003'
HOST_PORT='389'
else:
HOST_NAME = 'gary-sles'
HOST_PORT = '11711'
DOMAIN_NAME = 'csp.com'
ADMIN_NAME = 'administrator'
ADMIN_PASSWORD = 'vmware'
reset_service()
vdc_promo(DOMAIN_NAME)
source_uri = 'ldap://%s:%s' % ... |
import logging
import sys
from bottle import request, run
sys.path.insert(0, '..')
from mongo_orchestration.apps import (error_wrap, get_json, Route,
send_result, setup_versioned_routes)
from mongo_orchestration.apps.links import (
sharded_cluster_link, all_sharded_cluster_link... |
import testtools
from tempest.api.object_storage import base
from tempest.common.utils import data_utils
from tempest import config
from tempest import test
CONF = config.CONF
class ContainerTest(base.BaseObjectTest):
@classmethod
def resource_setup(cls):
super(ContainerTest, cls).resource_setup()
... |
import os
assert('ENV_A' in os.environ)
assert('ENV_B' in os.environ)
assert('ENV_C' in os.environ)
print('ENV_A is', os.environ['ENV_A'])
print('ENV_B is', os.environ['ENV_B'])
print('ENV_C is', os.environ['ENV_C']) |
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... |
import datetime
import numbers
import re
import types
import semantic_version
import six
from glance.common.artifacts import declarative
import glance.common.exception as exc
from glance import i18n
_ = i18n._
class Text(declarative.PropertyDefinition):
"""A text metadata property of arbitrary length
Maps to TE... |
"""
Support for Google - Calendar Event Devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/google/
NOTE TO OTHER DEVELOPERS: IF YOU ADD MORE SCOPES TO THE OAUTH THAN JUST
CALENDAR THEN USERS WILL NEED TO DELETE THEIR TOKEN_FILE. THEY WILL LOSE THEIR
... |
"""
Dow-Jones Utilities Index, Aug.28--Dec.18, 1972.
Dataset described in [1]_ and included as a part of the ITSM2000 software [2]_.
Downloaded on April 22, 2019 from:
http://www.springer.com/cda/content/document/cda_downloaddocument/ITSM2000.zip
See also https://finance.yahoo.com/quote/%5EDJU/history?period1=83822400&... |
"""
test_cookiecutter_local_with_input
----------------------------------
Tests formerly known from a unittest residing in test_main.py named
TestCookiecutterLocalWithInput.test_cookiecutter_local_with_input
TestCookiecutterLocalWithInput.test_cookiecutter_input_extra_context
"""
import os
import pytest
from cookiecutt... |
"""Benchmarks of Lasso regularization path computation using Lars and CD
The input data is mostly low rank but is a fat infinite tail.
"""
import gc
from time import time
import sys
import numpy as np
from collections import defaultdict
from sklearn.linear_model import lars_path
from sklearn.linear_model import lasso_p... |
"""Zookeeper transport.
:copyright: (c) 2010 - 2013 by Mahendra M.
:license: BSD, see LICENSE for more details.
**Synopsis**
Connects to a zookeeper node as <server>:<port>/<vhost>
The <vhost> becomes the base for all the other znodes. So we can use
it like a vhost.
This uses the built-in kazoo recipe for queues
**Ref... |
"""
WSGI config for {{ project_name }} project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPL... |
from os import makedirs
from os.path import exists, join, basename
from shutil import copyfile, rmtree
from urllib.request import urlretrieve
from skbio import TreeNode, io
from biom import load_table, Table
from biom.cli.util import write_biom_table
import qiime2
from qiime2.plugins import feature_table, demux, dada2,... |
from __future__ import print_function, division
import copy
class QSR(object):
"""Data class structure that is holding the QSR and other related information."""
def __init__(self, timestamp, between, qsr, qsr_type=""):
"""Constructor.
:param timestamp: The timestamp of the QSR, which matches the... |
import io
import time
try:
memoryview
except (NameError, AttributeError):
# implementation does not matter as we do not really use it.
# it just must not inherit from something else we might care for.
class memoryview(object): # pylint: disable=redefined-builtin,invalid-name
pass
try:
unic... |
"""this file contains the version of jToolkit"""
ver = "0.7.8" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.