content stringlengths 4 20k |
|---|
from pypov.pov import Texture, Pigment, Intersection, Cylinder, Torus
from pypov.pov import Union, Difference, Object, Box, Sphere, Merge, Isosurface
from pypov.common import grey, white
from pypov.colors import Colors
from lib.base import ten_by_ten
from lib.textures import cross_hatch, cross_hatch_2, wall_texture_1,... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import base64
from .common import InfoExtractor
from ..compat import compat_urllib_parse_unquote
from ..utils import (
ExtractorError,
parse_iso8601,
parse_duration,
)
class XuiteIE(InfoExtractor):
IE_DESC = '隨意窩Xuite影音'
_REGEX_BASE... |
# -*- coding: utf-8 -*-
"""{{ cookiecutter.repo_name }} URL Configuration
https://docs.djangoproject.com/en/1.8/topics/http/urls/
"""
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.s... |
from sqlalchemy import MetaData, Table, Column, Boolean
meta = MetaData()
def upgrade(migrate_engine):
meta.bind = migrate_engine
records_table = Table('records', meta, autoload=True)
disabled = Column('disabled', Boolean(), server_default='0')
disabled.create(records_table)
def downgrade(migrat... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from six import iteritems, string_types
from ansible.errors import AnsibleParserError
from ansible.plugins import module_loader
from ansible.parsing.splitter import parse_kv, split_args
from ansible.template import Templar
# For ... |
"""Tests for `tf.data.Dataset.interleave()`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import datase... |
"""
Demo platform for the rollor shutter component.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
from homeassistant.components.rollershutter import RollershutterDevice
from homeassistant.helpers.event import track_utc_time_change
def setup_pla... |
"""
===========================================
Robust linear model estimation using RANSAC
===========================================
In this example we see how to robustly fit a linear model to faulty data using
the RANSAC algorithm.
"""
import numpy as np
from matplotlib import pyplot as plt
from sklearn import ... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
ExtractorError,
parse_iso8601,
)
class DRTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?dr\.dk/tv/se/(?:[^/]+/)*(?P<id>[\da-z-]+)(?:[/#?]|$)'
_TEST = {
'url': 'https://www.... |
"""Handle version information related to Visual Stuio."""
import errno
import os
import re
import subprocess
import sys
import gyp
import glob
class VisualStudioVersion(object):
"""Information regarding a version of Visual Studio."""
def __init__(self, short_name, description,
solution_version, p... |
from io import BytesIO
import posixpath
from zipfile import ZipFile
from compiled_file_system import SingleFile
class DirectoryZipper(object):
'''Creates zip files of whole directories.
'''
def __init__(self, compiled_fs_factory, file_system):
self._file_system = file_system
self._zip_cache = compiled... |
import datetime
import mock
from nova import objects
from nova import servicegroup
from nova import test
class DBServiceGroupTestCase(test.NoDBTestCase):
def setUp(self):
super(DBServiceGroupTestCase, self).setUp()
self.down_time = 15
self.flags(service_down_time=self.down_time,
... |
"""The tests for the DTE Energy Bridge."""
import unittest
import requests_mock
from homeassistant.setup import setup_component
from tests.common import get_test_home_assistant
DTE_ENERGY_BRIDGE_CONFIG = {
'platform': 'dte_energy_bridge',
'ip': '192.168.1.1',
}
class TestDteEnergyBridgeSetup(unittest.Tes... |
from __future__ import absolute_import, unicode_literals
import logging
from celery import shared_task
from django.conf import settings
from django.utils import timezone
from requests.exceptions import HTTPError
from extralifeapi.donors import Donations
from ..models import *
log = logging.getLogger("donations")
... |
{
'name': 'CRM Gamification',
'version': '1.0',
'author': 'OpenERP SA',
'category': 'hidden',
'depends': ['gamification','sale_crm'],
'website' : 'https://www.odoo.com/page/gamification',
'description': """Example of goal definitions and challenges that can be used related to the usage of th... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
from copy import deepcopy
from ansible import constants as C
from ansible.module_utils._text import to_text
from ansible.module_utils.six import string_types
from ansible.plugins.loader import connection_loade... |
"""
Utils
Created on'17/06/15'
__author__='algarecu'
__email__='<EMAIL>'
"""
#Taken from https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py
class bcolors:
RED='\033['
OKGREEN='\033[92m'
WARNING='\033[93m'
BGGREEN='\033[42m' #backgroundtogreen
BGWHITE=... |
"""
Metric class used in monitor mixin framework.
"""
import numpy
class Metric(object):
"""
A metric computed over a set of data (usually from a `CountsTrace`).
"""
def __init__(self, monitor, title, data):
"""
@param monitor (MonitorMixinBase) Monitor Mixin instance that generated
... |
"""Tests for nets.inception_v1."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
# TODO: #6568 Remove this hack that makes dlopen() not crash.
if hasattr(sys, 'getdlopenflags') and hasattr(sys, 'setdlopenflags'):
import ctypes
sys.setdlope... |
from math import ceil
class InvalidPage(Exception):
pass
class PageNotAnInteger(InvalidPage):
pass
class EmptyPage(InvalidPage):
pass
class Paginator(object):
def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True):
self.object_list = object_list
self.per_pa... |
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.parties.WinterPartyCatchActivityToonSD
from panda3d.direct import WaitInterval
from panda3d.core import Vec4
import PartyCatchActivityToonSD
from direct.directnotify import DirectNotifyGlobal
from direct.interval.IntervalGlobal import Sequence, Pa... |
#
# objdoc: epydoc documentation completeness checker
# Edward Loper
#
# Created [01/30/01 05:18 PM]
# $Id: checker.py 1366 2006-09-07 15:54:59Z edloper $
#
"""
Documentation completeness checker. This module defines a single
class, C{DocChecker}, which can be used to check the that specified
classes of objects are d... |
from .. import matrix
def verify_matrix_output_diversity(res):
"""
Verifies that the size of the matrix passed matches the number of unique
outputs from res.index
"""
sz = res.size()
s = frozenset([matrix.generate_lists(res.index(i)) for i in range(sz)])
for i in range(res.size()):
... |
"""A module to ease code analysis
This module is here to help source code analysis.
"""
import re
from rope.base import codeanalyze, utils
@utils.cached(7)
def real_code(source):
"""Simplify `source` for analysis
It replaces:
* comments with spaces
* strs with a new str filled with spaces
* im... |
"""
Annotations Tool Mixin
This file contains global variables and functions used in the various Annotation Tools.
"""
from lxml import etree
from urlparse import urlparse
from os.path import splitext, basename
from HTMLParser import HTMLParser
def get_instructions(xmltree):
""" Removes <instructions> from the xm... |
from ebs_deploy import out, parse_env_config
def add_arguments(parser):
"""
Args for the delete environment command
"""
parser.add_argument('-e', '--environment',
help='Environment name', required=True)
parser.add_argument('-w', '--dont-wait',
help='... |
"""
Prints a comparison between different serializers.
Compares results based on size of the output, and time taken to (de)serialize.
"""
from __future__ import print_function
from timeit import default_timer as perf_timer
import sys
import datetime
import decimal
import uuid
import Pyro4.util
import Pyro4.errors
impo... |
from os.path import dirname, join
import tornado
from labcontrol.db import settings as labcontrol_settings
from labcontrol.gui.handlers.base import IndexHandler, NotFoundHandler
from labcontrol.gui.handlers.auth import LoginHandler, LogoutHandler, AccessHandler
from labcontrol.gui.handlers.plate import (
PlateMap... |
#!/usr/bin/python
"""
Detect which x86 CPU extension instructions the given scipy install uses.
This file can be used in the release process to check that the nosse installer
does not contain SSE instructions. This has happened before, see for example
ticket #1170.
Is meant to be run on OS X with Wine. Make sure objdu... |
import unittest
from apache_beam.metrics.cells import CellCommitState
from apache_beam.metrics.execution import MetricsContainer
from apache_beam.metrics.execution import ScopedMetricsContainer
from apache_beam.metrics.execution import MetricsEnvironment
from apache_beam.metrics.execution import MetricKey
from apache_... |
import SR, VDI, SRCommand, util, lvutil
import errno
import os, sys, time
import xml.dom.minidom
import xmlrpclib
import xs_errors
CAPABILITIES = ["SR_PROBE","VDI_CREATE","VDI_DELETE","VDI_ATTACH","VDI_DETACH",
"VDI_ACTIVATE","VDI_DEACTIVATE","VDI_CLONE","VDI_SNAPSHOT","VDI_RESIZE",
"VD... |
import mock
from oslo_config import cfg
from nova import context
from nova import objects
from nova import test
from nova.tests import fixtures
from nova.tests.unit import cast_as_call
from nova.tests.unit import fake_network
from nova.tests.unit import fake_server_actions
CONF = cfg.CONF
class ComputeManagerTestC... |
#!/usr/bin/env python
import pickle
import gauss_node
import numpy
def load_data(filename):
src = open(filename, "r")
X, Y = eval(src.readline())
src.close()
return X, Y
def main():
print "Loading data..."
X, Y = load_data("training_set.py")
print "len(X):", len(X), "len(X[0]):", len(X[0]), "len(Y):", len(... |
# coding=utf-8
import Queue
import cookielib
import threading
import urllib
import urllib2
from HTMLParser import HTMLParser
# general settings
user_thread = 10
username = "admin"
wordlist_file = "/tmp/cain.txt"
resume = None
# target specific settings
target_url = "http://192.168.112.131/administrator/index.php"
tar... |
from tests import clear_staging_env, staging_env, eq_, \
assert_raises_message
from alembic import util
env = None
a, b, c, d, e = None, None, None, None, None
cfg = None
def setup():
global env
env = staging_env()
global a, b, c, d, e
a = env.generate_revision(util.rev_id(), '->a', refresh=True)
... |
import scipy
import numpy
import scipy.sparse.linalg
#import pymining module
from matrix import *
from scipy_interface import *
class Pca:
def __init__(self):
self.isTrained = False
self.haveColSpace = False
self.haveRowSpace = False
self.colSpaceTrans = None
self.rowSpaceT... |
__doc__="""cpqScsiPhyDrv
cpqScsiPhyDrv is an abstraction of a HP SCSI Hard Disk.
$Id: cpqScsiPhyDrv.py,v 1.1 2010/06/30 16:29:32 egor Exp $"""
__version__ = "$Revision: 1.1 $"[11:-2]
from HPHardDisk import *
class cpqScsiPhyDrv(HPHardDisk):
"""cpqScsiPhyDrv object
"""
statusmap ={1: (DOT_GREY, SEV_WAR... |
import argparse
import copy
import os
import string
import sys
import llnl.util.tty as tty
from llnl.util.filesystem import set_executable
import spack.repo
import spack.store
import spack.build_systems.cmake
import spack.cmd
import spack.cmd.install as install
import spack.cmd.common.arguments as arguments
from spac... |
from twisted.trial import unittest
from twisted.internet import task, defer
from buildbot.schedulers import timed
from buildbot.test.util import scheduler
class Timed(scheduler.SchedulerMixin, unittest.TestCase):
OBJECTID = 928754
def setUp(self):
self.setUpScheduler()
def tearDown(self):
... |
import numpy as n
from scipy.io import wavfile as w
# auxiliary functions __n and __s.
# These only normalize the sonic vectors and
# write them as 16 bit, 44.1kHz WAV files.
def __n(sonic_array):
"""Normalize sonic_array to have values only between -1 and 1"""
t = sonic_array
if n.all(sonic_array==0):
... |
from .jarmgr import *
from .jarmgr import _MY_DIR
from .pom import *
from .docker import docker_file
import platform
import os
import warnings
import os
from subprocess import call as py_call
import json
def call(arglist):
error = py_call(arglist)
if error:
raise Exception('Subprocess e... |
"""Test runner for TensorFlow tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import shlex
from string import maketrans
import sys
import time
from google.protobuf import json_format
from google.protobuf import text_form... |
from keystone.common import sql
from keystone import exception
from keystone.i18n import _
class ProjectEndpoint(sql.ModelBase, sql.ModelDictMixin):
"""project-endpoint relationship table."""
__tablename__ = 'project_endpoint'
attributes = ['endpoint_id', 'project_id']
endpoint_id = sql.Column(sql.Str... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .turner import TurnerBaseIE
from ..utils import (
ExtractorError,
int_or_none,
)
class AdultSwimIE(TurnerBaseIE):
_VALID_URL = r'https?://(?:www\.)?adultswim\.com/videos/(?P<is_playlist>playlists/)?(?P<show_path>[^/]+)/(?P<episode_pa... |
"""illustrates a quick and dirty way to persist an XML document expressed using ElementTree and pickle.
This is a trivial example using PickleType to marshal/unmarshal the ElementTree
document into a binary column. Compare to explicit.py which stores the individual components of the ElementTree
structure in distinct ... |
# -*- coding: utf-8 -*-
import logging
import os
import time
from os import listdir
from os.path import join
from threading import Thread, Lock
from select import select
from Queue import Queue, Empty
import openerp
import openerp.addons.hw_proxy.controllers.main as hw_proxy
from openerp import http
from openerp.http ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
from ansible.module_utils.basic import AnsibleModule
decimal_point = re.compile(r... |
# Test interfaces to fortran blas.
#
# The tests are more of interface than they are of the underlying blas.
# Only very small matrices checked -- N=3 or so.
#
# !! Complex calculations really aren't checked that carefully.
# !! Only real valued complex numbers are used in tests.
from numpy import float32, float64, co... |
import time
DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def is_leap(year):
return (year % 4) == 0
def test():
seconds = 0
wday = 5 # Jan 1, 2000 was a Saturday
for year in range(2000, 2049):
print("Testing %d" % year)
yday = 1
for month in range(1, ... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
class Position(object):
'''
Keeps and updates the size and price of a position. The object has no
relationship to any asset. It only keeps size and price.
Member Attributes:
- size (int)... |
import sys
import traceback
import time
import struct
import threading
import os
if os.path.exists("../../lib/python"):
sys.path.append("../PS3 BD Remote")
sys.path.append("../../lib/python")
from bt.hid import HID
from bt.bt import bt_lookup_name
from xbmcclient import XBMCClient
from ps3 impo... |
# flake8: noqa
import subprocess
import sys
import unittest
_import_everything = b"""
# The event loop is not fork-safe, and it's easy to initialize an asyncio.Future
# at startup, which in turn creates the default event loop and prevents forking.
# Explicitly disallow the default event loop so that an error will be r... |
#!/usr/bin/python3
import requests
import argparse
import sys
def err(msg, *args):
print('error:', msg % args, file = sys.stderr)
token = open('token').read().strip()
URL = 'https://api.github.com/repos/{owner}/{repo}/collaborators/{username}?access_token=' + token
parser = argparse.ArgumentParser(description ... |
"""
Latent Dirichlet Allocation (LDA) in Python, using all CPU cores to parallelize and
speed up model training.
The parallelization uses multiprocessing; in case this doesn't work for you for
some reason, try the :class:`gensim.models.ldamodel.LdaModel` class which is an
equivalent, but more straightforward and singl... |
#!/usr/bin/env python
import pytest
from utils import *
from fireplace.dsl import *
from fireplace.exceptions import *
from fireplace.card import Card
def test_selector():
game = prepare_game()
game.player1.discard_hand()
alex = game.player1.give("EX1_561")
selector = PIRATE | DRAGON + MINION
assert len(selector... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class TopUp(Choreography):
def __init__(self, temboo_session):
"""
Create a new ins... |
## Generalized Linear Models (Formula)
# This notebook illustrates how you can use R-style formulas to fit Generalized Linear Models.
#
# To begin, we load the ``Star98`` dataset and we construct a formula and pre-process the data:
from __future__ import print_function
import statsmodels.api as sm
import statsmodels... |
"""
Tests for users API
"""
import datetime
from django.utils import timezone
from xmodule.modulestore.tests.factories import ItemFactory, CourseFactory
from student.models import CourseEnrollment
from certificates.models import CertificateStatuses
from certificates.tests.factories import GeneratedCertificateFactory
... |
from PyQt4.QtCore import QPoint
from PyQt4.QtGui import QPainter
def blit_opaque(target, brush, x, y):
painter = QPainter(target.get_qimage())
painter.setCompositionMode(QPainter.CompositionMode_Source)
painter.drawImage(QPoint(x, y), brush.get_qimage())
def blit(target, brush, x, y):
painter = QPai... |
"""
Univariate Kernel Density Estimators
References
----------
Racine, Jeff. (2008) "Nonparametric Econometrics: A Primer," Foundation and
Trends in Econometrics: Vol 3: No 1, pp1-88.
http://dx.doi.org/10.1561/0800000009
https://en.wikipedia.org/wiki/Kernel_%28statistics%29
Silverman, B.W. Density Estimatio... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsDateTimeStatisticalSummary.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later ... |
# Time: O(n)
# Space: O(1)
#
# Given a binary tree, determine if it is a valid binary search tree (BST).
#
# Assume a BST is defined as follows:
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's ... |
import base64
import json
import os
import re
import appengine_wrappers
from extensions_paths import SERVER2
from path_util import IsDirectory
from test_util import ReadFile, ChromiumPath
import url_constants
# TODO(kalman): Investigate why logging in this class implies that the server
# isn't properly caching some ... |
import math
import os
import subprocess
import time
import traceback
from multiprocessing import Pool, cpu_count
from celery import Celery
from celery import states as celery_states
from airflow import configuration
from airflow.config_templates.default_celery import DEFAULT_CELERY_CONFIG
from airflow.exceptions impo... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.cloudstack import (AnsibleCloudStack,
cs_argument_spec,... |
"""Abstract class for RSA."""
from cryptomath import *
class RSAKey:
"""This is an abstract base class for RSA keys.
Particular implementations of RSA keys, such as
L{OpenSSL_RSAKey.OpenSSL_RSAKey},
L{Python_RSAKey.Python_RSAKey}, and
L{PyCrypto_RSAKey.PyCrypto_RSAKey},
inherit from this.
... |
"""Exposes the Python wrapper conversion to trt_graph."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,line-too-long
import six as _six
from tensorflow.contrib.tensorrt.wrap_conversion import calib_convert
from tensorflow.... |
"""
This module is deprecated.
Please use `airflow.providers.microsoft.azure.hooks.azure_container_registry`.
"""
import warnings
# pylint: disable=unused-import
from airflow.providers.microsoft.azure.hooks.azure_container_registry import ( # noqa
AzureContainerRegistryHook,
)
warnings.warn(
"This module is... |
from c7n_azure.provider import resources
from c7n_azure.resources.arm import ArmResourceManager
@resources.register('webapp')
class WebApp(ArmResourceManager):
"""Web Applications Resource
:example:
This policy will find all web apps with 10 or less requests over the last 72 hours
.. code-block:: y... |
import socket
from django.core.mail import mail_admins, mail_managers, send_mail
from django.core.management.base import BaseCommand
from django.utils import timezone
class Command(BaseCommand):
help = "Sends a test email to the email addresses specified as arguments."
missing_args_message = "You must specif... |
# coding: utf8
import re
import uuid
import gluon.contrib.aes as AES
import threading
import os
import base64
class Enc:
def __init__(self, key=''):
self.key = ''
self.set_key(key)
def get_key(self):
if self.key == '':
# Ensure we have a key set
self.set_key()... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('pinax_notifications', '0001_initial'),
migrations.swappable_dependency(... |
from msrest.serialization import Model
class FailoverPolicy(Model):
"""The failover policy for a given region of a database account.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: The unique identifier of the region in which the database
accoun... |
import openerp
from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp.addons.website.controllers.main import Website as controllers
import datetime
import re
import werkzeug.utils
controllers = controllers()
import pytz
from pytz import timezone
class website_event(http.Controll... |
"""Provides a short mapping of all the branches in your local repo, organized
by their upstream ('tracking branch') layout.
Example:
origin/master
cool_feature
dependent_feature
other_dependent_feature
other_feature
Branches are colorized as follows:
* Red - a remote branch (usually the root of all loca... |
from charsetprober import CharSetProber
import constants
# This prober doesn't actually recognize a language or a charset.
# It is a helper prober for the use of the Hebrew model probers
### General ideas of the Hebrew charset recognition ###
#
# Four main charsets exist in Hebrew:
# "ISO-8859-8" - Visual Hebrew
# "w... |
__revision__ = "$Id$"
import string
import os
import time
import calendar
from invenio.config import CFG_SITE_URL, CFG_SITE_LANG, CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS, CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS_CLIENT_IP_DISTRIBUTION, CFG_WEBDIR
from invenio.base.i18n import gettext_set_language
from intbitset import intbitset
fro... |
# goto_assignments command tests are different in syntax
definition = 3
#! 0 ['a = definition']
a = definition
#! []
b
#! ['a = definition']
a
b = a
c = b
#! ['c = b']
c
cd = 1
#! 1 ['cd = c']
cd = c
#! 0 ['cd = e']
cd = e
#! ['module math']
import math
#! ['import math']
math
#! ['import math']
b = math
#! ['b =... |
"""
Benchmark load tests for stubs and collection
The stubs for resources in benchmark such as Regulations are retrieved and it
is followed by a collection get. The batch size for the collection get
(batch_size) and number of test iterations (num_iterations) are configurable.
The iterations of test allows to get ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.vyos import vyos_facts
from units.modules.utils import set_module_args
from .vyos_module import TestVyosModule, load_fixture
class TestVyosFact... |
from __future__ import unicode_literals
from flask import render_template, session
from indico.core import signals
from indico.core.logger import Logger
from indico.core.roles import ManagementRole
from indico.modules.events.abstracts.clone import AbstractSettingsCloner
from indico.modules.events.abstracts.notificati... |
from mongows.mws.db import get_db
from tests import MongoWSTestCase
from mongows.validators.ValidationTest import ValidationTest
class ValidationUtilsTestCase(MongoWSTestCase):
def setUp(self):
class ValidationTestCase(ValidationTest):
def run(self):
pass
self.db = get... |
import unittest
from unittest.mock import Mock
import AbstractPersistence as ap
import HardwareType as ht
import Interactors.HardwareInteractors as hi
import Interactors.Interactor as interactor
class TestDeleteHardwareTypeInteractor(unittest.TestCase):
"""Unit tests for the DeleteHardwareTypeInteractor class"""... |
"""
Linux on Hyper-V and Azure Test Code, ver. 1.0.0
Copyright (c) Microsoft Corporation
All rights reserved
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/LICEN... |
from __future__ import absolute_import
from django.core.management.base import BaseCommand
from zerver.models import UserPresence, UserActivity
from zerver.lib.utils import statsd, statsd_key
from datetime import datetime, timedelta
from collections import defaultdict
class Command(BaseCommand):
help = """Sends... |
import itertools
import re
import os
end_space = re.compile(r"([^\\]\s)*$")
def fnmatch_translate(pat, path_name=False):
parts = []
seq = False
i = 0
if pat[0] == "/" or path_name:
parts.append("^")
any_char = "[^/]"
if pat[0] == "/":
pat = pat[1:]
else:
... |
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT as DF
from odoo.addons import decimal_precision as dp
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.multi
def acti... |
from __future__ import absolute_import
import six
from django.conf import settings
from django.utils.translation import ugettext as _
from sentry.utils.html import escape
from sentry.utils.imports import import_string
def iter_interfaces():
rv = {}
for name, import_path in six.iteritems(settings.SENTRY_IN... |
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
# pylint: disable=redefined-builtin
# pylint: disable=protected-access
# pylint: disable=unused-argument
import os
from path import Path as path
import sys
import mock
MOCK_MODULES = [
'lxml',
'requests',
'xblock',
'xblock.fields',
'xblock.fra... |
from webob import exc
from nova.api.openstack import common
from nova.api.openstack.compute.schemas import networks_associate
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import exception
from nova.i18n import _
from nova import network
ALIAS ... |
from __future__ import unicode_literals
import base64
import logging
import string
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.sessions.exceptions import SuspiciousSession
from django.core.exceptions import SuspiciousOperation
from django.utils import timezone
from dj... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Tests for the engine module
"""
import numpy as np
import scipy.sparse as ssp
from nipype.testing import (assert_raises, assert_equal, assert_true,
assert_false, skipif)
impo... |
from __future__ import unicode_literals
from django.apps.registry import apps as global_apps
from django.db import migrations
from .loader import MigrationLoader
from .recorder import MigrationRecorder
from .state import ProjectState
class MigrationExecutor(object):
"""
End-to-end migration execution - load... |
from sympy import I, Integer
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.state import Bra, Ket, StateBase
def test_innerproduct():
k = Ket('k')
b = Bra('b')
ip = InnerProduct(b, k)
assert isinstance(ip, InnerPr... |
"""Plotting module that can plot 2D and 3D functions
"""
from sympy.utilities.decorator import doctest_depends_on
try:
@doctest_depends_on(modules=('pyglet',))
def PygletPlot(*args, **kwargs):
"""
Plot Examples
=============
See examples/advanced/pyglet_plotting.py for many mo... |
import github.GithubObject
class Download(github.GithubObject.CompletableGithubObject):
"""
This class represents Downloads as returned for example by http://developer.github.com/v3/todo
"""
@property
def accesskeyid(self):
"""
:type: string
"""
self._completeIfNot... |
from manila import exception
from manila import test
from manila import utils
class FakeNotifier(object):
"""Acts like the manila.openstack.common.notifier.api module."""
ERROR = 88
def __init__(self):
self.provided_publisher = None
self.provided_event = None
self.provided_priorit... |
"""Exceptions used throughout package"""
from __future__ import absolute_import
from itertools import chain, groupby, repeat
from pip._vendor.six import iteritems
class PipError(Exception):
"""Base pip exception"""
class InstallationError(PipError):
"""General exception during installation"""
class Unin... |
"""Elpy backend using the Rope library.
This backend uses the Rope library:
http://rope.sourceforge.net/
"""
import os
import time
import traceback
import rope.contrib.codeassist
import rope.base.project
import rope.base.libutils
import rope.base.exceptions
import rope.contrib.findit
from elpy import rpc
import e... |
#!/usr/bin/env python
'''
kicad-footprint-generator 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.
kicad-footprint-generator is distribute... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.