content stringlengths 4 20k |
|---|
"""## Functions for working with arbitrarily nested sequences of elements.
NOTE(mrry): This fork of the `tensorflow.python.util.nest` module
makes two changes:
1. It adds support for dictionaries as a level of nesting in nested structures.
2. It removes support for lists as a level of nesting in nested structures.
T... |
import six
import webob
from webob import exc
from nova.api.openstack.compute.contrib import security_groups as sg
from nova.api.openstack import extensions
from nova import context as nova_context
from nova import exception
from nova.i18n import _
from nova.network.security_group import openstack_driver
authorize =... |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class Participant(Base):
__tablename__ = 'participations'
id = Column(String(32), primary_key=True)
team_id = Column(String(41))
match_id = Column(Integer)
summoner_id ... |
"""Test case-sensitivity (PEP 235)."""
from .. import util
from . import util as source_util
importlib = util.import_importlib('importlib')
machinery = util.import_importlib('importlib.machinery')
import os
import sys
from test import support as test_support
import unittest
@util.case_insensitive_tests
class CaseSe... |
"""Test maasserver NodeMetadata model."""
from crochet import wait_for
from django.core.exceptions import ValidationError
from maasserver.models import NodeMetadata
from maasserver.testing.factory import factory
from maasserver.testing.testcase import MAASServerTestCase
wait_for_reactor = wait_for(30) # 30 seconds... |
# encoding: utf-8
"""
Custom element classes related to text runs (CT_R).
"""
from ..ns import qn
from ..simpletypes import ST_BrClear, ST_BrType
from ..xmlchemy import (
BaseOxmlElement, OptionalAttribute, ZeroOrMore, ZeroOrOne
)
class CT_Br(BaseOxmlElement):
"""
``<w:br>`` element, indicating a line, ... |
# -*- coding: utf-8 -*-
from openerp import SUPERUSER_ID
from openerp.osv import orm, fields
class PaymentTransaction(orm.Model):
_inherit = 'payment.transaction'
_columns = {
# link with the sale order
'sale_order_id': fields.many2one('sale.order', 'Sale Order'),
}
def form_feedbac... |
__all__ = ['findHTMLMeta', 'MetaNotFound']
from HTMLParser import HTMLParser, HTMLParseError
import htmlentitydefs
import re
from openid.yadis.constants import YADIS_HEADER_NAME
# Size of the chunks to search at a time (also the amount that gets
# read at a time)
CHUNK_SIZE = 1024 * 16 # 16 KB
class ParseDone(Excep... |
'''
tunepk urlresolver plugin
Copyright (C) 2013 icharania
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 dis... |
"""
Startmigration command, version 2.
"""
from __future__ import print_function
import sys
import os
import re
import string
import random
import inspect
from optparse import make_option
try:
set
except NameError:
from sets import Set as set
from django.core.management.base import BaseCommand
from django.c... |
# -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749.grant_types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import unicode_literals, absolute_import
import logging
log = logging.getLogger(__name__)
class RequestValidator(object):
def client_authentication_required(self, request, *args, **kwargs):
... |
from tkinter import *
class ScrolledList:
default = "(None)"
def __init__(self, master, **options):
# Create top frame, with scrollbar and listbox
self.master = master
self.frame = frame = Frame(master)
self.frame.pack(fill="both", expand=1)
self.vbar = vbar = Scrollba... |
__all__ = ['install_optimal_reactor','install_reactor']
def install_optimal_reactor():
"""
Try to install the optimal Twisted reactor for platform.
"""
import sys
if 'bsd' in sys.platform or sys.platform.startswith('darwin'):
try:
v = sys.version_info
if v[0] == 1 or (v[0] == 2... |
#! /usr/bin/python
import os
import sys
import glob
import optparse
import tempfile
import logging
import shutil
import ConfigParser
class Fail(Exception):
def __init__(self, test, msg):
self.msg = msg
self.test = test
def getMsg(self):
return '\'%s\' - %s' % (self.test.path, self.msg)... |
#!/usr/bin/env python3
import requests
import midata
from midata import authentication as auth
# input data
server = "https://db.scout.ch"
email = "<EMAIL>"
password = "password"
# log in
auth_info = auth.sign_in(server, email, password)
if not auth_info:
pass
user = midata.get_person(auth_info, auth_info.... |
from openerp import models, fields
class TransportDocument(models.Model):
_name = "transport.document"
name = fields.Char('Name', translate=True) |
#!/usr/bin/env python3
"""A utility script for automating the beets release process.
"""
import click
import os
import re
import subprocess
from contextlib import contextmanager
import datetime
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CHANGELOG = os.path.join(BASE, 'docs', 'changelog.rst')
... |
'''
Created on Nov 12, 2012
@author: mmornati
'''
from djcelery.models import PeriodicTask, IntervalSchedule
from django.db import models
class TaskScheduler(models.Model):
periodic_task = models.ForeignKey(PeriodicTask)
@staticmethod
def schedule_every(task_name, task, period, every, args=None, kwa... |
from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.lib.shape_base import (
apply_along_axis, apply_over_axes, array_split, split, hsplit, dsplit,
vsplit, dstack, kron, tile
)
from numpy.testing import (
run_module_suite, TestCase, assert_, assert_equal, asser... |
from blur.Stone import *
from blur.Stonegui import *
from PyQt4.QtCore import *
from blur.defaultdict import *
class FarmReport:
def __init__(self,name):
self.name = name
self.records = RecordList()
self.columns = []
self.headerLabels = []
self.model = None
def generate(self,startDate,endDate):
self.s... |
import json
from ansible.modules.storage.netapp.netapp_e_asup import Asup
from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args
__metaclass__ = type
from units.compat import mock
class AsupTest(ModuleTestCase):
REQUIRED_PARAMS = {
'api_username': 'rw',
... |
import unittest
import numpy as np
import six
import chainer
from chainer import cuda
import chainer.functions as F
from chainer import optimizers
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
class LinearModel(object):
UNIT_NUM = 10
BATCH_SIZE = 32
E... |
import math
import random
def rselect(array_to_search, n):
"""
Returns the nth order statistic from the array provided.
"""
return rselect_internal(array_to_search, n, 0, len(array_to_search))
def rselect_internal(search_array, n, start_index, end_index):
"""
Recursively computes the nth order... |
"""
Support for interacting with Snapcast clients.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.snapcast/
"""
import logging
import socket
import voluptuous as vol
from homeassistant.components.media_player import (
SUPPORT_VOLUME_MU... |
"""Tests pageBreakBefore, frameBreakBefore, keepWithNext...
"""
__version__='''$Id: test_platypus_breaking.py 3703 2010-04-14 17:13:51Z rgbecker $'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, printLocation
setOutDir(__name__)
import sys, os, time
from string import split, strip, joi... |
# -*- coding: utf-8 -*-
"""
pygments.formatters._mapping
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Formatter mapping defintions. This file is generated by itself. Everytime
you change something on a builtin formatter defintion, run this script from
the formatters folder to update it.
Do not alter the FORMA... |
from openerp import models
from openerp.tools import mute_logger
from openerp.osv.orm import except_orm
from openerp.tests import common
class TestAPI(common.TransactionCase):
""" test the new API of the ORM """
def assertIsRecordset(self, value, model):
self.assertIsInstance(value, models.BaseModel)... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
#
# Copyright (C) 2017 Lenovo, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.aruba import aruba_command
from units.modules.utils import set_module_args
from .aruba_module import TestArubaModule, load_fixture
class TestAr... |
"""Operations for constructing RaggedTensors."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import o... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
EXAMPLES = r'''
- name: Enable vvold rule set for all ESXi Host in given Cluster
vmware_host_firewall_manager:
ho... |
#!/usr/bin/env python3
from pgmpy.base import UndirectedGraph
from pgmpy.exceptions import CardinalityError
from collections import defaultdict
import numpy as np
class JunctionTree(UndirectedGraph):
"""
Class for representing Junction Tree.
Junction tree is undirected graph where each node represents a... |
from pyspark.ml.classification import MultilayerPerceptronClassifier
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder.appName("multilayer_perceptron_classification_example").get... |
"""Make a mapping from body part words to categories.
Make mapping <body part word> -> [historic words] based on Inger Leemans'
clustering.
Usage: python make_body_part_mapping.py
Requires files body_part_clusters_renaissance.csv,
body_part_clusters_classisism.csv, and body_part_clusters_enlightenment.csv to
be in t... |
# coding: utf-8
from __future__ import unicode_literals
import itertools
import re
from .common import InfoExtractor
from ..compat import (
compat_str,
compat_urllib_parse_unquote,
compat_urlparse
)
from ..utils import (
extract_attributes,
int_or_none,
strip_or_none,
unified_timestamp,
)
... |
from openerp.osv import orm, fields
class SelectTaxes(orm.TransientModel):
_name = 'account.update.tax.select_taxes'
_description = 'Select the taxes to be updated'
_rec_name = 'type_tax_use' # wha'evar
def save_taxes(self, cr, uid, ids, context=None):
"""
Create tax lines in the upd... |
"""
Test the course_info xblock
"""
import mock
from nose.plugins.attrib import attr
from urllib import urlencode
from django.conf import settings
from django.core.urlresolvers import reverse
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from util.date_utils import strftime_localized
from xmodule.modu... |
from django import template
from django.conf import settings
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required, permission_required
from utils import next_redirect, confirmation_view
from django.contrib import comments
from django.contrib.commen... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 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")
http:... |
"""Python compatibility wrappers."""
from __future__ import absolute_import
import sys
from struct import pack
try:
MAX_INT = sys.maxsize
except AttributeError:
MAX_INT = sys.maxint
MAX_INT64 = (1 << 63) - 1
MAX_INT32 = (1 << 31) - 1
MAX_INT16 = (1 << 15) - 1
# Determine the word size of the processor.
if ... |
#!/usr/bin/python
# This is a simple example showing how you can send a key press event
# to XBMC in a non-queued fashion to achieve a button pressed down
# event i.e. a key press that repeats.
# The repeat interval is currently hard coded in XBMC but that might
# change in the future.
# NOTE: Read the comments in '... |
"""
:mod: RSSCache
Extension of DictCache to be used within RSS
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = '$Id$'
import datetime
import threading
import time
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities.DictCache import... |
import re
import logging
from threading import RLock
from itertools import count
from collections import defaultdict
from sqlalchemy.orm import joinedload
from aleph.core import db
from aleph.text import normalize_strong
from aleph.model import Reference, Entity
from aleph.analyze.analyzer import Analyzer
log = logg... |
"""
The vyos lldp_global fact class
It is in this file the configuration is collected from the device
for a given resource, parsed, and the facts tree is populated
based on the configuration.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from re import findall, M
from copy ... |
import logging
import simplejson as json
from time import sleep
from nose.tools import nottest
from onlinelinguisticdatabase.tests import TestController, url
import onlinelinguisticdatabase.model as model
from onlinelinguisticdatabase.model.meta import Session
import onlinelinguisticdatabase.lib.helpers as h
from onlin... |
"""
A sample app that is able to exit and spit out specific messages on stdout
and stderr exactly as asked for.
This is used for testing the socorro.cron.base.SubprocessMixin class
To test this app run it like this::
$ ./sampleapp.py 1 foo bar 1> out.log 2> err.log
$ echo $?
1
$ cat out.log
foo
... |
import os_client_config
from os_client_config import exceptions
def main():
module = AnsibleModule(argument_spec=dict(
clouds=dict(required=False, default=[]),
))
p = module.params
try:
config = os_client_config.OpenStackConfig()
clouds = []
for cloud in config.get_all_... |
"""Tests for record_input_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.framework import test_util
from tensorflow.python.framework.errors_impl import NotFoundError
from tensorflow.python.lib.io import tf_record
fr... |
"""
Utilities for creating public APIs (e.g. argument validation decorators).
"""
from zipline.utils.input_validation import preprocess
def restrict_to_dtype(dtype, message_template):
"""
A factory for decorators that restrict Term methods to only be callable on
Terms with a specific dtype.
This is c... |
import uuid
from openstack_dashboard.test import helpers as test
from openstack_dashboard.utils import filters
class UtilsFilterTests(test.TestCase):
def test_accept_valid_integer(self):
val = 100
ret = filters.get_int_or_uuid(val)
self.assertEqual(val, ret)
def test_accept_valid_int... |
import os
import operator
def get_seq(f_path, start, end):
with open(f_path, "rb") as data:
bytes = data.read()
return bytes[start:end]
def get_seq_reversed(f_path, start, end):
with open(f_path, "rb") as data:
bytes = data.read()
bytes = bytes[::-1]
return bytes[start:end]
def process(folder, start=0,... |
from datetime import timedelta, datetime
from six import iteritems, itervalues
from functools import partial
from .search import Search
from .aggs import A
from .utils import AttrDict
from .result import Response
from .query import Q
__all__ = ['FacetedSearch', 'HistogramFacet', 'TermsFacet', 'DateHistogramFacet', 'R... |
"""Caching loader for the 20 newsgroups text classification dataset
The description of the dataset is available on the official website at:
http://people.csail.mit.edu/jrennie/20Newsgroups/
Quoting the introduction:
The 20 Newsgroups data set is a collection of approximately 20,000
newsgroup documents,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from megacosm.generators import MundaneItem
import unittest2 as unittest
from pprint import pprint
import redis
from config import IntegrationTestConfiguration
class TestMundaneItemIntegration(unittest.TestCase):
def setUp(self):
self.redis = redis.from_ur... |
# -*- coding: 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 unique constraint on 'Tag', fields ['name']
db.create_unique('taggit_tag', ['name'])
def back... |
from anibots import *
import breve
class AnibotPhysicsSim( breve.PhysicalControl ):
def __init__( self ):
breve.Control.__init__( self )
self.bots = breve.objectList()
self.actionDuration = 45
self.iterCount=self.actionDuration
self.videoLog = breve.Movie()
self.block = None
#configure the anibots
... |
"""Tests for IPython.utils.importstring."""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-------... |
import pytest
import numpy as np
from zoo.chronos.model.forecast.tcmf_forecaster import TCMFForecaster
from unittest import TestCase
import tempfile
import pandas as pd
class TestChronosModelTCMFForecaster(TestCase):
def setUp(self):
self.model = TCMFForecaster()
self.num_samples = 300
se... |
import cPickle
import logging
import pickle
from datetime import datetime
from beaker.container import OpenResourceNamespaceManager, Container
from beaker.exceptions import InvalidCacheBackendError, MissingCacheParameter
from beaker.synchronization import file_synchronizer, null_synchronizer
from beaker.util import ve... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsFieldMapping widget and model.
.. 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 lat... |
from LSP.plugin.core.configurations import ConfigManager
from LSP.plugin.core.configurations import is_supported_syntax
from LSP.plugin.core.configurations import WindowConfigManager
from test_mocks import MockView
from test_mocks import MockWindow
from test_mocks import TEST_CONFIG, DISABLED_CONFIG
from test_mocks imp... |
"""Test cases for usage of polysquarecmakelinter.main()."""
from artificialintelligence.knapsack import (knapsack,
items_for_knapsack)
from nose_parameterized import parameterized, param
from testtools import TestCase
from collections import namedtuple
Item = namedtuple... |
# -*- coding: utf-8 -*-
import functools
import hashlib
import logging
import threading
import binascii
from collections import OrderedDict
import os
from celery.local import PromiseProxy
from gevent.pool import Pool
from website import settings
_local = threading.local()
logger = logging.getLogger(__name__)
def po... |
from django.conf.urls import patterns, url
from views import *
from django.views.generic.base import RedirectView
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', browse,name='browse.browse... |
import os
from telemetry.core import util
# TODO(dtu): Move these functions from core.util to here.
GetBaseDir = util.GetBaseDir
GetTelemetryDir = util.GetTelemetryDir
GetUnittestDataDir = util.GetUnittestDataDir
GetChromiumSrcDir = util.GetChromiumSrcDir
AddDirToPythonPath = util.AddDirToPythonPath
GetBuildDirector... |
import unittest
from test import support
from weakref import proxy, ref, WeakSet
import operator
import copy
import string
import os
from random import randrange, shuffle
import sys
import warnings
import collections
from collections import UserString as ustr
import gc
import contextlib
class Foo:
pass
class Ref... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import collections
import os
import time
from multiprocessing import Lock
from itertools import chain
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.plugins.cache.base import BaseCacheModul... |
"""Quotas for instances, volumes, and floating ips."""
import sys
from oslo_config import cfg
from oslo_log import log as logging
from oslo_log import versionutils
from oslo_utils import importutils
import six
import webob
from neutron._i18n import _, _LI, _LW
from neutron.common import exceptions
from neutron.db.qu... |
"""Converts a prompts file in TSV format to Festival's Scheme format.
"""
from __future__ import unicode_literals
import io
STDIN = io.open(0, mode='rt', encoding='utf-8', closefd=False)
STDOUT = io.open(1, mode='wt', encoding='utf-8', closefd=False)
def main(unused_args):
for line in STDIN:
line = line.rstr... |
from __future__ import unicode_literals
from unittest import skipUnless
from django.contrib.gis.tests.utils import HAS_SPATIAL_DB, mysql
from django.db import connection, migrations, models
from django.db.migrations.migration import Migration
from django.db.migrations.state import ProjectState
from django.test import... |
"""Tests for cli_config."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
import shutil
import tempfile
from tensorflow.python.debug.cli import cli_config
from tensorflow.python.framework import test_util
from tensorflow.python.platf... |
#!/usr/bin/env python2.7
# usage: mibview.py [-h] mibString
#
# Convert wildcarded OID MIB views into OID/mask format as used by EXOS.
#
# positional arguments:
# mibString Wildcard MIB string to be translated into OID/mask format
#
# optional arguments:
# -h, --help show this help message and exit
import a... |
"""
Exceptions and errors for use in twisted.internet modules.
"""
from __future__ import division, absolute_import
import socket
from twisted.python import deprecate
from twisted.python.versions import Version
class BindError(Exception):
"""An error occurred binding to an interface"""
def __str__(self):... |
import editdist
import unittest
import random
test_vectors = (
( 'abc', 'abc', 0 ),
( 'abc', 'ab', 1 ),
( 'abc', 'abcd', 1 ),
( 'abc', 'bc', 1 ),
( 'abc', 'a', 2 ),
( 'abc', '', 3 ),
( '', '', 0 ),
( 'abc', 'acx', 2 ),
( 'abc', 'acxx', 3 ),
( 'abc', 'bcd', 2 ),
( 'a' * 1000, 'a' * 1000, 0 ),
(... |
"""
This module defines client fixtures that can be used to target the
Neutron API via different methods.
"""
import abc
import fixtures
import six
from neutron.common import exceptions as n_exc
from neutron import context
from neutron import manager
from neutron.tests import base
from neutron.tests.unit import test... |
import os
import traceback
def main():
module = AnsibleModule(
argument_spec=dict(
service=dict(default=None, required=True),
short_service_name=dict(required=False),
warn_over=dict(default=15, required=False),
crit_over=dict(default=30, required=False),
... |
import py
import pytest
from py._iniconfig import IniConfig, ParseError, __all__ as ALL
from py._iniconfig import iscommentline
from textwrap import dedent
def pytest_generate_tests(metafunc):
if 'input' in metafunc.funcargnames:
for name, (input, expected) in check_tokens.items():
metafunc.add... |
from __future__ import print_function
def get_sys_info():
import sys
import distutils.sysconfig
import imp
print("exec_prefix:%s" % sys.exec_prefix)
print("short_version:%s" % sys.version[:3])
print("long_version:%s" % sys.version.split()[0])
print("py_inc_dir:%s" % distutils.sysconfig.get... |
from __future__ import absolute_import, division, print_function
from fractions import Fraction
import sys
import subprocess
sys.path.insert(0, '../')
from compiler import *
from constructs import *
def test_tree_graph():
R = Parameter(Int, "R")
C = Parameter(Int, "C")
x = Variable(Int, "x")
y = Va... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class Canalc2IE(InfoExtractor):
IE_NAME = 'canalc2.tv'
_VALID_URL = r'http://.*?\.canalc2\.tv/video\.asp\?.*?idVideo=(?P<id>\d+)'
_TEST = {
'url': 'http://www.canalc2.tv/video.asp?idVideo=12163&v... |
"""
WebSubmit Metadata Plugin - This is the generic metadata extraction
plugin. Contains methods to extract metadata from many kinds of files.
Dependencies: extractor
"""
__plugin_version__ = "WebSubmit File Metadata Plugin API 1.0"
import extractor
from invenio.legacy.bibdocfile.api import decompose_file
def can_r... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import generics
from rest_framework import serializers as ser
from api.base import utils
from api.base.exceptions import Conflict
from api.base.exceptions import JSONAPIAttributeException
from api.base.serializers import JSONAPISerial... |
from __future__ import unicode_literals
import datetime
import os
import subprocess
from django.utils.lru_cache import lru_cache
def get_version(version=None):
"Returns a PEP 386-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version num... |
"""Tests for hashing layer."""
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_spec
from tenso... |
from panda3d.core import *
from direct.showbase.DirectObject import DirectObject
from DirectUtil import *
from DirectGeometry import *
class DirectGrid(NodePath, DirectObject):
def __init__(self,gridSize=100.0,gridSpacing=5.0,planeColor=(0.5,0.5,0.5,0.5),parent = None):
# Initialize superclass
Node... |
from __future__ import unicode_literals
import collections
import os
import pkgutil
import sys
from importlib import import_module
import django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import (
BaseComma... |
from django import forms
from django.forms.util import flatatt
from django.utils.encoding import force_unicode
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from wiki.editors.base import BaseEditor
class MarkItUpAdminWidget(forms.Widget):
"""A simplified more fail-... |
#!/usr/bin/env python
"""wrapper.py implements an end-to-end wrapper that classifies an image read
from disk, using the imagenet classifier.
"""
import numpy as np
import os
from skimage import io
from skimage import transform
import caffe
IMAGE_DIM = 256
CROPPED_DIM = 227
# Load the imagenet mean file
IMAGENET_MEA... |
import re
# TODO: Import the spanner module
from google.cloud import spanner
# END TODO
"""
Get spanner management objects
"""
# TODO: Create a spanner Client
spanner_client = spanner.Client()
# END TODO
# TODO: Get a reference to the Cloud Spanner quiz-instance
instance = spanner_client.instance('quiz-instan... |
from django.apps import apps
from django.contrib.auth.models import Permission
from django.db.models import Q
from openslides.utils.auth import GROUP_ADMIN_PK, GROUP_DEFAULT_PK
from openslides.utils.postgres import restart_id_sequence
from .models import Group, User
def get_permission_change_data(sender, permission... |
from aol_model.aod import Aod
from aol_model.ray import Ray
from numpy import sqrt, allclose, cross, dot
from aol_model.vector_utils import normalise
aod = Aod([0,0,1], [1,0,0], 1, 1, 1)
def test_on_axis_ray_displacement():
rays = [Ray([0,0,0],[0,0,1],800e-9,1)]*5
aod.move_ray_through_aod(rays)
still_on_a... |
import logging
from django.core.exceptions import ObjectDoesNotExist
from synnefo.db.models import Volume
from astakos.im.models import AstakosUser, Project
from synnefo_admin.admin.exceptions import AdminHttp404
from synnefo_admin.admin.utils import create_details_href
def get_volume_or_404(query):
try:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2017-2018 Alan Frost. All rights reserved.
Generate static image gallery HTML as masonary layout or carousel
> python gallery.py -t "Susan Frost's Gallery" -p index.html masonary > t
> python gallery.py -t "Susan Frost's Gallery" -p gallery.html gallery... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.nxos import nxos_vpc_interface
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosVpcModule(TestNxosModule):
module = nxos_vp... |
"""Testing for Gaussian process regression """
# Licence: BSD 3 clause
import numpy as np
from scipy.optimize import approx_fprime
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels \
import RBF, ConstantKernel as C, WhiteKernel
from sklearn.utils.testing \
... |
"""Defines interface for DB access.
The underlying driver is loaded as a :class:`LazyPluggable`.
Functions in this module are imported into the nova.virt.baremetal.db
namespace. Call these functions from nova.virt.baremetal.db namespace, not
the nova.virt.baremetal.db.api namespace.
All functions in this module retu... |
'''
mobilenet
Suittable for image with around resolution x resolution, resolution is multiple of 32.
Reference:
MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications
https://arxiv.org/abs/1704.04861
'''
__author__ = 'qingzhouzhen'
__date__ = '17/8/5'
__modify__ = 'dwSun'
__modified_date__... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import Http404, HttpResponseRedirect
from django.views.generic import list_detail
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.urlresolver... |
#!/usr/bin/env python3
from sys import exit
from test.http_test import HTTPTest
from misc.wget_file import WgetFile
"""
This test ensures that Wget handles a 504 Gateway Timeout response
correctly.
Since, we do not have a direct mechanism for conditionally sending responses
via the HTTP Server, I've us... |
import numpy, os, sys, unittest
sys.path.append("@CMAKE_LIBRARY_OUTPUT_DIRECTORY@")
import bornagain as ba
class Shape2DTest(unittest.TestCase):
def test_constructPolygonFromList(self):
"""
Testing construction of polygon from two Numpy arrays
"""
# initializing from list
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.