content stringlengths 4 20k |
|---|
__author__ = 'gauravhirlekar'
def init_feature():
detector = cv2.SURF(500) # 500 is the threshold Hessian value for the detector.
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=100) # Or pass empty dictionary
matcher = cv2.Flann... |
'''
This is the main program of openvim, it reads the configuration
and launches the rest of threads: http clients, openflow controller
and host controllers
'''
__author__="Alfonso Tierno"
__date__ ="$10-jul-2014 12:07:15$"
__version__="0.4.5-r465"
version_date="Feb 2016"
database_version="0.7" #expected datab... |
"""
Various utility functions
"""
from __future__ import print_function
import traceback
import struct
import sys
import os
import time
import socket
import collections
#FIXME: ugh, why can't I make importing pox.core work here?
import logging
log = logging.getLogger("util")
class DirtyList (list):
#TODO: right... |
import os
import subprocess
import tempfile
from mozprocess import ProcessHandler
from .base import Browser, require_arg, get_free_port, browser_command, ExecutorBrowser
from ..executors import executor_kwargs as base_executor_kwargs
from ..executors.executorservodriver import (ServoWebDriverTestharnessExecutor,
... |
"""
homeassistant.components.device_tracker.tomato
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a Tomato router for device
presence.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.tomato/
""... |
import logging
import os
from six.moves import configparser
import monasca_setup.agent_config
import monasca_setup.detection
from monasca_setup.detection.utils import find_process_name
log = logging.getLogger(__name__)
mysql_conf = '/root/.my.cnf'
HOST = 'localhost'
PORT = 3306
SOCKET = '/var/run/mysqld/mysqld.sock'... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: win_copy
version_added: '1.9.2'
short_description: Copies files to remote locations on windows hosts
description:
- The C(win_copy) module copie... |
m5.util.addToPath('../configs/common')
from cpu2000 import parser
workload = parser(isa, opsys, 'mdred')
root.system.cpu[0].workload = workload.makeLiveProcess() |
from __future__ import unicode_literals
from django.http import HttpRequest
# In a separate file to avoid circular imports...
class Bundle(object):
"""
A small container for instances and converted data for the
``dehydrate/hydrate`` cycle.
Necessary because the ``dehydrate/hydrate`` cycle needs to ac... |
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
UserModel = get_user_model()
class ModelBackend(object):
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, request, username=None, pa... |
"""Visitor/traversal interface and library functions.
SQLAlchemy schema and expression constructs rely on a Python-centric
version of the classic "visitor" pattern as the primary way in which
they apply functionality. The most common use of this pattern
is statement compilation, where individual expression classes ma... |
__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer',
'RepresenterError']
from error import *
from nodes import *
import datetime
import sys, copy_reg, types
class RepresenterError(YAMLError):
pass
class BaseRepresenter(object):
yaml_representers = {}
yaml_multi_representers = {}
de... |
"""User input parameter validation.
This module handles user input parameter validation
against a provided input model.
Note that the objects in this module do *not* mutate any
arguments. No type version happens here. It is up to another
layer to properly convert arguments to any required types.
Validation Errors
... |
if __name__ == '__main__':
import sys
import os
pkg_dir = (os.path.split(
os.path.split(
os.path.split(
os.path.abspath(__file__))[0])[0])[0])
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
... |
"""
Management utility to create superusers.
"""
from __future__ import unicode_literals
import getpass
import sys
from django.contrib.auth import get_user_model
from django.contrib.auth.management import get_default_username
from django.contrib.auth.password_validation import validate_password
from django.core impor... |
from __future__ import division, print_function, absolute_import
from os import path
from warnings import catch_warnings
DATA_PATH = path.join(path.dirname(__file__), 'data')
import numpy as np
from numpy.testing import (assert_equal, assert_array_equal, run_module_suite,
assert_)
from scipy.io.idl import reads... |
# Tests invocation of the interpreter with various command line arguments
# All tests are executed with environment variables ignored
# See test_cmd_line_script.py for testing of script execution
import test.test_support, unittest
import sys
from test.script_helper import spawn_python, kill_python, python_exit_code
... |
import json
from urllib import urlopen
import requests
import getpass
from string import Template
import sys
import os
import subprocess
class RunError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def run(command, **kwargs):
fail_hard... |
import sys
from subprocess import Popen, PIPE
import unittest
from scrapy.utils.test import get_testenv
class CmdlineTest(unittest.TestCase):
def setUp(self):
self.env = get_testenv()
self.env['SCRAPY_SETTINGS_MODULE'] = 'tests.test_cmdline.settings'
def _execute(self, *new_args, **kwargs):
... |
import logging
import sys
from webkitpy.common.checkout.changelog import ChangeLog
from webkitpy.tool.steps.abstractstep import AbstractStep
from webkitpy.tool.steps.options import Options
_log = logging.getLogger(__name__)
# FIXME: Some of this logic should probably be unified with CommitterValidator?
class Valida... |
import pytest
from awx.api.versioning import reverse
@pytest.fixture
def organization_resource_creator(organization, user):
def rf(users, admins, job_templates, projects, inventories, teams):
# Associate one resource of every type with the organization
for i in range(users):
member_u... |
#!/usr/bin/env python3
from collections import OrderedDict
import pkg_resources
from plover.registry import Registry
def sorted_requirements(requirements):
return sorted(requirements, key=lambda r: str(r).lower())
# Find all available distributions.
all_requirements = [
dist.as_requirement()
for dist... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
parse_duration,
parse_iso8601,
)
class MLBIE(InfoExtractor):
_VALID_URL = r'''(?x)
https?://
(?:[\da-z_-]+\.)*mlb\.com/
(?:
... |
"""Scrapers for the decimequiensosvos backend."""
import datetime
import sys
from collections import namedtuple
from yaswfp import swfparser
Episode = namedtuple("Episode", "name occup bio image date")
class _ConstantPoolExtractor(object):
"""Get items from the constant pool."""
def __init__(self, constan... |
"""If you have Ned Batchelder's coverage_ module installed, you may activate a
coverage report with the ``--with-coverage`` switch or NOSE_WITH_COVERAGE
environment variable. The coverage report will cover any python source module
imported after the start of the test run, excluding modules that match
testMatch. If you ... |
import time
from openerp.osv import fields,osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
class delivery_carrier(osv.osv):
_name = "delivery.carrier"
_description = "Carrier"
def name_get(self, cr, uid, ids, context=None):
if not len(ids):
retur... |
import sys
import logging
from django.conf import settings
# Create a dummy handler to use for now.
class NullHandler(logging.Handler):
def emit(self, record):
pass
def get_logger():
"Attach a file handler to the logger if there isn't one already."
debug_on = getattr(settings, "SOUTH_LOGGING_ON", ... |
from sympy import diff, Integral, Limit, sin, Symbol, Integer, Rational, cos, \
tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, E, I, oo, \
pi, GoldenRatio, EulerGamma, Sum, Eq, Ne, Ge, Lt, Float, Matrix
from sympy.printing.mathml import mathml, MathMLPrinter
from sympy.utilities.pytest import ra... |
"""
Harvester for the OpenSIUC API at Southern Illinois University for the SHARE project
More information available here:
https://github.com/CenterForOpenScience/SHARE/blob/master/providers/edu.siu.opensiuc.md
An example API call: http://opensiuc.lib.siu.edu/do/oai/?verb=ListRecords&metadataPrefix=oai_dc&from=2014-10... |
from __future__ import print_function
import os
import sys
import json
import urllib2
import functools
import subprocess
from sparktestsupport import SPARK_HOME, ERROR_CODES
from sparktestsupport.shellutils import run_cmd
def print_err(msg):
"""
Given a set of arguments, will print them to the STDERR stream
... |
#!/usr/bin/python
import os
#import stat
import sys
import re
import random
from optparse import OptionParser
from stat import *
#create all file list (used for path.walk
def proceed_create_file_list(filelist, directory, files):
for file in files:
filelist += [os.path.join(directory,file)]
filelist.so... |
"""
This module is indended to provide a pluggable way to add assertions about
the rendered content of XBlocks.
For each view on the XBlock, this module defines a @singledispatch function
that can be used to test the contents of the rendered html.
The functions are of the form:
@singledispatch
def assert_stu... |
"""AuthZ Adapter implementations of authentication.process managers."""
# pylint: disable=no-init
# Numerous classes don't require __init__.
# pylint: disable=too-many-public-methods
# Number of methods are defined in specification
# pylint: disable=too-many-ancestors
# Inheritance defined in specification
... |
from __future__ import absolute_import
from __future__ import print_function
import glob
import os
import shutil
import sys
from twisted.internet import defer
from twisted.internet import threads
from twisted.python import log
from twisted.python import runtime
from buildbot_worker import runprocess
from buildbot_wo... |
# keyboardAgents.py
# -----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berk... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for core additions
.. note:: 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 2 of the License, or
(at your option) any later version.
"""
__a... |
import os
import time
import tempfile
__doc__ = """ Add nfiles to a directory (two clients) and check consistency after synch.
"""
from smashbox.utilities import *
from smashbox.utilities.hash_files import *
nfiles = int(config.get('nplustwo_nfiles',10))
def adder(step):
# if you don't want to cleanup server ... |
from __future__ import unicode_literals
from django.db import models
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
email_address = self.get_or_create(user=user, email=email, **kwargs)
if confirm and not email... |
import BaseHTTPServer
import errno
import json
import optparse
import os
import re
import socket
import SocketServer
import struct
import sys
import warnings
import tlslite.errors
# Ignore deprecation warnings, they make our output more cluttered.
warnings.filterwarnings("ignore", category=DeprecationWarning)
if sys... |
"""Middleware classes for third_party_auth."""
from social.apps.django_app.middleware import SocialAuthExceptionMiddleware
from . import pipeline
class ExceptionMiddleware(SocialAuthExceptionMiddleware):
"""Custom middleware that handles conditional redirection."""
def get_redirect_uri(self, request, excep... |
# _*_ coding:utf-8 _*_
from dataFunctions import *
import newUserThatDay as td
import newUserNextWeek as nw
import scene as sc
import timeAnalysis as ta
from bson.objectid import ObjectId
# calculate weekly top 10 topics
def weeklyTopicsEnterTop10(startDate, endDate):
pipeline = [
{
"$match": ... |
"""
Module for preprocessing data before
feeding it into the classfier
"""
import string
import re
from nltk.stem import SnowballStemmer
from nltk.corpus import stopwords
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import MinMaxScaler, Imputer
from sklearn.feature_extraction impo... |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class BackupPoliciesOperations(object):
"""BackupPoliciesOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
... |
"""
Utilities for view tests.
"""
import json
from contentstore.tests.utils import CourseTestCase
from contentstore.views.helpers import xblock_studio_url
from xmodule.modulestore.tests.factories import ItemFactory
class StudioPageTestCase(CourseTestCase):
"""
Base class for all tests of Studio pages.
"... |
import logging
import time
import openerp
from openerp.osv import osv
from openerp.tools.translate import _
_logger = logging.getLogger(__name__)
class ir_sequence_type(openerp.osv.osv.osv):
_name = 'ir.sequence.type'
_order = 'name'
_columns = {
'name': openerp.osv.fields.char('Name', size=64, r... |
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
class Command(BaseCommand):
help = ("Runs the command-line client for specified database, or the "
"default database if none is provided.")
option_lis... |
import StringIO
import unittest2 as unittest
from webkitpy.common import read_checksum_from_png
class ReadChecksumFromPngTest(unittest.TestCase):
def test_read_checksum(self):
# Test a file with the comment.
filehandle = StringIO.StringIO('''\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x03 \x00\x00... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
import xmodule_django.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... |
import unittest
from asq.queryables import Queryable
from asq.test.test_queryable import infinite, TracingGenerator
__author__ = "Robert Smallshire"
class TestWhere(unittest.TestCase):
def test_where(self):
a = range(0, 100)
b = Queryable(a).where(lambda x: x % 3 == 0).to_list()
c = list(... |
from sympy import symbols, Derivative, Integral, exp, cos, oo, Function
from sympy.functions.special.bessel import besselj
from sympy.functions.special.polynomials import legendre
from sympy.functions.combinatorial.numbers import bell
from sympy.printing.conventions import split_super_sub, requires_partial
def test_s... |
import gdb
class CachedType:
def __init__(self, name):
self._type = None
self._name = name
def _new_objfile_handler(self, event):
self._type = None
gdb.events.new_objfile.disconnect(self._new_objfile_handler)
def get_type(self):
if self._type is None:
... |
from functools import partial
import codecs
import pandas as pd
from azureml.errors import (
UnsupportedDatasetTypeError,
_not_none,
_not_none_or_empty,
)
class DataTypeIds(object):
"""Constants for the known dataset data type id strings."""
ARFF = 'ARFF'
PlainText = 'PlainText'
GenericCS... |
"""Base classes that are extended by low level AMQP frames and higher level
AMQP classes and methods.
"""
class AMQPObject(object):
"""Base object that is extended by AMQP low level frames and AMQP classes
and methods.
"""
NAME = 'AMQPObject'
INDEX = None
def __repr__(self):
items =... |
import uctypes
S1 = {}
assert uctypes.sizeof(S1) == 0
S2 = {"a": uctypes.UINT8 | 0}
assert uctypes.sizeof(S2) == 1
S3 = {
"a": uctypes.UINT8 | 0,
"b": uctypes.UINT8 | 1,
}
assert uctypes.sizeof(S3) == 2
S4 = {
"a": uctypes.UINT8 | 0,
"b": uctypes.UINT32 | 4,
"c": uctypes.UINT8 | 8,
}
assert ucty... |
"""Generate Google Mock classes from base classes.
This program will read in a C++ source file and output the Google Mock
classes for the specified classes. If no class is specified, all
classes in the source file are emitted.
Usage:
gmock_class.py header-file.h [ClassName]...
Output is sent to stdout.
"""
__aut... |
"""Classes to aid in configuration of the agent."""
import collections
import logging
import os
import pwd
import yaml
log = logging.getLogger(__name__)
class Plugins(collections.defaultdict):
"""A container for the plugin configurations used by the monasca-agent.
This is essentially a defaultdict(dic... |
from datetime import datetime
import json
import sqlite3
from bottle import get, post, run, request, static_file
db = sqlite3.connect('data.db')
cursor = db.cursor()
def init_db():
# check table
cursor.execute('SELECT COUNT(*) FROM sqlite_master WHERE type=? AND name=?',
('table', 'data'))... |
from deprecation import list_deprecated_before
from docopt import docopt
from trello import TrelloClient
from datetime import datetime
CARD_DESC_TEMPLATE = '''Remove all items that were deprecated in or before version {tag}.
This list automatically updated: {date}
{deprecated_desc}
'''
def create_line_title(filena... |
"""
variables_to_restore是为了在保持模型的时候方便使用滑动平均的参数,如果不使用这个保存,那模型就会保存所以参数,
除非你提前设定,就是在保存的时候指定保存变量也是可以的,比如saver = tf.train.Saver([v])这样就可以指定保存变量v,
在模型导入的时候只有这个变量会被导入。
"""
import tensorflow as tf
# v = tf.Variable(tf.constant(0.0, dtype=tf.float32), name='v')
# ema = tf.train.ExponentialMovingAverage(0.99) # 设定滑动平均函数
# main... |
#! /usr/local/bin/python3.5
import boto3
import time
def list_all_ec2():
ec2 = boto3.resource('ec2')
return ec2.instances.all()
def create_instance():
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
ImageId='ami-ebd02392',
MinCount=1,
MaxCount=1,
Instanc... |
"""distutils.command.upload
Implements the Distutils 'upload' subcommand (upload package to PyPI)."""
from distutils.errors import *
from distutils.core import Command
from distutils.spawn import spawn
from distutils import log
from hashlib import md5
import os
import socket
import platform
import ConfigParser
import... |
#!/usr/bin/python
"""
starter code for exploring the Enron dataset (emails + finances)
loads up the dataset (pickled dict of dicts)
the dataset has the form
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
FileSelectionPanel.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
********************... |
#!/usr/bin/env python
"""Code supporting distance matrices with arbitrary row/column labels.
Currently used to support amino acid distance matrices and similar.
NOTE: This is _much_ slower than using a numpy array. It is primarily
convenient when you want to index into a matrix by keys (e.g. by amino acid
labels) an... |
import unittest
from qingcloud.misc.json_tool import json_dump, json_load
class JsonToolTestCase(unittest.TestCase):
def test_json_dump_dict(self):
obj = {1:1, 'str': 'string', 'none': None}
expected = '{"1":1,"none":null,"str":"string"}'
self.assertEqual(json_dump(obj), expected)
def... |
"""
Track test skips via launchpadlib API and raise alerts if a bug
is fixed but a skip is still in the Tempest test code
"""
import logging
import os
import re
from launchpadlib import launchpad
BASEDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
TESTDIR = os.path.join(BASEDIR, 'tempest')
LPCAC... |
# coding: utf-8
from __future__ import unicode_literals
import json
from .common import InfoExtractor
from ..utils import (
ExtractorError,
)
class CNETIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?cnet\.com/videos/(?P<id>[^/]+)/'
_TESTS = [{
'url': 'http://www.cnet.com/videos/hands-on-wi... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import time
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
fr... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class hr_timesheet_invoice_create(osv.osv_memory):
_name = 'hr.timesheet.invoice.create'
_description = 'Create invoice from timesheet'
_columns = {
'date': fields.boolean('Date', help='The real date of each work will be dis... |
"""
grifthost urlresolver plugin
Copyright (C) 2015 tknorris
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 d... |
import unittest
from urwid import graphics
from urwid.compat import B
import urwid
class LineBoxTest(unittest.TestCase):
def border(self, tl, t, tr, l, r, bl, b, br):
return [bytes().join([tl, t, tr]),
bytes().join([l, B(" "), r]),
bytes().join([bl, b, br]),]
def test... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import codecs
import yaml
from ansible.parsing.yaml.loader import AnsibleLoader
from ansible.parsing.yaml.dumper import AnsibleDumper
from ansible.plugins.cache import BaseFileCacheModule
class CacheModule(BaseFileCacheModule):... |
import os
import unittest
import unitils
import platform
try:
from unittest import mock
except ImportError:
import mock
class TestCpCli(unittest.TestCase):
"""Test the functionality of the cp.py cli
"""
@mock.patch("unitils.cp")
def test_only_needs_src_and_dst(self, mock_cp):
argv = [... |
import yaml
import pprint
# Tokens mnemonic:
# directive: %
# document_start: ---
# document_end: ...
# alias: *
# anchor: &
# tag: !
# scalar _
# block_sequence_start: [[
# block_mapping_start: {{
# block_end: ]}
# flow_... |
from contextlib import contextmanager
import logging
import re
import sys
from threading import local
import time
import warnings
from functools import wraps
from xml.dom.minidom import parseString, Node
from django.conf import settings, UserSettingsHolder
from django.core import mail
from django.core.signals import r... |
"""
ref: https://www.hackerrank.com/contests/w24/challenges/simplified-chess-engine
"""
import unittest
def get_moves(piece, r, c, board):
def check_valid(x, y):
"""
:param board: playing board
:param c: pieces color
:param x: coord
:param y: coord
:return: boole... |
from django.conf import settings
from django.http import HttpResponseForbidden
from django.template import Context, Template
from django.utils.translation import ugettext as _
# We include the template inline since we need to be able to reliably display
# this error message, especially for the sake of developers, and ... |
"""
New Technology File System (NTFS) file system parser.
Sources:
- The NTFS documentation
http://www.linux-ntfs.org/
- NTFS-3G driver
http://www.ntfs-3g.org/
Creation date: 3rd january 2007
Author: Victor Stinner
"""
SECTOR_SIZE = 512
from hachoir_parser import Parser
from hachoir_core.field import (FieldSet,... |
"""Xception V1 model for Keras.
On ImageNet, this model gets to a top-1 validation accuracy of 0.790
and a top-5 validation accuracy of 0.945.
Reference:
- [Xception: Deep Learning with Depthwise Separable Convolutions](
https://arxiv.org/abs/1610.02357) (CVPR 2017)
"""
from tensorflow.python.keras import ba... |
"""
Discussion API forms
"""
from django.core.exceptions import ValidationError
from django.forms import (
BooleanField,
CharField,
ChoiceField,
Form,
IntegerField,
NullBooleanField,
Select)
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locator import CourseLocator
from opene... |
DOCUMENTATION = u'''
---
module: bzr
author: André Paramés
version_added: "1.1"
short_description: Deploy software (or files) from bzr branches
description:
- Manage I(bzr) branches to deploy files or software.
options:
name:
required: true
aliases: [ 'parent' ]
description:
... |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.models import AuditLogEntry, AuditLogEntryEvent
from sentry.testutils import TestCase, PermissionTestCase
class OrganizationAuditLogPermissionTest(PermissionTestCase):
def setUp(self):
super(OrganizationAudit... |
"""
Tests for paver quality tasks
"""
from __future__ import absolute_import, print_function
import os
import shutil
import tempfile
import textwrap
import unittest
import six
from ddt import data, ddt, file_data, unpack
from mock import MagicMock, mock_open, patch
from path import Path as path
from paver.easy import... |
import testtools
from oslo_log import log as logging
from designate.tests import TestCase
from designate import context
from designate import exceptions
LOG = logging.getLogger(__name__)
class TestDesignateContext(TestCase):
def test_deepcopy(self):
orig = context.DesignateContext(user='12345', tenant='... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
"""
Softlayer connection
"""
from libcloud.common.base import ConnectionUserAndKey
from libcloud.common.xmlrpc import XMLRPCResponse, XMLRPCConnection
from libcloud.common.types import InvalidCredsError, LibcloudError
class SoftLayerException(LibcloudError):
"""
Exception class for SoftLayer driver
"""
... |
import re
from django.test import TestCase
from mptt.exceptions import InvalidMove
from mptt.tests import doctests
from mptt.tests.models import Category, Genre
def get_tree_details(nodes):
"""Creates pertinent tree details for the given list of nodes."""
opts = nodes[0]._meta
return '\n'.join(['%s %s %s... |
""" Python Character Mapping Codec for PalmOS 3.5.
Written by Sjoerd Mullender (<EMAIL>); based on iso8859_15.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(s... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.stata
~~~~~~~~~~~~~~~~~~~~~
Lexer for Stata
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, include, words
from pygments.token import Comment, Keyword,... |
from OmegaExpansion import pwmExp
import time
import sys
# check the arguments
channel = 0
if len(sys.argv) == 2:
channel = int(sys.argv[1])
print('>> Using channel %d'%channel)
pwmExp.setVerbosity(0)
# check initialization
# should return 0 if the PWM Expansion has just been plugged in
ret = pwmExp.checkInit()
p... |
from builtins import map
from builtins import range
import imp
import logging
# Raise an ImportError if z3 is not available WITHOUT actually importing it
imp.find_module("z3")
from miasm.ir.translators.translator import Translator
log = logging.getLogger("translator_z3")
console_handler = logging.StreamHandler()
con... |
import py
import sys
class CommonFSTests(object):
def test_constructor_equality(self, path1):
p = path1.__class__(path1)
assert p == path1
def test_eq_nonstring(self, path1):
p1 = path1.join('sampledir')
p2 = path1.join('sampledir')
assert p1 == p2
def test_new_ide... |
from datetime import datetime
import os
import os.path
from django.db import models
from django.contrib.auth.models import User, Group
from django.utils.html import escape
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.hashcompat import sha_constructor
from ... |
"""
WSGI config for testproject 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_APPLICATIO... |
"""
Utilities for fast persistence of big data, with optional compression.
"""
# Copyright (c) 2009 Gael Varoquaux
# License: BSD Style, 3 clauses.
import pickle
import traceback
import sys
import os
import zlib
import warnings
if sys.version_info[0] >= 3:
from io import BytesIO
from pickle import _Unpickler... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) conexus.at
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public... |
import logging
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from openassessment.assessment.api.peer import get_assessments
from submissions.api import SubmissionRequestError, get_submissions
log = logging.getLogger(__name__)
@login_required()
def get_eva... |
"""
Copyright 2015 Ericsson AB
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software di... |
import abc
import os
TRUNK_COLOR = '#966F33'
LEAF_COLOR = '#6db33f'
EDGE_COLOR = "#cf142b"
NODE_COLOR = "#cccccc"
class Namespace(dict):
"""
Abstract constants class
Constants can be accessed via .attribute or [key] and can be iterated over.
"""
def __init__(self, *args, **kwargs):
d = {... |
from __future__ import absolute_import, division, print_function, \
with_statement
import collections
import logging
import time
# this LRUCache is optimized for concurrency, not QPS
# n: concurrency, keys stored in the cache
# m: visits not timed out, proportional to QPS * timeout
# get & set is O(1), not O(n).... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.