content string |
|---|
"""
Volume driver for HP LeftHand Storage array.
This driver requires 11.5 or greater firmware on the LeftHand array, using
the 1.0 or greater version of the hplefthandclient.
You will need to install the python hplefthandclient.
sudo pip install hplefthandclient
Set the following in the cinder.conf file to enable th... |
"""
NaiveBayes Example.
Usage:
`spark-submit --master local[4] examples/src/main/python/mllib/naive_bayes_example.py`
"""
import shutil
from pyspark import SparkContext
# $example on$
from pyspark.mllib.classification import NaiveBayes, NaiveBayesModel
from pyspark.mllib.util import MLUtils
# $example off$
if _... |
from distutils.util import convert_path
from distutils import log
from distutils.errors import DistutilsOptionError
import os
from setuptools import Command
from setuptools.compat import basestring
class rotate(Command):
"""Delete older distributions"""
description = "delete older distributions, keeping N n... |
from BitTornado import PSYCO
if PSYCO.psyco:
try:
import psyco
assert psyco.__version__ >= 0x010100f0
psyco.full()
except:
pass
from download_bt1 import BT1Download
from RawServer import RawServer, UPnP_ERROR
from RateLimiter import RateLimiter
from ServerPortHandler import Mult... |
# ASN.1 types tags
from operator import getitem
from pyasn1 import error
tagClassUniversal = 0x00
tagClassApplication = 0x40
tagClassContext = 0x80
tagClassPrivate = 0xC0
tagFormatSimple = 0x00
tagFormatConstructed = 0x20
tagCategoryImplicit = 0x01
tagCategoryExplicit = 0x02
tagCategoryUntagged = 0x04
class Tag:
... |
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q, QuerySet
from django.conf import settings
from cookies.models import *
from concepts.models import Concept
from cookies import authorization
import jsonpickle, datetime, copy, requests
from itertools import groupby, combination... |
import os
import unittest
import shutil
import sys
import tempfile
import mock
import elpy.pydocutils
class TestGetPydocCompletions(unittest.TestCase):
def test_should_return_top_level_modules(self):
modules = elpy.pydocutils.get_pydoc_completions("")
self.assertIn('sys', modules)
self.a... |
from direct.directnotify.DirectNotifyGlobal import directNotify
import fnmatch
import os
from panda3d.core import Multifile, Filename, VirtualFileSystem
import yaml
APPLICABLE_FILE_PATTERNS = ('*.mf', 'ambience.yaml')
CONTENT_EXT_WHITELIST = ('.jpg', '.jpeg', '.rgb', '.png', '.ogg', '.ttf')
class ContentPackError(... |
from django.db.models import CharField
from django.db.models.functions import LTrim, RTrim, Trim
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class TrimTests(TestCase):
def test_trim(self):
Author.objects.create(name=' John ', alias='j')
... |
import datetime
import sys
import socket
from socket import timeout as SocketTimeout
import warnings
from .packages import six
try: # Python 3
from http.client import HTTPConnection as _HTTPConnection, HTTPException
except ImportError:
from httplib import HTTPConnection as _HTTPConnection, HTTPException
cla... |
"""
TEST CASES:
Test.describe("Basic tests")
Test.assert_equals(average_string("zero nine five two"), "four")
Test.assert_equals(average_string("four six two three"), "three")
Test.assert_equals(average_string("one two three four five"), "three")
Test.assert_equals(average_string("five four"), "four")
Test.assert_equ... |
"""Compute intensity features in labeled image."""
import numpy as np
import pandas as pd
import scipy.stats
from skimage.measure import regionprops
def compute_intensity_features(
im_label, im_intensity, num_hist_bins=10,
rprops=None, feature_list=None):
"""Calculate intensity features from an in... |
from django.apps import apps
from django.utils.translation import ugettext_lazy as _
from taiga.base.fields import JsonField
from taiga.base.api.serializers import ValidationError
from taiga.base.api.serializers import ModelSerializer
from . import models
######################################################
# Cus... |
import cirruscluster.ext.ansible.constants as C
class Host(object):
''' a single ansible host '''
__slots__ = [ 'name', 'vars', 'groups' ]
def __init__(self, name=None, port=None):
self.name = name
self.vars = {}
self.groups = []
if port and port != C.DEFAULT_REMOTE_PORT:... |
#!/usr/bin/env python
import socket
import errno
try :
import memcache
HAVE_MEMCACHE = True
except ImportError:
HAVE_MEMCACHE = False
def iterwindow(l, slice=50):
"""Generate sublists from an iterator
>>> list(iterwindow(iter(range(10)),11))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>> list(iterwi... |
"""
Represents an DBSecurityGroup
"""
from boto.ec2.securitygroup import SecurityGroup
class DBSecurityGroup(object):
"""
Represents an RDS database security group
Properties reference available from the AWS documentation at
http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DeleteDBS... |
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor, error
from twisted.python import log
from jq.common import VariablePacketProtocol
import pickle
import functools
class ConsumerClientProtocol(VariablePacketProtocol):
def connectionMade(self):
data = pickle.... |
import os
import argparse
import logging
logging.basicConfig(level=logging.DEBUG)
from common import find_mxnet
from common import data, fit, modelzoo
import mxnet as mx
def get_fine_tune_model(symbol, arg_params, num_classes, layer_name):
"""
symbol: the pre-trained network symbol
arg_params: the argument... |
from __future__ import print_function
from pyspark import SparkContext
# $example on$
from pyspark.mllib.feature import ElementwiseProduct
from pyspark.mllib.linalg import Vectors
# $example off$
if __name__ == "__main__":
sc = SparkContext(appName="ElementwiseProductExample") # SparkContext
# $example on$
... |
"""Fake HUG API module usable for testing importation of modules"""
import hug
@hug.directive(apply_globally=False)
def my_directive(default=None, **kwargs):
'''for testing'''
return default
@hug.default_input_format('application/made-up')
def made_up_formatter(data):
'''for testing'''
return data
... |
import importlib
import os
import pdb
import sys
import tempfile
sys.path.append("/opt/tosca")
from translator.toscalib.tosca_template import ToscaTemplate
import pdb
from services.hpc.models import HpcHealthCheck, HpcService
from xosresource import XOSResource
class XOSHpcHealthCheck(XOSResource):
provides = "t... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
__doc__ = """
SCons C Pre-Processor module
"""
import SCons.compat
import os
import re
import string
#
# First "subsystem" of regular expressions that we set up:
#
# Stuff to turn the C preprocessor directives in a file's contents into
# a list of tuples... |
#!/usr/bin/env python
"""
@package mi.core.test.test_persistent_store
@file <git-workspace>/ooi/edex/com.raytheon.uf.ooi.plugin.instrumentagent/utility/edex_static/base/ooi/instruments/mi-instrument/mi/core/test/test_persistent_store.py
@author Johnathon Rusk
@brief Unit tests for PersistentStoreDict module
"""
# Not... |
"""This module originally includes functions for grading Vsepr problems.
Also, may be this module is the place for other chemistry-related grade functions. TODO: discuss it.
"""
import json
import unittest
import itertools
def vsepr_parse_user_answer(user_input):
"""
user_input is json generated by vsepr.js... |
import cx_Oracle
from django.db.backends.oracle.introspection import DatabaseIntrospection
class OracleIntrospection(DatabaseIntrospection):
# Associating any OBJECTVAR instances with GeometryField. Of course,
# this won't work right on Oracle objects that aren't MDSYS.SDO_GEOMETRY,
# but it is the only o... |
from unittest import TestCase
from mathUtils.Vector2 import Vector2
from mathUtils.MathUtils import MathUtils
from mathUtils.Direction import Direction
class TestMathUtils(TestCase):
def test_getDirectionVector(self):
a = Vector2(1, 1)
b = Vector2(7, 7)
self.assertEqual(Vector2(6, 6), Math... |
"""Utilities for statistics"""
def sorted(xs):
"""Return a sorted copy of the list xs"""
_xs = list(xs)
_xs.sort()
return _xs
def stemleaf(ns):
"""Given a list of integers ns, print a stem-and-leaf display."""
return _stemleaf(sorted(ns))
def dsd(ns):
"""Given a list of integers ns, print... |
import socket, struct
import netlink
qdisc_kinds = {}
TC_H_ROOT = 0xFFFFFFFF
class QdiscException(Exception): pass
class request(object):
"qdisc request message"
def __init__(self, cmd, flags=0, dev=None, handle=0):
self.n = netlink.nlmsg()
self.t = netlink.tcmsg()
self.n.nlmsg_fla... |
import os
import sys
import re
import time
import traceback
packageFullPath = "..\..\..\..\..\PrimeSenseVersions.nsh"
def find_package_number(findStr, text):
for line in text:
temp = re.search(findStr, line)
if temp != None:
packageNumber = temp.group(1)
return packageNumbe... |
# These are versions of the functions in django.utils.translation.trans_real
# that don't actually do anything. This is purely for performance, so that
# settings.USE_I18N = False can use this module rather than trans_real.py.
import warnings
from airy.core.conf import settings
from airy.utils.encoding import force_un... |
from layer.basic.pooling import MaxPoolingWithTimeLayer as MaxPoolingWithTimeLayerBase
class MaxPoolingWithTimeLayer(MaxPoolingWithTimeLayerBase):
def get_computation_on_java_code(self, code, binder):
datatype = binder.get_base_type(self.input)
input_var = binder.get_name(self.input)
outp... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
class GetChainTipsTest (BitcoinTestFramework):
def run_test (self):
BitcoinTestFramework.run_test (self)
tips = self.nodes[0].getchaintips ()
assert_equal (len (tips), 1)
as... |
from django.forms import Form, HiddenInput, NullBooleanField, RadioSelect
from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin
class NullBooleanFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_nullbooleanfield_clean(self):
f = NullBooleanField()
self.assertI... |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed i... |
"""Base option parser setup"""
import sys
import optparse
import pkg_resources
import os
import textwrap
from distutils.util import strtobool
from pip.backwardcompat import ConfigParser, string_types, ssl
from pip.locations import default_config_file, default_log_file
from pip.util import get_terminal_size, get_prog
... |
import pytz
from pyrfc3339.utils import timezone, timedelta_seconds
def generate(dt, utc=True, accept_naive=False, microseconds=False):
'''
Generate an :RFC:`3339`-formatted timestamp from a
:class:`datetime.datetime`.
>>> from datetime import datetime
>>> generate(datetime(2009,1,1,12,59,59,0,p... |
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
from lettuce import world, step
from nose.tools import assert_true, assert_false # pylint: disable=no-name-in-module
@step('I fill in the registration form$')
def i_fill_in_the_registration_form(step):
def fill_in_reg_form():
reg... |
"""Classes for storing and processing test results."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import re
from . import types as t
from .util import (
display,
get_ansible_version,
)
from .util_common import (
write_text_test_results,
wr... |
# encoding: utf-8
import sys
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from apps.rss_feeds.models import Feed
try:
from apps.rss_feeds.models import FeedIcon
except ImportError:
pass
class Migration(DataMigration):
def forwards(self, orm):
... |
from .. import models
from .helpers import PhotologueBaseTest
from .factories import GalleryFactory, PhotoFactory
class GalleryTest(PhotologueBaseTest):
def setUp(self):
"""Create a test gallery with 2 photos."""
super(GalleryTest, self).setUp()
self.test_gallery = GalleryFactory()
... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Bunch of log formatters to be used."""
import logging
try:
import ujson as json
except Exception as ex:
import json
class TextFormatter(logging.Formatter):
"""Format the meta data in the log message to fix string length."""
datefmt = '%Y-%m-%d %H:%M... |
import logging
import logging.handlers
from optparse import OptionParser
import os
import sys
import quantumclient.cli as qcli
from quantumclient import Client
LOG = logging.getLogger('quantum')
FORMAT = 'json'
#ACTION_PREFIX_EXT = '/v1.0'
#ACTION_PREFIX_CSCO = ACTION_PREFIX_EXT + \
# '/extensions/csco/tena... |
import sys
from PyQt5.QtCore import (pyqtProperty, pyqtSlot, QCoreApplication, QObject,
QUrl)
from PyQt5.QtQml import (qmlRegisterType, QQmlComponent, QQmlEngine,
QQmlListProperty)
QML = b'''
import QtQuick 2.0
import People 1.0
BirthdayParty {
host: Person {
name: "Bob Jones"
sh... |
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest.common import waiters
from tempest import config
from tempest import test
CONF = config.CONF
class VolumesSnapshotsTestJSON(base.BaseV2ComputeTest):
@classmethod
def skip_checks(cls):
super(VolumesSnapshot... |
from __future__ import unicode_literals
from django.db import router
class Operation(object):
"""
Base class for migration operations.
It's responsible for both mutating the in-memory model state
(see db/migrations/state.py) to represent what it performs, as well
as actually performing it agains... |
import simplejson
import openerp
import openerp.http as http
from openerp.http import request
import openerp.addons.web.controllers.main as webmain
import json
class meeting_invitation(http.Controller):
@http.route('/calendar/meeting/accept', type='http', auth="calendar")
def accept(self, db, token, action, ... |
from kafka.tools.protocol.requests.update_metadata_v0 import UpdateMetadataV0Request
from kafka.tools.protocol.responses.update_metadata_v3 import UpdateMetadataV3Response
class UpdateMetadataV3Request(UpdateMetadataV0Request):
api_version = 3
response = UpdateMetadataV3Response
help_string = ''
sch... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.data
~~~~~~~~~~~~~~~~~~~~
Lexers for data file format.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, ExtendedRegexLexer, LexerContext, \
... |
import github.GithubObject
class PaginatedListBase:
def __init__(self):
self.__elements = list()
def __getitem__(self, index):
assert isinstance(index, (int, slice))
if isinstance(index, (int, long)):
self.__fetchToIndex(index)
return self.__elements[index]
... |
from markdown.blockprocessors import BlockProcessor
from MooseCommonExtension import MooseCommonExtension
import re
from markdown.util import etree
class MooseCSS(BlockProcessor, MooseCommonExtension):
"""
Markdown extension for applying CSS styles to paragraph
Markdown syntax is:
!css <options>
... |
# We will need to create Qt4 items
from PyQt4 import QtCore
from PyQt4.QtGui import QGraphicsRectItem, QGraphicsSimpleTextItem, \
QGraphicsEllipseItem, QColor, QPen, QBrush
from ... import Tree, faces, TreeStyle, NodeStyle
# To play with random colors
import colorsys
import random
class InteractiveItem(QGraphics... |
import contextlib
from oslo_config import cfg
from oslo_db.sqlalchemy import session
from sqlalchemy import exc
_FACADE = None
MAX_RETRIES = 10
def _create_facade_lazily():
global _FACADE
if _FACADE is None:
_FACADE = session.EngineFacade.from_config(cfg.CONF, sqlite_fk=True)
return _FACADE
... |
import warnings
warnings.warn(
"Create your own event dispatching mechanism, "
"twisted.python.dispatch will soon be no more.",
DeprecationWarning, 2)
class EventDispatcher:
"""
A global event dispatcher for events.
I'm used for any events that need to span disparate objects in the client.
... |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2015 ARM Limited
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 o... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import datetime
import backtrader as bt
class SmaCross(bt.SignalStrategy):
params = dict(sma1=10, sma2=20)
def notify_order(self, order):
if not order.alive():
pr... |
import logging
import os
import sys
import time
from tests.common.impala_cluster import *
from random import choice
from threading import Timer
logging.basicConfig(level=logging.INFO, format='%(threadName)s: %(message)s')
LOG = logging.getLogger('failure-injector')
# This class is used for injecting failures for the ... |
"""Implements Query BigQuery API."""
from __future__ import absolute_import
from __future__ import unicode_literals
from builtins import object
import google.datalab
import google.datalab.data
import google.datalab.utils
from ._query_output import QueryOutput
from . import _api
from . import _query_job
from . import ... |
from sympy.assumptions import ask, Q
from sympy.assumptions.assume import assuming, global_assumptions
from sympy.abc import x, y
def test_assuming():
with assuming(Q.integer(x)):
assert ask(Q.integer(x))
assert not ask(Q.integer(x))
def test_assuming_nested():
assert not ask(Q.integer(x))
ass... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class InaIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ina\.fr/video/(?P<id>I?[A-Z0-9]+)'
_TEST = {
'url': 'http://www.ina.fr/video/I12055569/francois-hollande-je-crois-que-c-est-clair-video.ht... |
from __future__ import absolute_import
# -*- coding: utf-8 -*-
import numpy as np
import random
from six.moves import range
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre'):
"""
Pad each sequence to the same length:
the length of the longuest sequence.
If maxlen is ... |
"""
Tests the helper functions/classes/etc used in wrapping GMT.
"""
import os
import numpy as np
import pytest
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers import (
GMTTempFile,
args_in_kwargs,
data_kind,
kwargs_to_strings,
unique_name,
)
@pytest.mark.parametrize(
"data,x,... |
from panda3d.core import LVector4f
import DNANode
import DNAUtil
import DNAError
class DNALandmarkBuilding(DNANode.DNANode):
COMPONENT_CODE = 13
def __init__(self, name):
DNANode.DNANode.__init__(self, name)
self.code = ''
self.wallColor = LVector4f(1, 1, 1, 1)
self.title = ''
... |
"""Selectors module.
This module allows high-level and efficient I/O multiplexing, built upon the
`select` module primitives.
The following code adapted from trollius.selectors.
"""
from abc import ABCMeta, abstractmethod
from collections import namedtuple, Mapping
import math
import select
import sys
from gunicor... |
from setuptools import setup, find_packages
setup(
name = 'TestProject',
version = '0.1',
license = 'BSD',
author = 'Foo Bar',
author_email = '<EMAIL>',
packages = find_packages(),
) |
#!/usr/bin/env python
'''
CREATED:2014-01-24 12:42:43 by Brian McFee <<EMAIL>>
Compute beat evaluation metrics
Usage:
./beat_eval.py REFERENCE.TXT ESTIMATED.TXT
'''
from __future__ import print_function
import argparse
import sys
import os
import eval_utilities
import mir_eval
def process_arguments():
'''Ar... |
import optparse
import sys
import time
import base64
from decimal import Decimal
sys.path.insert(0, "bin/python")
import samba
samba.ensure_external_module("testtools", "testtools")
samba.ensure_external_module("subunit", "subunit/python")
import samba.getopt as options
from ldb import (
SCOPE_BASE, SCOP... |
from openerp.osv import fields, orm
class res_partner(orm.Model):
_inherit = "res.partner"
_columns = {
'bank_statement_label': fields.one2many('account.statement.label',
'partner_id',
'Bank Statement Labe... |
import sys
import os
import GenericSearch
import pandas
# Define regions contaminated by telluric residuals or other defects. We will not use those regions in the cross-correlation
badregions = [[0, 1510], # Blue end of H band (lots of water absorption)
#[1561, 1615], # CO2 band that is often poorly c... |
"""Top-level presubmit script for GYP.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
PYLINT_BLACKLIST = [
# TODO: fix me.
# From SCons, not done in google style.
'test/lib/TestCmd.py',
'test/lib/TestCommon.py',... |
import hashlib
import logging
import re
import warnings
from django.conf import settings
from django.core.mail import mail_managers
from django.core import urlresolvers
from django import http
from django.utils.deprecation import RemovedInDjango18Warning
from django.utils.encoding import force_text
from django.utils.h... |
from south.db import db
from django.db import models
from mysite.search.models import *
class Migration:
def forwards(self, orm):
# Adding field 'BugAnswer.created_date'
db.add_column('search_buganswer', 'created_date', orm['search.buganswer:created_date'])
# Adding f... |
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger
from pkg_resources import EntryPoint
from guessit.options import reload as reload_options
from stevedore import ExtensionManager
from stevedore.extension import Extension
log = getLogger(__name__)
class... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pyexpect.replwrap will not work with unicode_literals
# from __future__ import unicode_literals
import os
import random
import sys
import unittest
import utils
# osquery-specific testing utils
import test_ba... |
from __future__ import absolute_import, division, unicode_literals
from six import text_type
import re
from . import _base
from .. import ihatexml
from .. import constants
from ..constants import namespaces
from ..utils import moduleFactoryFactory
tag_regexp = re.compile("{([^}]*)}(.*)")
def getETreeBuilder(Elemen... |
"""SCons.Tool.rpmutils.py
RPM specific helper routines for general usage in the test framework
and SCons core modules.
Since we check for the RPM package target name in several places,
we have to know which machine/system name RPM will use for the current
hardware setup. The following dictionaries and functions try t... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Alumno.activo'
db.add_column(u'alumnos_alumno', 'activo',... |
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import Connection
from ansible.module_utils.network.eos.providers import providers
from ansible.module_utils._text import to_text
class NetworkModule(AnsibleModule):
fail_on_missing_provider = True
def __init__(self, c... |
import doctest
import json
import logging
import os
import unittest
import sys
sys.path.insert(0, "..")
import configr
class Tests(unittest.TestCase):
''' Test suite. '''
def tests_metadata(_):
_.assertTrue(hasattr(configr, "version"))
_.assertTrue(hasattr(configr.version, "__version__"))
_.assertT... |
import os,sys
from PyQt4 import QtCore
from PyQt4 import QtGui
import functools
import itertools
import re
from subprocess import Popen
import pythoncom #-- shortcut
from win32com.shell import shell, shellcon
from installer_ui import Ui_MainWindow
class MainGUI(QtGui.QMainWindow,Ui_MainWindow):
def __init__(self,pa... |
import datetime
import time
from openerp.osv import osv
from openerp.report import report_sxw
class attendance_print(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(attendance_print, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
'ti... |
import pytz
from datetime import datetime
from catalyst.api import symbol
from catalyst.utils.run_algo import run_algorithm
coin = 'btc'
quote_currency = 'usd'
n_candles = 5
def initialize(context):
context.symbol = symbol('%s_%s' % (coin, quote_currency))
def handle_data_polo_partial_candles(context, data):
... |
# LogoMation-like turtle graphics
from math import * # Also for export
import Tkinter
class Error(Exception):
pass
class RawPen:
def __init__(self, canvas):
self._canvas = canvas
self._items = []
self._tracing = 1
self.degrees()
self.reset()
def degrees(self, full... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# By Yusuke Suzuki <<EMAIL>>
# Modified by Mathias Bynens <http://mathiasbynens.be/>
# http://code.google.com/p/esprima/issues/detail?id=110
import sys
import string
import re
class RegExpGenerator(object):
def __init__(self, detector):
self.detector = detec... |
from build import plot_results, print_results
#valid formats are png, pdf, ps, eps and svg
#if format=None the plot will be displayed
format = 'png'
#output = print_results
output = plot_results
for function in ['fill', 'reduce', 'inner_product', 'gather', 'merge']:
output(function + '.xml', 'InputType', 'InputSi... |
# -*- coding: utf-8 -*-
"""
requests.auth
~~~~~~~~~~~~~
This module contains the authentication handlers for Requests.
"""
import os
import re
import time
import hashlib
import threading
import warnings
from base64 import b64encode
from .compat import urlparse, str, basestring
from .cookies import extract_cookies_... |
from sqlalchemy import types as sqltypes
from sqlalchemy.sql.expression import (
ClauseList, Function, _literal_as_binds, text, _type_from_args
)
from sqlalchemy.sql import operators
from sqlalchemy.sql.visitors import VisitableType
class _GenericMeta(VisitableType):
def __call__(self, *args, **kwargs):
... |
"""Classification metrics library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import ma... |
#!/home/amos/anaconda/bin/python
from PythonQt.Qt import *
from PythonQt.QtGui import *
class CGScene(QGraphicsScene):
def __init__(self, parent = None):
super(CGScene, self).__init__(self)
class Texture(QGraphicsItem):
def __init__(self, pos, tex):
super(Texture, self).__init__(self)
self.tex = tex
s... |
"""Miscellaneous functions and classes that dont fit into specific
categories."""
import sys, os, vtk
#----------------------------------------------------------------------
# the following functions are for the vtk regression testing and examples
def vtkGetDataRoot():
"""vtkGetDataRoot() -- return vtk example d... |
"""inject_closure module"""
INJECTEDKEY = "injected_{}"
OUTERLINE = " outer_{0} = injected_{0}"
INNERLINE = " inner_{0} = outer_{0}"
SOURCE= ("def not_important():",
" def also_not_important():",
" return also_not_important")
def inject_closure(f, *args):
"""Ret... |
from oslo_utils import timeutils
from oslo_versionedobjects import fields
from cinder import objects
def fake_db_service(**updates):
NOW = timeutils.utcnow().replace(microsecond=0)
db_service = {
'created_at': NOW,
'updated_at': None,
'deleted_at': None,
'deleted': False,
... |
import wx
import wx.lib.activex
import comtypes.client as cc
import sys
if not hasattr(sys, 'frozen'):
cc.GetModule( ('{D27CDB6B-AE6D-11CF-96B8-444553540000}', 1, 0) )
from comtypes.gen import ShockwaveFlashObjects
clsID = '{D27CDB6E-AE6D-11CF-96B8-444553540000}'
progID = 'ShockwaveFlash.ShockwaveFlash.1'
cla... |
#!/usr/bin/python
import sys
import time
import os
import string
import StringIO
sys.path.insert(0, "python")
import libxml2
# Memory debug specific
libxml2.debugMemory(1)
debug = 0
verbose = 0
quiet = 1
#
# the testsuite description
#
CONF=os.path.join(os.path.dirname(__file__), "test/xsdtest/xsdtestsuite.xml")
LOG=... |
"""
Utilities related to nose.
"""
from django.core.management import call_command
from django.db import DEFAULT_DB_ALIAS, connections, transaction
import django_nose
class NoseTestSuiteRunner(django_nose.NoseTestSuiteRunner):
"""Custom NoseTestSuiteRunner."""
def setup_databases(self):
""" Setup dat... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding index on 'Player', fields ['is_dead']
db.create_index('namelist_player', ['is_dead'])
# ... |
from twisted.trial import unittest
from twisted.manhole import service
from twisted.spread.util import LocalAsRemote
class Dummy:
pass
class DummyTransport:
def getHost(self):
return 'INET', '127.0.0.1', 0
class DummyManholeClient(LocalAsRemote):
zero = 0
broker = Dummy()
broker.transport... |
"""
Configuration reader and defaults.
Author: Henrik Thostrup Jensen <<EMAIL>>
Copyright: NORDUnet (2011)
"""
import os
import ConfigParser
from opennsa import constants as cnt
# defaults
DEFAULT_CONFIG_FILE = '/etc/opennsa.conf'
DEFAULT_LOG_FILE = '/var/log/opennsa.log'
DEFAULT_TLS = 'tru... |
"""The application's Globals object"""
import string
from pylons import session
from orthography import Orthography
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is creat... |
"""Monkey's Audio streams with APEv2 tags.
Monkey's Audio is a very efficient lossless audio compressor developed
by Matt Ashland.
For more information, see http://www.monkeysaudio.com/.
"""
__all__ = ["MonkeysAudio", "Open", "delete"]
import struct
from mutagen.apev2 import APEv2File, error, delete
from mutagen._... |
from django.db import transaction as tx
from taiga.base.api.utils import get_object_or_404
#############################################
# ViewSets
#############################################
class MoveOnDestroyMixin:
@tx.atomic
def destroy(self, request, *args, **kwargs):
move_to = self.request.Q... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.