content stringlengths 4 20k |
|---|
from openerp.osv import osv, fields
class auth_oauth_provider(osv.osv):
"""Class defining the configuration values of an OAuth2 provider"""
_name = 'auth.oauth.provider'
_description = 'OAuth2 provider'
_order = 'name'
_columns = {
'name' : fields.char('Provider name', required=True), ... |
#!/opt/mesosphere/bin/python3
import logging
import os
import sys
import time
def main(directory, max_files, managed_file):
'''
Finds all files under the given `directory` and checks if the number
of files exceeds the `max_files`. If so, deletes files starting from
the oldest (except for the `manage... |
from twisted.internet import defer
from synapse.util.logutils import log_function
from synapse.types import UserID
from synapse.events.utils import serialize_event
from synapse.api.constants import Membership, EventTypes
from synapse.events import EventBase
from ._base import BaseHandler
import logging
import random... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
HAS_KEYRING = True
from ansible.errors import AnsibleError
try:
import keyring
except ImportError:
HAS_KEYRING = False
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Disp... |
"""
Unit tests for shoppingcart context_processor
"""
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from mock import patch, Mock
from course_modes.tests.factories import CourseModeFactory
from student.tests.factories import UserFactory
from xmodule.modulestore.tests.django_utils... |
import math
import RingTrack
import RingAction
center = (0, 0)
up = (0, 1)
down = (0, -1)
left = (-1, 0)
right = (1, 0)
ul = (-1, 1)
ur = (1, 1)
lr = (1, -1)
ll = (-1, -1)
def ringLerp(t, a, b):
omT = 1.0 - t
return (float(a[0]) * omT + float(b[0]) * t, float(a[1]) * omT + float(b[1]) * t)
def ringClerp(t, a... |
import pytest
from poker.card import Rank
def test_comparisons():
assert Rank("A") > Rank("K")
assert Rank("K") > Rank("Q")
assert Rank("Q") > Rank("J")
assert Rank("J") > Rank("T")
assert Rank("T") > Rank("9")
assert Rank("9") > Rank("2")
assert Rank("A") > Rank("2")
def test_comparison... |
"""Logging helpers"""
import logging
_default_level = "info"
_default_format = "%(asctime)s %(levelname)s %(message)s"
_debug_format = "%(asctime)s %(module)s:%(funcName)s:%(lineno)s %(levelname)s %(message)s"
def _name_to_level(name):
"""Translate log level name to internal logging value"""
levels = {"debug... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from unittest import skipUnless
from django.contrib.gis.geos import HAS_GEOS
from django.test import TestCase
from django.test.utils import override_settings
GOOGLE_MAPS_API_KEY = 'XXXX'
@skipUnless(HAS_GEOS, 'Geos is required.')
class GoogleMapsTest(... |
# -*- coding: utf-8 -*-
from .op import Op
from .db import DataType
from . import util
def _hex_dollar(value, size):
fmt = "${{:0{}X}}".format(2 * size)
return fmt.format(value)
def _disp_str(disp):
return "{:+d}".format(disp) if disp else ""
def _operand(addr, operand):
return operand
class MD6... |
from __future__ import absolute_import
import theano
import theano.tensor as T
import numpy as np
from .utils.theano_utils import shared_zeros, shared_scalar, floatX
from six.moves import zip
def clip_norm(g, c, n):
if c > 0:
g = T.switch(T.ge(n, c), g * c / n, g)
return g
def kl_divergence(p, p_ha... |
import csv
import os
from pydblite import Base
def convertcsv2db(csvpath, dbpath): #Converts a CSV file to a PyDBLite database
db = Base(dbpath)
try:
csvfile = open(csvpath, 'rb')
except csv.Error:
print("Could not open CSV file at " + csvpath + "\n")
reader = csv.reader(csvfi... |
from openerp import SUPERUSER_ID
from openerp.osv import osv, fields
from openerp.tools import html2plaintext
class note_stage(osv.osv):
""" Category of Note """
_name = "note.stage"
_description = "Note Stage"
_columns = {
'name': fields.char('Stage Name', translate=True, required=True),
... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.theorem
~~~~~~~~~~~~~~~~~~~~~~~
Lexers for theorem-proving languages.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, default, words
from py... |
from gnuradio import gr, gr_unittest, blocks
import math
class test_min(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_001(self):
src_data = (0, 0.2, -0.25, 0, 12, 0)
expected_result = (float(min(src_data)),)
... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
urljoin,
)
class MelonVODIE(InfoExtractor):
_VALID_URL = r'https?://vod\.melon\.com/video/detail2\.html?\?.*?mvId=(?P<id>[0-9]+)'
_TEST = {
'url': 'http://vod.melon.com... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
int_or_none
)
class RUTVIE(InfoExtractor):
IE_DESC = 'RUTV.RU'
_VALID_URL = r'''(?x)
https?://player\.(?:rutv\.ru|vgtrk\.com)/
(?P<path>flash\... |
from ctypes import c_char
from django.contrib.gis.geos.libgeos import (
GEOM_PTR, PREPGEOM_PTR, GEOSFuncFactory,
)
from django.contrib.gis.geos.prototypes.errcheck import check_predicate
# Prepared geometry constructor and destructors.
geos_prepare = GEOSFuncFactory('GEOSPrepare', argtypes=[GEOM_PTR], restype=PRE... |
def topological_sort_as_sets(dependency_graph):
"""Variation of Kahn's algorithm (1962) that returns sets.
Takes a dependency graph as a dictionary of node => dependencies.
Yields sets of items in topological order, where the first set contains
all nodes without dependencies, and each following set co... |
# -*- coding: utf-8 -*-
from .baserequest import BaseRequest
from oandapyV20.types import TradeID, PriceValue
from oandapyV20.definitions.orders import TimeInForce, OrderType
class StopLossOrderRequest(BaseRequest):
"""create a StopLossOrderRequest.
StopLossOrderRequest is used to build the body for a StopL... |
#==============================================================================
# khitest.py
#==============================================================================
from gandalf.analysis.facade import *
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib import rc
import time
rc('font',... |
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import time
from happy.ReturnMsg import ReturnMsg
from happy.Utils import *
from happy.HappyNode import HappyNode
from happy.HappyNetwork import HappyNetwork
from WeaveTest import WeaveTest
options = {}
options["client... |
from neutron.common import rpc as n_rpc
import oslo_messaging
class LbaasAgentApi(object):
"""Agent side of the Agent to Plugin RPC API."""
# history
# 1.0 Initial version
# 2.0 Generic API for agent based drivers
# - get_logical_device() handling changed on plugin side;
# - p... |
from abc import ABCMeta, abstractmethod
import six
class KubernetesRequestFactory:
"""
Create requests to be sent to kube API.
Extend this class to talk to kubernetes and generate your specific resources.
This is equivalent of generating yaml files that can be used by `kubectl`
"""
__metaclass... |
import unittest2
import openerp
import openerp.tests.common as common
class test_res_config(common.TransactionCase):
def setUp(self):
super(test_res_config, self).setUp()
self.res_config = self.registry('res.config.settings')
# Define the test values
self.menu_xml_id = 'base.menu... |
import project
import report
import wizard
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/env python
"""
DataSet
"""
"""
Copyright 2001 Pearu Peterson all rights reserved,
Pearu Peterson <<EMAIL>>
Permission to use, modify, and distribute this software is given under the
terms of the LGPL. See http://www.fsf.org
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
$Revision: 1... |
# pyre-strict
from typing import TYPE_CHECKING, Optional, Dict, List, Any
from lowerpines.endpoints.object import AbstractObject, Field, RetrievableObject
from lowerpines.endpoints.request import Request, JsonType
from lowerpines.endpoints.like import LikeCreateRequest, LikeDestroyRequest
from lowerpines.exceptions im... |
# Module 'ntpath' -- common operations on WinNT/Win95 pathnames
"""Common pathname manipulations, WindowsNT/95 version.
Instead of importing this module directly, import os and refer to this
module as os.path.
"""
import os
import sys
import stat
import genericpath
import warnings
from genericpath impor... |
from ..exceptions import except_orm
from .orm import Model, TransientModel, AbstractModel
# Deprecated, kept for backward compatibility.
# openerp.exceptions.Warning should be used instead.
except_osv = except_orm
# Deprecated, kept for backward compatibility.
osv = Model
osv_memory = TransientModel
osv_abstract = Ab... |
import unittest
from Cython import StringIOTree as stringtree
code = """
cdef int spam # line 1
cdef ham():
a = 1
b = 2
c = 3
d = 4
def eggs():
pass
cpdef bacon():
print spam
print 'scotch'
print 'tea?'
print 'or coffee?' # line 16
"""
linemap = dict(... |
import unittest
import sys
import os
import subprocess
import shutil
from copy import copy
from test.support import (run_unittest, TESTFN, unlink, check_warnings,
captured_stdout, skip_unless_symlink)
import sysconfig
from sysconfig import (get_paths, get_platform, get_config_vars,
... |
import argparse
import os
import os.path
parser = argparse.ArgumentParser()
parser.add_argument("--backend")
args = parser.parse_args()
os.environ['KERAS_BACKEND'] = args.backend
import tensorflow.python.keras.backend
if args.backend == "theano":
tensorflow.python.keras.backend.set_image_dim_ordering("th")
elif... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from mock import Mock
from memory_task_queue import MemoryTaskQueue
class TestMemoryTaskQueue(object):
def setup_method(self, test_method):
pass
def teardown_method(self, test_metho... |
from numpy.testing import assert_array_almost_equal, TestCase, run_module_suite
import numpy as np
from scipy.optimize import fmin_slsqp
class TestSLSQP(TestCase):
"""Test fmin_slsqp using Example 14.4 from Numerical Methods for
Engineers by Steven Chapra and Raymond Canale. This example
maximizes the ... |
"""Suite Standard URL suite: Mac URL standard, supported by many apps
Level 1, version 1
Generated from /Volumes/Sap/Applications (Mac OS 9)/Netscape Communicator\xe2\x84\xa2 Folder/Netscape Communicator\xe2\x84\xa2
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = 'GURL'... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test that nested SConscript files in a VariantDir don't throw
an OSError exception looking for the wrong file.
"""
import TestSCons
test = TestSCons.TestSCons()
test.subdir(['src'],
['src', 'md'],
['src', 'md', 'test'])
test.... |
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
from taiga.base.serializers import TagsField, PgArrayField, JsonField
from taiga.projects.userstories import models as us_models
from taiga.projects.tasks import models as task_models
from taiga.projects.issues import models... |
from LogAnalyzer import Test,TestResult
import DataflashLog
class TestGPSGlitch(Test):
'''test for GPS glitch reporting or bad GPS data (satellite count, hdop)'''
def __init__(self):
Test.__init__(self)
self.name = "GPS"
def run(self, logdata, verbose):
self.result = TestResult()
self.result.status = Tes... |
import sys
from flask import Flask, render_template
from flask_flatpages import FlatPages
from flask_frozen import Freezer
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
app = Flask (__name__)
app.config.from_object (__name__)
pages = FlatPages (app)
freezer = Freezer (app)
PROJECT_TAG = 'p... |
class Printer(object):
def __init__(self):
pass
def start_file(self):
print '''/* @flow */
/* @generated */
/* jshint ignore:start */
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the roo... |
import os
import pytest
from flask_user.tests.tst_app import app as the_app, init_app
from flask_user.tests.tst_utils import TstClient
@pytest.fixture(scope='session')
def app(request):
test_config = dict(
SQLALCHEMY_DATABASE_URI='sqlite:///:memory:', # In-memory sqlite DB
TESTING=True, ... |
from __future__ import (absolute_import, division)
__metaclass__ = type
from units.compat import unittest
from units.compat.mock import Mock
class BaseFactsTest(unittest.TestCase):
# just a base class, not an actual test
__test__ = False
gather_subset = ['all']
valid_subsets = None
fact_namespac... |
"""
Centralized command line and file system interface for the build script.
"""
# ----------------------------------------------------------------------------
from __future__ import print_function
import os
import pipes
import platform
import shutil
import subprocess
import sys
from contextlib import contextmanager
... |
from __future__ import print_function
import argparse
import glob
import multiprocessing
import os
import pipes
import subprocess
import sys
import tempfile
def get_verify_toolchain_modules_commands(toolchain_dir, sil_opt):
if sil_opt is None:
sil_opt = os.path.join(toolchain_dir, 'usr', 'bin', 'sil-opt'... |
import re
import time
import subprocess
epochs = 100
seconds_per_epoch = 0.236
cmd = 'bin\\cnn.exe train dry -c data\config.json --epochs {0:} -i data\\train_samples36'.format(epochs)
kernel_profile_regex = "Kernel '.*/(.*?]).*?([\-e.\d]+)ns.*?([\-e.\d]+)s"
def get_kernel_profiling_info(out):
out = out.decode('UTF-... |
from django.core import management
from django.core.checks import Error, run_checks
from django.db.models.signals import post_init
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils import six
class OnPostInit(object):
def __call__(self, **kwargs):
pas... |
#!/usr/bin/python
import gzip
import json
import logging
logging.basicConfig(level=logging.INFO, format="%(message)s")
meta_data = json.load(open("/var/rrd/vicenter/meta/hostSystemMemoryStats.json"))
print meta_data
#last_value = {}
with gzip.open("/var/rrd/vicenter/raw/hostSystemMemoryStats_2017-03-10.csv.gz") as ra... |
__reversion__ = "$Revision: 20 $"
__author__ = "$Author: holtwick $"
__date__ = "$Date: 2007-10-09 12:58:24 +0200 (Di, 09 Okt 2007) $"
"""
Helper for complex CSS definitons like font, margin, padding and border
Optimized for use with PISA
"""
import types
import logging
log = logging.getLogger("ho.css")
def ... |
from nameko.events import BROADCAST, event_handler
from sharingthelove import *
# --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- #
def do_work_son(sProject, sUniqSelectorId, sUniqTargetId, sDomain, sIp, sProtocol, sOpenTcpPort, sTcpService):
g... |
"""
A '2D' Histogram plot - e.g. one that has data on both the x and y axis. This is generated using numpy.histogram2d and
a call to pcolormesh. Although strictly a 2D plot it inherits from ComparativeScatter rather than Generic2D because
the unpacking has more in common with that.
"""
from cis.plotting.comparativescat... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.base.workunit import WorkUnitLabel
from pants.contrib.cpp.targets.cpp_binary import CppBinary
from pants.contrib.cpp.tasks.cpp_task import CppTask
class ... |
"""Stream-related things."""
__all__ = ['StreamReader', 'StreamWriter', 'StreamReaderProtocol',
'open_connection', 'start_server',
'IncompleteReadError',
]
import socket
if hasattr(socket, 'AF_UNIX'):
__all__.extend(['open_unix_connection', 'start_unix_server'])
from . import co... |
""" @file modelfactory.py
Model factory.
"""
import logging
import nupic.frameworks.opf.opfutils as opfutils
# Import models
from clamodel import CLAModel
from model import Model
from two_gram_model import TwoGramModel
from previousvaluemodel import PreviousValueModel
class ModelFactory(object):
""" Static fact... |
from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.contrib.auth import context_processors
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.urls import urlpatterns
from django.contrib.auth.views import password_reset, login
from django.contri... |
#!
# This is statement is required by the build system to query build info
if __name__ == '__build__':
raise Exception
import string
__version__ = string.split('$Revision: 1.1.1.1 $')[1]
__date__ = string.join(string.split('$Date: 2007/02/15 19:25:21 $')[1:3], ' ')
__author__ = 'Tarn Weisner Burton <<EMAIL>>'
#
# P... |
import re
import uno
import string
import unohelper
import xmlrpclib
from com.sun.star.task import XJobExecutor
if __name__<>"package":
from lib.gui import *
from Expression import Expression
from Fields import Fields
from Repeatln import RepeatIn
from lib.error import *
database="test"
uid ... |
from __future__ import unicode_literals
import re
import json
import os
from .common import InfoExtractor
from ..compat import (
compat_urlparse,
compat_urllib_parse_urlencode,
compat_urllib_parse_urlparse,
compat_str,
)
from ..utils import (
unified_strdate,
determine_ext,
int_or_none,
... |
"""Tests for rnn module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import numpy as np
from tensorflow.contrib.rnn.python.ops import rnn as contrib_rnn
from tensorflow.python.framework import dtypes
from tensorflow.python.framewor... |
"""contrib module containing volatile or experimental code."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
# Add projects here, they will show up under tf.contrib.
from tensorflow.contrib import batching
from tensorflow.contrib import bayesfl... |
from twisted.trial import unittest
from twisted.internet import reactor, defer
from twisted.python.failure import Failure
from scrapy.utils.defer import mustbe_deferred, process_chain, \
process_chain_both, process_parallel, iter_errback
from six.moves import xrange
class MustbeDeferredTest(unittest.TestCase):
... |
from __future__ import division, unicode_literals
"""
TODO: Modify module doc.
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "<EMAIL>"
__date__ = "6/6/13"
import unittest
import os
import json
from pymatge... |
"""
This config file follows the dev enviroment, but adds the
requirement of a celery worker running in the background to process
celery tasks.
The worker can be executed using:
django_admin.py celery worker
"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from bas... |
# Script for building the _ssl and _hashlib modules for Windows.
# Uses Perl to setup the OpenSSL environment correctly
# and build OpenSSL, then invokes a simple nmake session
# for the actual _ssl.pyd and _hashlib.pyd DLLs.
# THEORETICALLY, you can:
# * Unpack the latest SSL release one level above your main Python ... |
#!/usr/bin/env python
## https://bitbucket.org/pygame/pygame/raw/2383b8ab0e2273bc83c545ab9c18fee1f3459c64/pygame/base.py
'''Pygame core routines
Contains the core routines that are used by the rest of the
pygame modules. Its routines are merged directly into the pygame
namespace. This mainly includes the auto-initia... |
from ctypes import c_void_p
from types import NoneType
from django.contrib.gis.geos.error import GEOSException
# Trying to import GDAL libraries, if available. Have to place in
# try/except since this package may be used outside GeoDjango.
try:
from django.contrib.gis import gdal
except ImportError:
# A 'dumm... |
import os
import platform
import re
import shutil
import sys
from color import Coloring
from command import InteractiveCommand, MirrorSafeCommand
from error import ManifestParseError
from project import SyncBuffer
from git_config import GitConfig
from git_command import git_require, MIN_GIT_VERSION
class Init(Interac... |
"""Tests for the Question Player controller."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.domain import skill_services
from core.tests import test_utils
import feconf
class SkillMasteryDataHa... |
#! /usr/bin/python
from classes.Dataset import *
from classes.DatasetManager import *
from classes.Settings import *
from classes.Utils import *
import numpy as np
# Definition of the Relevancy class
class Relevancy():
# Load required classes
datasetManager = DatasetManager()
settings = Settings()
utils = Util... |
# Jinja2 filters for use in building dictionary with /etc/hosts to template
# Initialize a Dictionary keys with default value (usefull for preseting the value to an array)
def initDict( in_default, keyarray ):
r={}
for k in keyarray:
r[k]=in_default
return r
# Appends the hostname with subdomain first, then... |
"""
Implementation of the majority of http://www.ietf.org/rfc/rfc3339.txt.
Use datetime.datetime.isoformat() as an inverse of the various parsing
routines in this module.
Limitations, with respect to RFC 3339:
- Section 4.3, "Unknown Local Offset Convention", is not implemented.
- Section 5.6, "Internet Date/Time... |
from m5.SimObject import SimObject
class SparcISA(SimObject):
type = 'SparcISA'
cxx_class = 'SparcISA::ISA'
cxx_header = "arch/sparc/isa.hh" |
"""Support for switches using the PiFace Digital I/O module on a RPi."""
import logging
import voluptuous as vol
from homeassistant.components import rpi_pfio
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.const import ATTR_NAME, DEVICE_DEFAULT_NAME
import homeassistant.helpers.config_... |
import sys
from subprocess import Popen,PIPE
try:
import json
except ImportError:
import simplejson as json
VBOX="VBoxManage"
def get_hosts(host=None):
returned = {}
try:
if host:
p = Popen([VBOX, 'showvminfo', host], stdout=PIPE)
else:
returned = { 'all': s... |
from __future__ import absolute_import, division, print_function, unicode_literals
from guessit.plugins.transformers import Transformer
from guessit.matcher import found_guess
from guessit.containers import PropertiesContainer
class GuessEpisodeSpecial(Transformer):
def __init__(self):
Transformer.__init... |
__all__ = [
'Charset',
'add_alias',
'add_charset',
'add_codec',
]
import email.base64mime
import email.quoprimime
from email import errors
from email.encoders import encode_7or8bit
# Flags for types of header encodings
QP = 1 # Quoted-Printable
BASE64 = 2 # Base64
SHORTEST = 3... |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.regression
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests corner cases and bugs.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Template, Enviro... |
from django.test import TestCase
from django.contrib.gis.geos import GEOSGeometry, Point, MultiPoint
from django.contrib.gis.db.models import Collect, Count, Extent, F, Union
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.tests.utils import mysql, oracle, no_mysql, no_oracle, no_spati... |
from __future__ import print_function
from unittest import TestCase
import qelos as q
from torch.autograd import Variable
import torch
from torch import nn
import numpy as np
class TestWordEmb(TestCase):
def test_creation_simple(self):
dic = dict(zip(map(chr, range(97, 122)), range(122-97)))
m = q... |
from twisted.python import log
from twisted.internet import utils
from twisted.internet import defer, reactor, threads, interfaces
from twisted.trial import unittest, util
from twisted.trial.test import packages
import sys, os, time
suppress = [(['ignore', 'Do NOT use wait.*'], {})]
class WaitReentrancyTest(unittest... |
"""
This bootstrap module should be used to setup parts of the version_tracker plugin
that need to exist before all controllers are loaded. It is best used to
define/register hooks, setup namespaces, and the like.
"""
from pkg_resources import get_distribution
from cement.core.namespace import CementNamespace, re... |
"""
Support for the LIFX platform that implements lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.lifx/
"""
import colorsys
import logging
import voluptuous as vol
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_COLO... |
# Scan an Apple header file, generating a Python file of generator calls.
import sys
from bgenlocations import TOOLBOXDIR, BGENDIR
sys.path.append(BGENDIR)
from scantools import Scanner
LONG = "TextEdit"
SHORT = "te"
OBJECT = "TEHandle"
def main():
input = LONG + ".h"
output = SHORT + "gen.py"
defsoutput... |
from .proxy_only_resource import ProxyOnlyResource
class TopLevelDomain(ProxyOnlyResource):
"""A top level domain object.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype na... |
import numpy as np
import scipy.interpolate as si
from numpy import pi
from lfd.rapprentice import math_utils as mu
def smaller_ang(x):
return (x + pi)%(2*pi) - pi
def closer_ang(x,a,dir=0):
"""
find angle y (==x mod 2*pi) that is clos... |
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.messages import constants, utils
from django.utils.encoding import force_text, python_2_unicode_compatible
LEVEL_TAGS = utils.get_level_tags()
@python_2_unicode_compatible
class Message(object):
"""
Represents an ac... |
"""Subunit test protocol."""
import samba
samba.ensure_third_party_module("iso8601", "pyiso8601")
import iso8601
import unittest
PROGRESS_SET = 0
PROGRESS_CUR = 1
PROGRESS_PUSH = 2
PROGRESS_POP = 3
def RemoteError(description=""):
return (Exception, Exception(description), None)
class RemotedTestCase(unitt... |
"""Tests for SimpleRNN layer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python import keras
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framew... |
"""Tests for ReduceJoin op from string_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.framework import constant_op
from t... |
import time
from cloudify_rest_client.executions import Execution
from .exceptions import (ExecutionTimeoutError,
EventProcessingTimeoutError)
WAIT_FOR_EXECUTION_SLEEP_INTERVAL = 1
WORKFLOW_END_TYPES = {u'workflow_succeeded', u'workflow_failed',
u'workflow_cancelled'}
... |
"""Google Analytics Management API Demo.
This script demonstrates how to retrieve the important data from the Google
Analytics Data Management API using the Python Client library. This example
requires a Google Analytics account with data and a username and password.
Each feed in the Management API is retrieved and pr... |
'''
ElasticTree view for drawn topology
@author Albert Wu (<EMAIL>)
'''
from nox.ripcordapps.dispatch_server.ripcord_pb2 import Vertex, Edge, \
Path, Tunnels, Tunnel, TunnelsRequest, NewTunnelRequest, Topology,\
DisplayTunnel, DisplaySwitch, TopologyRequest, TopologyReply, \
LinkUtilizationRequest, LinkUtili... |
"""Encodings and related functions."""
__all__ = [
'encode_7or8bit',
'encode_base64',
'encode_noop',
'encode_quopri',
]
import base64
from quopri import encodestring as _encodestring
def _qencode(s):
enc = _encodestring(s, quotetabs=True)
# Must encode spaces, which quopri.encodestrin... |
"""
sentry.rules.conditions.event_frequency
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from datetime import datetime, timedelta
from django import forms
fro... |
"""Testing for Spectral Clustering methods"""
from sklearn.externals.six.moves import cPickle
dumps, loads = cPickle.dumps, cPickle.loads
import numpy as np
from scipy import sparse
from sklearn.utils import check_random_state
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_a... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import time
def main():
arg_spec = dict(
name=dict(required=True),
timeout=dict(default=300, type='int'),
state=dict(required=True, choices=['present... |
{
'name': 'Donation Recurring',
'version': '0.1',
'category': 'Accounting & Finance',
'license': 'AGPL-3',
'summary': 'Manage recurring donations',
'author': 'Barroux Abbey, Akretion, Odoo Community Association (OCA)',
'website': 'http://www.barroux.org',
'depends': ['donation'],
'da... |
import types
from itk.support import itkBase
# Needed to avoid problem with aliasing of itk.set (itkTemplate)
# inside the itk namespace. We need to explictly specify the
# use of the builtin set
from builtins import set as _builtin_set
# Need to use a recursive lock for thread ownership
# within the given thread yo... |
from __future__ import print_function
# $example on$
from pyspark.ml.feature import OneHotEncoder, StringIndexer
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("OneHotEncoderExample")\
.getOrCreate()
# $example ... |
from datetime import datetime
from sqlalchemy.orm import relationship, backref
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, Unicode, DateTime
from spendb.core import db, url_for
from spendb.model.dataset import Dataset
class Run(db.Model):
""" A run is a generic groupin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.