content stringlengths 4 20k |
|---|
import sys
import mock
import testtools
from sahara.tests.scenario import runner
class RunnerUnitTest(testtools.TestCase):
def _isDictContainSubset(self, sub_dictionary, dictionary):
for key in sub_dictionary:
if sub_dictionary[key] != dictionary[key]:
return False
r... |
'''serializer.py: common python serializer for heron'''
from abc import abstractmethod
try:
import cPickle as pickle
except:
import pickle
import heronpy.api.cloudpickle as cloudpickle
class IHeronSerializer(object):
"""Serializer interface for Heron"""
@abstractmethod
def initialize(self, config):
"""... |
r"""Integration of records and files for Invenio.
Invenio-Records-Files provides basic API for integrating
`Invenio-Records <https://invenio-records.rtfd.io/>`_
and `Invenio-Files-REST <https://invenio-files-rest.rtfd.io/>`_.
Initialization
--------------
First create a Flask application:
>>> from flask import Flask... |
"""SPCM."""
# --- import --------------------------------------------------------------------------------------
import os
import pathlib
import collections
import time
import numpy as np
from ._data import Data
from .. import exceptions as wt_exceptions
from ..kit import _timestamp as timestamp
# --- define ---... |
import qctests.EN_spike_and_step_check
import util.testingProfile
import numpy
import util.main as main
##### EN_spike_and_step_check ----------------------------------------------
class TestClass:
parameters = {
'db': 'iquod.db',
"table": 'unit'
}
def setUp(self):
# this qc test... |
import unittest
import requests
import requests_mock
from airflow.models.dag import DAG
from airflow.providers.apache.druid.transfers.hive_to_druid import HiveToDruidOperator
class TestDruidHook(unittest.TestCase):
# To debug the large json diff
maxDiff = None
hook_config = {
'sql': 'SELECT * ... |
from nose.tools import *
import numpy as np
import causalinference.core.data as d
import causalinference.core.propensity as p
from utils import random_data
def test_get_excluded_lin():
K1 = 4
included1 = []
ans1 = [0, 1, 2, 3]
assert_equal(p.get_excluded_lin(K1, included1), ans1)
K2 = 4
included2 = [3, 1]
a... |
"""
Tests for L{pyflakes.scripts.pyflakes}.
"""
import sys
from StringIO import StringIO
from twisted.python.filepath import FilePath
from twisted.trial.unittest import TestCase
from pyflakes.scripts.pyflakes import checkPath
def withStderrTo(stderr, f):
"""
Call C{f} with C{sys.stderr} redirected to C{stde... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
h... |
#!/home/obiike_nwoke/supysonic/venv/bin/python2
#
# The Python Imaging Library
# $Id$
#
# this demo script illustrates how a 1-bit BitmapImage can be used
# as a dynamically updated overlay
#
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
... |
"""SOCKS unit tests."""
from twisted.trial import unittest
from twisted.test import proto_helpers
import struct, socket
from twisted.internet import defer, address
from twisted.protocols import socks
class StringTCPTransport(proto_helpers.StringTransport):
stringTCPTransport_closing = False
peer = None
d... |
from sqlalchemy import Column, Integer, Float, MetaData, Table
meta = MetaData()
def _get_table(table_name):
return Table(table_name, meta, autoload=True)
rxtx_base = Column('rxtx_base', Integer)
rxtx_factor = Column('rxtx_factor', Float, default=1)
rxtx_quota = Column('rxtx_quota', Integer)
rxtx_cap = Column('... |
"""Append module search paths for third-party packages to sys.path.
****************************************************************
* This module is automatically imported during initialization. *
****************************************************************
In earlier versions of Python (up to 1.5a3), scri... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
class SessionManager(models.Manager):
def encode(self, session_dict):
"""
Returns the given session dictionary serialized and encoded as a string.
"""
return SessionStore().encode(session_dict)
... |
"""
Base classes for test cases
Tests will usually inherit from one of these classes to have the controller
and/or dataplane automatically set up.
"""
import importlib
import os
import logging
import unittest
import oftest
from oftest import config
import oftest.dataplane as dataplane
import oftest.base_tests as bas... |
"""
Test CuisinePEP8 module
"""
import unittest
from unittest.mock import patch
from JumpScale import j
class GitClientStub:
def __init__(self, baseDir):
self.baseDir = baseDir
@patch('JumpScale.j.tools.cuisine.local.development.pip')
@patch('JumpScale.j.clients.git')
class TestCuisineCore(unittest.Te... |
import jwt
from urlparse import urljoin
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def validate_modules():
"""
Validate that the modules that have been set up correctly.
"""
try:
jwt.rsa_load
except AttributeError:
raise ImproperlyConf... |
from pylab import *
import matplotlib.cm as cm
import numpy as np
import scipy.linalg as la
from scipy.stats import chi2
from scipy.spatial import Voronoi, voronoi_plot_2d
from sklearn.datasets import make_blobs
def plot_2d_clusters(X, labels, centers):
"""
Given an observation array, a label vector, and the ... |
# multiAgents.py
# --------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (<EMAIL>) and Dan Klein (<EMAIL>).
# For ... |
"""Ensure the files have been migrated to tape."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import datetime
from pprint import pformat
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities.ReturnValues import returnSingleResult
from DIRAC.Request... |
from unittest import mock
from django.test import RequestFactory, TestCase
from django.contrib.auth.models import User
from ..models import PublicKey, JWKSEndpointTrust
from ..middleware import JWTAuthMiddleware
from ..tokens import Token
from ..keys import RSAPrivateKey, Ed25519PrivateKey
class BaseMiddlewareTest(Te... |
"""BibFormat element - Prints journal data from an Authority Record.
"""
import re
__revision__ = "$Id$"
def format_element(bfo, detail='no'):
""" Prints the data of a journal authority record in HTML. By default prints
brief version.
@param detail: whether the 'detailed' rather than the 'brief' format
... |
"""mqtt line tests
"""
import logging
import asyncio
import pytest
import hbmqtt
import hbmqtt.broker
from hbmqtt.mqtt.constants import QOS_1
import hbmqtt.client
import pynais as ns
from . import cancel_tasks
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger()
CONFIG = {
'listeners': {
'de... |
#! /usr/bin/env python
from openturns import *
from math import *
TESTPREAMBLE()
try :
# Create an intance
inputVars = Description(["t"])
formula = Description(["sin(t)", "cos(t)"])
myFunc = NumericalMathFunction(inputVars, formula)
myTrendFunc = TrendTransform(myFunc)
print "myTrendFunc=", ... |
# -*- coding: utf-8 -*-
"""Unit tests for Gram-Charlier exansion
No reference results, test based on consistency and normal case.
Created on Wed Feb 19 12:39:49 2014
Author: Josef Perktold
"""
import numpy as np
from scipy import stats
from numpy.testing import assert_allclose, assert_array_less
from statsmodels.... |
import cv2
from PIL import Image, ImageTk
import numpy
from Queue import Queue, Empty
import time
import Tkinter as tk
from Threads import VideoThread
from TelemetryWidget import TelemetryWidget
from ControlWidget import ControlWidget
from img_proc.misc import *
from img_proc.GlobalSurveyor import *
import tkMessageB... |
import os
import re
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from argparse import ArgumentParser
from collections import defaultdict
def _parse(file_path, pattern_iter, pattern_loss, pattern_accuracy):
with open(file_path, 'r') as f:
log = f.read()
iter_list = map(in... |
from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='DarkLan... |
import random
from cmath import exp, pi, log
from gnuradio import gr, gr_unittest
from utils import mod_codes
import digital_swig as digital
import blocks_swig as blocks
# import from local folder
import psk
import qam
import qamlike
tested_mod_codes = (mod_codes.NO_CODE, mod_codes.GRAY_CODE)
# A list of the conste... |
from oslo_config import cfg
from oslo_log import log as logging
# Import extensions to pull in osapi_compute_extension CONF option used below.
from nova.tests.functional import integrated_helpers
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class ExtensionsTest(integrated_helpers._IntegratedTestBase):
_api... |
import json
from js2py.base import Js
indent = ''
# python 3 support
import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
def parse(text):
reviver = arguments[1]
s = text.to_string().value
try:
unfiltered = json.loads(s)
except:
raise this.Mak... |
# -*- coding: utf-8 -*-
"""
UV Light Plugin
Copyright (C) 2015 Olaf Lüke <<EMAIL>>
uv_light.py: UV Light Bricklet Plugin Implementation
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... |
from __future__ import absolute_import
from celery.app.registry import _unpickle_task, _unpickle_task_v2
from celery.tests.case import AppCase, depends_on_current_app
def returns():
return 1
class test_unpickle_task(AppCase):
@depends_on_current_app
def test_unpickle_v1(self):
self.app.tasks['... |
"""
Serializer fields that deal with relationships among entities
(e.g. resources, sub-resources, resource versions) in the OCL Object Model.
"""
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.relations import HyperlinkedIdentityField, HyperlinkedRelatedField
class HyperlinkedRelatedField(H... |
__author__ = "David Rusk <<EMAIL>>"
# Modified from http://flask.pocoo.org/docs/patterns/fabric/
from fabric.api import *
# the user to use for the remote commands
env.user = "drusk"
# the servers where the commands are executed
env.hosts = ["rusk.dlinkddns.com"]
def package():
# create a new source distribu... |
"""
Module for event listener matchers used in testing
"""
from pyherc.events import e_event_type
from hamcrest.core.base_matcher import BaseMatcher
class EventRedraws(BaseMatcher):
"""
Class for checking redraws in event
"""
def __init__(self, redraws):
"""
Default constructor
... |
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
from nova import utils
KEYPAIR_TYPE_SSH = 'ssh'
KEYPAIR_TYPE_X509 = 'x509'
# TODO(berrange): Remove NovaObjectDictCompat
@base.NovaObjectRegistry.register
class KeyPair(base.NovaPersi... |
"""
A SOAP implementation for wsme.
Parts of the code were taken from the tgwebservices soap implmentation.
"""
from __future__ import absolute_import
import pkg_resources
import datetime
import decimal
import base64
import logging
import six
from wsmeext.soap.simplegeneric import generic
from wsmeext.soap.wsdl impo... |
"""Undocumented Module"""
__all__ = ['Diff', 'ObjectPool']
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.PythonUtil import invertDictLossless, makeList, safeRepr
from direct.showbase.PythonUtil import getNumberedTypedString, getNumberedTypedSortedString
from direct.showbase.Pyth... |
import requests
import sys
import yaml
try:
import simplejson as json
except ImportError:
import json
from invtool.dispatch import Dispatch
from invtool.lib.registrar import registrar
from invtool.lib.config import REMOTE, auth
class ServiceDispatch(Dispatch):
def route(self, nas):
return getatt... |
from coalib.core.Bear import Bear
from coalib.settings.FunctionMetadata import FunctionMetadata
class ProjectBear(Bear):
"""
This bear base class does not parallelize tasks at all, it runs on the
whole file base provided.
"""
def __init__(self, section, file_dict):
"""
:param sect... |
from odoo import SUPERUSER_ID
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
class wiz_mass_sale_order(models.TransientModel):
_name = 'wiz.mass.sale.order'
@api.multi
def mass_sale_order_email_send(self):
context = self._context
active_... |
import config
from system.shared import mkdir_p
import logging
from logging.handlers import RotatingFileHandler
import os
import sys
def init_logger(mainLoggerName = __name__):
logger = logging.getLogger(mainLoggerName)
logsDirPath = os.path.dirname(config.LOG_FILE_PATH)
if not os.path.exists(logsDirPat... |
#!/usr/bin/env python
import pytest
from translate.misc import multistring, test_autoencode
class TestMultistring(test_autoencode.TestAutoencode):
type2test = multistring.multistring
def test_constructor(self):
t = self.type2test
s1 = t("test")
assert type(s1) == t
assert s1... |
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from rest_framework.serializers import HyperlinkedModelSerializer
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_gis.serializers import GeoFeatureModelSerializer
from django.core.exceptions impo... |
#
# C naming conventions
#
#
# Prefixes for generating C names.
# Collected here to facilitate ensuring uniqueness.
#
pyrex_prefix = "__pyx_"
codewriter_temp_prefix = pyrex_prefix + "t_"
temp_prefix = u"__cyt_"
builtin_prefix = pyrex_prefix + "builtin_"
arg_prefix = pyrex_prefix + "arg_"
f... |
"""This code example gets a forecast for a prospective line item. To determine
which orders exist, run get_all_orders.py. To determine which placements exist,
run get_all_placements.py."""
__author__ = '<EMAIL> (Jeff Sham)'
# Locate the client library. If module was installed via "setup.py" script, then
# the followi... |
__doc__="""CiscoPowerSupply
CiscoPowerSupply is an abstraction of a PowerSupply.
$Id: CiscoPowerSupply.py,v 1.0 2010/12/13 20:02:33 egor Exp $"""
__version__ = "$Revision: 1.0 $"[11:-2]
from Globals import InitializeClass
from Products.ZenModel.PowerSupply import PowerSupply
class CiscoPowerSupply(PowerSupply):
... |
#!/usr/bin/env python
import unittest
from test import test_support
from test.test_urllib2 import sanepathname2url
import socket
import urllib2
import os
import sys
TIMEOUT = 60 # seconds
def _retry_thrice(func, exc, *args, **kwargs):
for i in range(3):
try:
return func(*args, **kwargs)
... |
# -*- coding: utf-8 -*-
from .op import Op
from .db import Analysis
from . import util
_UNKNOWN = Analysis.UNKNOWN
_CODE = Analysis.CODE
_NOTCODE = Analysis.NOTCODE
def _not_executable(db, perms, addr):
return db.is_notcode(addr) or not perms[addr].executable
def _access_illegal(db, perms, addr, op):
... |
import os
import pandas as pd
import subprocess
from collections import Counter
import numpy as np
import math
import pysam
import pybedtools
from bcbio.utils import file_exists, tmpfile, chdir, splitext_plus
from bcbio.provenance import do
from bcbio.distributed.transaction import file_transaction
from bcbio.log imp... |
"""Support for International Space Station data sensor."""
from datetime import timedelta
import logging
import pyiss
import requests
import voluptuous as vol
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import (
ATTR_LATITUDE,
ATTR_LONGITUDE,... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
from ansible.module_utils.network.ios.ios import run_commands
from ansible.module_utils.network.ios.ios import ios_argument_spec, check_args
from ansible.module_utils.net... |
from decouple import config
TAAR_ENSEMBLE_BUCKET = config("TAAR_ENSEMBLE_BUCKET", default="test_ensemble_bucket")
TAAR_ENSEMBLE_KEY = config("TAAR_ENSEMBLE_KEY", default="test_ensemble_key")
TAAR_WHITELIST_BUCKET = config("TAAR_WHITELIST_BUCKET", default="test_whitelist_bucket")
TAAR_WHITELIST_KEY = config("TAAR_WHIT... |
from toolset.utils.output_helper import log, FNULL
from toolset.utils.docker_helper import DockerHelper
from toolset.utils.time_logger import TimeLogger
from toolset.utils.metadata import Metadata
from toolset.utils.results import Results
from toolset.utils.audit import Audit
import os
import subprocess
import traceba... |
#!/usr/bin/env python
# APM automatic test suite
# Andrew Tridgell, October 2011
import pexpect, os, sys, shutil, atexit
import optparse, fnmatch, time, glob, traceback, signal
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'pysim'))
import util
os.environ['PYTHONUNBUFFERED'] = '1'
os... |
import dht
from machine import Pin
from lib.Unit import TemperatureUnit, HumidityUnit
from lib.toolkit import log, convert_C_to_F
class DHTType:
DHT11 = 0
DHT22 = 1
def __init__(self):
pass
class DHT:
type = ""
sensor = ""
# @timed_function
def __init__(self, type, pin):
... |
""" Module that provides the Signal class and related objects.
This module provides the following objects:
Signal -- class to model hardware signals
posedge -- callable to model a rising edge on a signal in a yield statement
negedge -- callable to model a falling edge on a signal in a yield statement
"""
from __futu... |
#!python
'''Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptool... |
import numpy as np
from .normals import normals
def surface(func, umin=0, umax=2 * np.pi, ucount=64, urepeat=1.0,
vmin=0, vmax=2 * np.pi, vcount=64, vrepeat=1.0):
"""
Computes the parameterization of a parametric surface
func: function(u,v)
Parametric function used to build the surfac... |
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.dns.drivers.luadns import LuadnsDNSDriver
from libcloud.test import MockHttp
from libcloud.test.file_fixtures import DNSFileFixtures
from libcloud.test.secrets import DNS_PARAMS_LUADNS
from libcloud.dns.types import ZoneDoesNotExistError, ... |
import datetime
import itertools
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from model.queues import Queue
from model import queuestatus
class QueueStatus(webapp.RequestHandler):
def _rows_for_work_items(self, queue):
queued_items = queue.work_items()
... |
import config
import comm
import os
import subprocess
def get_filename(url):
return ''.join((
'.'.join(url.split('.')[:-1]).split('/')[-1],
'.flv',
))
def rtmpdump(rtmp_url, rtmp_host, rtmp_app, rtmp_playpath, output_filename, resume=False, execvp=False):
executables = (
'rtmpdump',
'rtmpdump_x86',
'f... |
"""This is a helper module to get and manipulate histogram data.
The histogram data is the same data as is visible from "chrome://histograms".
More information can be found at: chromium/src/base/metrics/histogram.h
"""
import collections
import json
import logging
BROWSER_HISTOGRAM = 'browser_histogram'
RENDERER_HIS... |
from flask import g, render_template, flash
from talkatv.decorators import require_active_login
from talkatv.site.forms import SiteForm
from talkatv.models import Site, Item
from talkatv import app, db
@app.route('/site/add', methods=['GET', 'POST'])
@require_active_login()
def add_site():
form = SiteForm()
... |
from .sub_resource import SubResource
class ApplicationGatewayIPConfiguration(SubResource):
"""IP configuration of an application gateway. Currently 1 public and 1
private IP configuration is allowed.
:param id: Resource ID.
:type id: str
:param subnet: Reference of the subnet resource. A subnet ... |
import xmlrpclib
import socket
import time
import sys
try:
from xml.parsers.expat import ExpatError
except ImportError: # No expat in IronPython 2.7
class ExpatError(Exception): pass
from robot import utils
from robot.errors import RemoteError
class Remote:
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def _... |
"""Objects for holding data values which can be expanded in templates.
This module contains the base classes for objects which can hold data values
(scaler constants, arrays, ...) that might be expanded in a template. It is
primarily used for CSP.
"""
from googleapis.codegen import template_objects
class DataValue(... |
from neutronclient.common import exceptions
from neutronclient.v2_0 import client as clientv20
from oslo.config import cfg
from nova.openstack.common import lockutils
from nova.openstack.common import log as logging
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class AdminTokenStore(object):
_instance = No... |
import pytest
from cnfgen.graphs import CompleteBipartiteGraph
from cnfgen.graphs import BipartiteGraph
def test_build_bipartite():
G = BipartiteGraph(3, 4)
assert len(G) == 7
assert G.left_order() == 3
assert G.right_order() == 4
assert not G.has_edge(2, 1)
G.add_edge(1, 2)
G.add_edge(3,... |
from pythonforandroid.toolchain import Recipe, shprint
from os.path import join
import sh
class Hostpython3CrystaXRecipe(Recipe):
version = 'auto' # the version is taken from the python3crystax recipe
name = 'hostpython3crystax'
conflicts = ['hostpython2']
def get_build_container_dir(self, arch=Non... |
"""
A simple program that parses untranslated.ts files
current directory *must* be the top level qtcreator source directory
Usage:
scripts/uichanges.py old_untranslated.ts qtcreator_untranslated.ts
IN TOP LEVEL QTC SOURCE DIRECTORY!
"""
import os, sys, string
import subprocess
from xml.sax import saxutils,... |
"""
.. module:: tomo_recon
:platform: Unix
:synopsis: runner for tests using the MPI framework
.. moduleauthor:: Mark Basham <<EMAIL>>
"""
import unittest
from savu.test import test_utils as tu
from savu.test.travis.framework_tests.plugin_runner_test import \
run_protected_plugin_runner
class SimpleFitRe... |
from twisted.trial import unittest
from twisted.python import components
from twisted.pair import ethernet, raw
from zope.interface import implements
class MyProtocol:
implements(raw.IRawPacketProtocol)
def __init__(self, expecting):
self.expecting = list(expecting)
def datagramReceived(self, d... |
from django.contrib.auth.models import User
from rest_framework import serializers
from booktype.apps.account import utils as account_utils
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
class UserSerializer(serializers.HyperlinkedModelSerializer):
... |
import six
from six import iteritems
from six.moves import http_client
from st2api.controllers import resource
from st2common import log as logging
from st2common.constants.triggers import TIMER_TRIGGER_TYPES
from st2common.models.api.trigger import TriggerAPI
from st2common.models.system.common import ResourceReferen... |
# -*- coding: utf-8 -*-
"""
Metrics
=======
Defines various metrics:
- :func:`colour.utilities.metric_mse`
- :func:`colour.utilities.metric_psnr`
References
----------
- :cite:`Wikipedia2003c` : Wikipedia. (2003). Mean squared error. Retrieved
March 5, 2018, from https://en.wikipedia.org/wiki/Mean_squared_... |
{
'name': 'Lot Filtering in Stock Transfer',
'version': '0.9',
'author': 'Rooms For (Hong Kong) Ltd T/A OSCG',
'website': 'http://www.openerp-asia.net',
'category': 'Stock',
'depends': [
"stock",
],
'description': """
* Adds a new function field 'lot_balance' to stock.production.... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class AddList(Choreography):
def __init__(self, temboo_session):
"""
Create a new i... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
import os
import json
import vcr
import pytest
import cfn_resource
class FakeLambdaContext(object):
def __init__(self, name='Fake', version='LATEST'):
self.name = name
self.version = version
@property
def get_remaining_time_in_millis(self):
return 10000
@property
def fun... |
import HTMLParser
import json
import logging
import urllib2
import urlparse
class _HRefParser(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.hrefs = []
def handle_starttag(self, tag, attrs):
if tag == "a":
for name, value in attrs:
if name == "hre... |
'''tzinfo timezone information for Europe/Uzhgorod.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Uzhgorod(DstTzInfo):
'''Europe/Uzhgorod timezone definition. See datetime.tzinfo for details'''
zone = 'Europe/Uzhgorod'
... |
import unittest
import sys
import os
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
GHC_DIR = TEST_DIR[:-5] + 'GeoHealthCheck'
# Needed to find classes and plugins
sys.path.append(GHC_DIR)
# Shorthand to run all test scripts in tests dir.
# TODO use nose or more intelligent test_*.py discovery
if __name__ == ... |
__author__ = 'Brandyn A. White <<EMAIL>>'
__license__ = 'GPL V3'
import unittest
import hadoopy
class Mapper(object):
"""Emit each term with a count of 1.
Args:
key: unused
value: term
Yields:
A tuple in the form of (key, value)
key: term as string
value: count a... |
from nova.cells import utils as cells_utils
from nova import compute
from nova.compute import rpcapi as compute_rpcapi
from nova import context
from nova.openstack.common import rpc
from nova import test
class ComputeHostAPITestCase(test.TestCase):
def setUp(self):
super(ComputeHostAPITestCase, self).setU... |
"""Tests for certificate Django models. """
import ddt
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.test.utils import override_settings
from nose.plugins.attrib import attr
i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import sys
from modules.Datastore import ModuleIoBucket
import modules.bitstamp.client as bsclient
__author__ = 'Giannis Dzegoutanis'
## PychoHistory Module ########
module_name = u'StampThatBit'
module_features = (u'timestamp', u'volume'... |
"""Increase text size for MySQL (not relevant for other DBs' text types)
Revision ID: d2ae31099d61
Revises: 947454bf1dff
Create Date: 2017-08-18 17:07:16.686130
"""
# revision identifiers, used by Alembic.
revision = 'd2ae31099d61'
down_revision = '947454bf1dff'
branch_labels = None
depends_on = None
from alembic i... |
#!/usr/bin/env python
import sys
import numpy as np
#from sklearn import linear_model # LogisticRegression
from sklearn import svm
from multiprocessing import Pool
from scipy import interp
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import StratifiedKFold
from sklearn import preprocessing... |
import sys, random, locale
from formathelper import locale_list, printit
from formathelper import integers, numbers, randfill
from formathelper import all_fillchars, all_format_sep, all_format_loc
from randdec import randdec, randint, un_incr_digits
testno = 0
print("rounding: half_even")
# unicode fill character te... |
from dataclasses import dataclass
from typing import Sequence, Any
djongo_access_url = 'https://nesdis.github.io/djongo/support/'
_printed_features = set()
@dataclass(repr=False)
class SQLDecodeError(ValueError):
err_key: Any = None
err_sub_sql: Any = None
err_sql: Any = None
params: Sequence = None
... |
import asyncio
import json
import aiopg
from .connection import SAConnection
from .exc import InvalidRequestError
from aiopg.connection import TIMEOUT
try:
from sqlalchemy.dialects.postgresql.psycopg2 import PGDialect_psycopg2
except ImportError: # pragma: no cover
raise ImportError('aiopg.sa requires sqlal... |
import os, json, logging, pickle
import numpy as np
from collections import defaultdict
from copy import deepcopy
from mapserver.graph.contractor2 import GraphContractor
from mapserver.routing.router2 import Router
from networkx.readwrite import json_graph as imports
from mapserver.graph.update import GraphUpdate
from... |
from PySide.QtCore import *
from PySide.QtGui import *
import findWidget_UIs as ui
class findWidgetClass(QWidget, ui.Ui_findReplace):
searchSignal = Signal(str)
replaceSignal = Signal(list)
replaceAllSignal = Signal(list)
def __init__(self, parent):
super(findWidgetClass, self).__init__(parent)... |
'''
http://stackoverflow.com/questions/4702518/how-to-access-members-of-an-rdf-list-with-rdflib-or-plain-sparql
'''
import rdflib
import json
import os
import csv, codecs, cStringIO
class UtilSyntax:
@staticmethod
def convert(input):
if isinstance(input, dict):
return {UtilSyntax.convert(key): UtilSyntax.conve... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
from earo.event import Event, Field
import unittest
class TestEvent(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_field(self):
class AEvent(Event):
str_field = Field(str, 'test')
boo... |
#
# Run Control
#
# Code basis taken from xdress' run control in xdress/utils.py.
#
import os
import io
class NotSpecified(object):
"""A helper class singleton for run control meaning that a 'real' value
has not been given."""
def __repr__(self):
return "NotSpecified"
NotSpecified = NotSpecifie... |
from Analyser_Merge import Analyser_Merge, Source, Load, Mapping, Select, Generate
class Analyser_Merge_Tourism_FR_Gironde_Caravan(Analyser_Merge):
def __init__(self, config, logger = None):
self.missing_official = {"item":"8140", "class": 1, "level": 3, "tag": ["merge", "tourism"], "desc": T_(u"Gironde c... |
"""
Tests for Discussion API pagination support
"""
from unittest import TestCase
from django.test import RequestFactory
from lms.djangoapps.discussion.rest_api.pagination import DiscussionAPIPagination
from lms.djangoapps.discussion.rest_api.tests.utils import make_paginated_api_response
class PaginationSerializ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.