code stringlengths 1 199k |
|---|
"""Schedule for softmax operator"""
import tvm
from .. import generic
from .injective import _schedule_injective
@generic.schedule_softmax.register(["cuda", "gpu"])
def schedule_softmax(outs):
"""Schedule for softmax op.
Parameters
----------
outs: Array of Tensor
The computation graph descrip... |
"""Module to help with parsing and generating configuration files."""
from collections import OrderedDict
from distutils.version import LooseVersion # pylint: disable=import-error
import logging
import os
import re
import shutil
from typing import ( # noqa: F401 pylint: disable=unused-import
Any,
Tuple,
O... |
"""Support for easier dynamic composition of type extensions."""
import inspect
from importlib import import_module
from django.apps import apps
class Composer:
"""Support for easier dynamic composition of type extensions."""
def __init__(self):
"""Construct new composer instance."""
self._disco... |
import numpy as np
from cgpm.dummy.piecewise import PieceWise
from cgpm.utils.general import logsumexp
def test_piecewise_logpdf():
pw = PieceWise([0,1], [2], sigma=1, flip=.8)
# x,z
pw.simulate(None, [0,1], None, {2:1})
pw.logpdf(None, {0:1.5, 1:0}, None, {2:1})
# x
pw.simulate(None, [0], None,... |
"""Test for MovieLens dataset."""
import tensorflow_datasets.public_api as tfds
from tensorflow_datasets.structured import movielens
class MovielensTest(tfds.testing.DatasetBuilderTestCase):
DATASET_CLASS = movielens.Movielens
SPLITS = {
"train": 8,
}
if __name__ == "__main__":
tfds.testing.test_main() |
from daiquiri.core.constants import ACCESS_LEVEL_PUBLIC
from daiquiri.oai.adapter import BaseOaiAdapter
from daiquiri.registry.adapter import RegistryOaiAdapterMixin
from .models import Schema, Table
from .serializers.datacite import (DataciteSchemaSerializer,
DataciteTableSerializer)... |
from dbt.contracts.graph.parsed import ParsedDataTestNode
from dbt.node_types import NodeType
from dbt.parser.base import SimpleSQLParser
from dbt.parser.search import FilesystemSearcher, FileBlock
from dbt.utils import get_pseudo_test_path
class DataTestParser(SimpleSQLParser[ParsedDataTestNode]):
def get_paths(se... |
'''
Support for the Amazon Simple Queue Service.
'''
from __future__ import absolute_import
import logging
import json
import salt.utils
import salt.ext.six as six
log = logging.getLogger(__name__)
_OUTPUT = '--output json'
def __virtual__():
if salt.utils.which('aws'):
# awscli is installed, load the modul... |
"""
Returns a new PDB file only with atoms in common to all input PDB files.
Atoms are judged equal is their name, altloc, res. name, res. num, insertion
code and chain fields are the same. Coordinates are taken from the first input
file. Keeps matching TER/ANISOU records.
Usage:
python pdb_intersect.py <pdb file> ... |
import struct
import loxi
from . import util
import functools
import loxi.generic_util
import sys
ofp = sys.modules['loxi.of13']
class bsn_controller_connection(loxi.OFObject):
def __init__(self, state=None, auxiliary_id=None, role=None, uri=None):
if state != None:
self.state = state
el... |
"""Utilities for key-value format conversions."""
from __future__ import unicode_literals
import logging
import six
from .oidutil import string_to_text
__all__ = ['seqToKV', 'kvToSeq', 'dictToKV', 'kvToDict']
_LOGGER = logging.getLogger(__name__)
class KVFormError(ValueError):
pass
def seqToKV(seq, strict=False):
... |
import json
from urllib.parse import urlparse
from moto.core.responses import BaseResponse
from moto.core.utils import amzn_request_id
from .exceptions import DataBrewClientError
from .models import databrew_backends
class DataBrewResponse(BaseResponse):
SERVICE_NAME = "databrew"
@property
def databrew_back... |
from oslo.config import cfg
from neutron.agent.common import config
from neutron.plugins.common import constants as p_const
from neutron.plugins.openvswitch.common import constants
DEFAULT_BRIDGE_MAPPINGS = []
DEFAULT_VLAN_RANGES = []
DEFAULT_TUNNEL_RANGES = []
DEFAULT_TUNNEL_TYPES = []
ovs_opts = [
cfg.StrOpt('int... |
import re
from JumpScale import j
from JumpScale.portal.macrolib import div_base
from JumpScale.portal.docgenerator.PageHTML import PageHTML
class Confluence2HTML():
def defGet(self, name):
name = name.lower().replace("_", "").replace("-", "").replace(" ", "")
if name in j.portal.tools.defmanager.al... |
'''
uWSGI stats server http://uwsgi-docs.readthedocs.org/en/latest/StatsServer.html
:maintainer: Peter Baumgartner <pete@lincolnloop.com>
:maturity: new
:platform: all
'''
from __future__ import absolute_import
import json
import salt.utils
def __virtual__():
'''
Only load the module if uwsgi is installed
... |
def get_service():
from discovery_doc import build_and_update
return build_and_update('bigquery','v2')
def poll_job(service, projectId, jobId, interval=5, num_retries=5):
import time
job_get = service.jobs().get(
projectId=projectId,
jobId=jobId)
job_resource = job_get.execut... |
"""This API defines FeatureColumn abstraction.
To distinguish the concept of a feature family and a specific binary feature
within a family, we refer to a feature family like "country" as a feature
column. For example "country:US" is a feature which is in "country" feature
column and has a feature value ("US").
Support... |
__author__ = 'Gareth Coles'
class OpusException(Exception):
def __init__(self, code):
from utils.opus.lib import opus
self.code = code
self.message = opus.opus_strerror(self.code).decode("utf-8") |
from django.contrib import admin
from arkestra_utilities.admin_mixins import (
WidgetifiedModelAdmin,
GenericModelForm,
fieldsets,
SupplyRequestMixin
)
from contacts_and_people.admin import PhoneContactInline
from links.admin import ObjectLinkInline
from .models import Study, StudyEntity, StudyType
... |
import boxm_batch;
import sys;
import optparse;
import os;
import glob;
boxm_batch.register_processes();
boxm_batch.register_datatypes();
class dbvalue:
def __init__(self, index, type):
self.id = index # unsigned integer
self.type = type # string
dir = "/Users/isa/Experiments/super3d/scili_experiments_bi... |
from contextlib import contextmanager
from shutil import rmtree
from tempfile import mkdtemp
@contextmanager
def tmpdir(skip_cleanup=False, explicit=None):
"""
Context-manage a temporary directory.
Can be given ``skip_cleanup`` to skip cleanup, and ``explicit`` to choose a
specific location.
(If bot... |
import sys
import time
import math
from dnutils import logs
try:
import numpy
from scipy.optimize import fmin_bfgs, fmin_cg, fmin_ncg, fmin_tnc, fmin_l_bfgs_b, fsolve, fmin_slsqp, fmin, fmin_powell
except:
sys.stderr.write("Warning: Failed to import SciPy/NumPy (http://www.scipy.org)! Parameter learning wit... |
from __future__ import division, print_function
"""
Example of a 2 dimensional root finidng problem (Langmuir).
Parameters taken from GNU GSL Manual
"""
from symneqsys import SimpleNEQSys, Problem
from symneqsys.gsl import GSL_Solver
class LangmuirSys(SimpleNEQSys):
var_tokens = 'K alpha'
def __init__(self, c0,... |
from django.core.management.base import BaseCommand
from django.db import transaction
from django.conf import settings
from onadata.apps.fieldsight.models import Site
from onadata.apps.fsforms.models import FInstance, FieldSightXF
class Command(BaseCommand):
help = 'Create default groups'
def handle(self, *args... |
from setuptools import setup
setup(
setup_requires=['pbr'],
package_dir={'': 'src'},
py_modules=['retrace'],
pbr=True,
) |
from troposphere import Base64, Join, Output, GetAtt, Tags
from troposphere import Parameter, Ref, Template
from troposphere import cloudformation
import troposphere.ec2 as ec2
t = Template()
t.set_description("Configures an EC2 instance using cfn-init configsets")
key_name = t.add_parameter(Parameter(
'KeyName',
... |
import os.path
from setuptools import setup
NAME = "eagexp"
__version__ = None
exec(open(os.path.join(NAME, "about.py")).read())
VERSION = __version__
URL = "https://github.com/ponty/eagexp"
DESCRIPTION = "export eagle schematic or board to image or partlist"
LONG_DESCRIPTION = """export eagle schematic or board to ima... |
import isodate
import datetime
class TimeInformation(object):
"""
Arguments:
* ``extent`` A time extent instance (``TimeExtentValue`` or
``TimeExtentInterval``)
* ``mode`` The layer mode ("single", "range" or "disabled")
"""
def __init__(self):
self.extent = None
... |
from __future__ import absolute_import
from xml.parsers.expat import ExpatError
from xml.dom.minidom import Document
from xml.dom.minidom import parseString
import pytest
from sunpy.util import xml
def test_xml_to_dict1():
"""
should return dict of xml string
"""
source_xml = "<outer>\
<inner1... |
from pysb.testing import *
from pysb.core import *
def test_component_names_valid():
for name in 'a', 'B', 'AbC', 'dEf', '_', '_7', '__a01b__999x_x___':
c = Component(name, _export=False)
eq_(c.name, name)
def test_component_names_invalid():
for name in 'a!', '!B', 'A!bC~`\\', '_!', '_!7', '__a0... |
__author__ = 'Michael Meisinger, Stephen Henrie'
from unittest import SkipTest
from mock import Mock
from unittest import SkipTest
from nose.plugins.attrib import attr
from pyon.ion.resource import lcs_workflows, LCS, LCE, ExtendedResourceContainer, OT, RT, PRED, AS, lcstate, get_object_schema
from pyon.core.bootstrap ... |
from bt import backend_to_check
def test_default():
backend_to_check(None) |
from unidecode import unidecode
from django.template import defaultfilters
def preload_templatetags():
from django.conf import settings
#from django.template.loader import add_to_builtins
from django.template.base import add_to_builtins
import django.template.loader
try:
for lib in settings.... |
from se34euca.lib.EucaUITestLib_Base import *
class EucaUITestLib_Admin_Console(EucaUITestLib_Base):
def test_ui_create_accounts_and_users_via_admin_console(self):
print
print "Started Test: Create Account and Users via Admin Console"
print "Test: Click -> Accounts button"
self.click... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import re
from grako.ast import AST
from grako import grammars as model
class ANTLRSemantics(object):
def __init__(self, name):
self.name = name
self.tokens = {}
def grammar(self, ast):
... |
import os
from typing import Optional
from opensfm import dataset, undistort
from opensfm.dataset import DataSet
def run_dataset(
data: DataSet,
reconstruction: Optional[str] = None,
reconstruction_index: int = 0,
tracks: Optional[str] = None,
output: str = "undistorted",
skip_images: bool = Fal... |
import cortex
import numpy as np
import tempfile
import pytest
from cortex import db, dataset
from cortex.testing_utils import has_installed
subj, xfmname, nverts, volshape = "S1", "fullhead", 304380, (31,100,100)
no_inkscape = not has_installed('inkscape')
def test_braindata():
vol = np.random.randn(*volshape)
... |
N = 10000
M = 50
m = N
for n in range(N):
s1 = str(n)
s2 = s1[::-1]
for i in range(M):
n += int(s2)
s1 = str(n)
s2 = s1[::-1]
if s1 == s2:
m -= 1
break
print m |
from __future__ import print_function, division
import matplotlib.pyplot as plt
import numpy as np
from numpy.testing import assert_allclose
import pytest
from ..optical_properties import OpticalProperties
from ..mean_opacities import MeanOpacities
from ..emissivities import Emissivities
from ...util.functions import v... |
import numpy as np
import math
_use_pysb = False
try:
import pysb.core
import pysb.integrate
_use_pysb = True
except ImportError:
pass
__all__ = ['MCMC', 'MCMCOpts']
class MCMC(object):
"""An interface for Markov-Chain Monte Carlo parameter estimation.
Parameters
----------
options : bay... |
from setuptools import setup, find_packages
version = '0.2a'
install_requires = [
'cliff', # for the CLI
'lxml', # for geocatalogo CSW
'owslib', # for geocatalogo CSW
'prettytable', # for nicely formatted ASCII tables
'pymongo', # for the mongodb-based storage
'requests', # for crawlers
... |
from __future__ import division
import numpy as np
from scipy.interpolate import UnivariateSpline
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.font_manager
import sim
import pro... |
from collections import namedtuple as nt
from parmatter import unformat_lines
from .msh_parmatters import CountLine, NodeLine, ElementLine, BoundaryLine
Mesh = nt('Mesh', 'nodes elements boundaries')
def read(path, validate=False):
'''Create a Mesh object from a .msh file'''
# define which lines are allowed to ... |
"""
@package mi.dataset.driver.camhd_a
@file mi-dataset/mi/dataset/driver/camhd_a/camhd_a_telemetered_driver.py
@author Ronald Ronquillo
@brief Telemetered driver for the camhd_a instrument
Release notes:
Initial Release
"""
from mi.dataset.dataset_parser import DataSetDriverConfigKeys
from mi.dataset.dataset_driver im... |
from __future__ import absolute_import, unicode_literals
ADMIN_MENU_ORDER = (
("Content", ("pages.Page", "blog.BlogPost",
"generic.ThreadedComment", ("Media Library", "fb_browse"),)),
("Site", ("sites.Site", "redirects.Redirect", "conf.Setting")),
("Users", ("auth.User", "auth.Group",)),
("Feedback"... |
import time
import copy
import itertools
import pygame
from pygame.locals import K_h
from .. import LightStim
from Core import Viewport
class ManViewport(Viewport):
# add event control callback
def __init__(self,**kwargs):
super(ManViewport, self).__init__(**kwargs)
self.active = True
se... |
from datetime import timedelta
from django_performance_testing.core import LimitViolationError
from django_performance_testing.timing import \
TimeCollector, TimeLimit
from freezegun import freeze_time
import pytest
def test_it_has_the_correct_collector():
assert TimeLimit.collector_cls == TimeCollector
def tes... |
from modeltranslation.translator import translator, TranslationOptions
from manti_by.apps.gallery.models import Gallery
class GalleryTranslationOptions(TranslationOptions):
fields = ("name",)
translator.register(Gallery, GalleryTranslationOptions) |
import sys
import random
from test_base import *
class TestLock1(TestBase):
def generate(self):
self.clear_tag()
set_index = 0
way_on_locked = self.ways_on_locked
#way_on_locked = random.randint(0,7)
for iteration in range(way_on_locked):
tag = iteration
taddr = self.get_addr(tag, set_... |
"""Python utility to merge many CSV files into a single file.
If there are multiple CSV files with the same TELEMETRY_PAGE_NAME_KEY then the
avg of all values is stored in the resultant CSV file.
"""
import csv
import glob
import optparse
import os
import sys
TELEMETRY_PAGE_NAME_KEY = 'stories'
TELEMETRY_FIELD_NAME_KEY... |
from django.conf.urls.defaults import *
from django.contrib.auth.views import login, logout, password_change, password_change_done
from django.contrib import admin
urlpatterns = patterns('',
url('^create/((?P<url_id>\d+)/){0,1}$',
'token_auth.views.create_token', name='create_token' ),
url('^delete/(?P<... |
from django.conf import settings
from django.core.cache import caches
from django.views.generic import TemplateView, ListView
from django_th.models import TriggerService
import django_th
from th_rss.models import Rss
class MyRssFeed(TemplateView):
"""
page to display its RSS from any service
"""
tem... |
import os
import json
def handle_db_after_an_install(pkg_type, pkg_to_install_name, branch_to_install,
lang_cmd_for_install, db_pname):
branch_to_install_dict = {'installation_lang_cmd': lang_cmd_for_install,
}
if not os.path.exists(db_pname):
... |
import time
import pyfits
from AllSky340 import AllSky340
cam = AllSky340(port="/dev/tty.usbserial-A700dzlT", baudrate=460800, timeout=1)
cam.log_info("Testing camera communication.")
p = cam.ping()
if p:
exp = 0.1
cam.log_info("Taking %f sec test image." % exp)
imag = cam.getImage(exp, light=True)
now ... |
from pyramid.view import view_config
@view_config(route_name='home', renderer='templates/mytemplate.pt')
def my_view(request):
return {'project': 'TestProject'} |
dna = '' # use to store dna string
with open('rosalind_dna.txt', mode = 'r', encoding = 'utf-8') as fi:
with open('rosalind_dna.out', mode = 'w', encoding = 'utf-8') as fo:
dna = fi.read() # get dna string
dna = dna.strip() # remove all unecessary whitespace
bases = ('A', 'C', 'G', 'T') # de... |
"""
DUnit tests for kwarg_misprints_detection.py.
Copyright (c) 2015 Samsung Electronics Co., Ltd.
Copyright (c) 2015 Vadim Markovtsev.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistribution... |
from dana import *
import matplotlib.pyplot as plt
def H(x):
return 1 if x > 0 else 0
n = 20
dt = 1.0*millisecond
duration = 100.0*dt
np.random.seed(1)
delta = -2
tau_GPe = 10
tau_STN = 10
tau_GPi = 10
theta_D1 =0.1
theta_D2 = 0.1
theta_GPe = 0.1
theta_STN = 0.1
lamda_D1 = 5*(1/(1+np.exp(-6*(delta - theta_D1))))
la... |
R""" MPCD particle updaters
Updates properties of MPCD particles.
"""
import hoomd
from hoomd.md import _md
from . import _mpcd
class sort():
R""" Sorts MPCD particles in memory to improve cache coherency.
Args:
system (:py:class:`hoomd.mpcd.data.system`): MPCD system to create sorter for
period... |
import os
from setuptools import setup
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='codefellows-django-testing',
version='0.1.0',
packages=[
'codefellows_django_testing',
'notes',
'notes.tests',
'notes.migrations'
],
url=... |
from cxroots import Circle
C = Circle(0, 2)
f = lambda z: z**6 + z**3
df = lambda z: 6*z**5 + 3*z**2
r = C.roots(f, df)
r.show() |
import pytest
from aiorest_ws.utils.text import capfirst
@pytest.mark.parametrize("value, expected", [
(None, None),
([], []),
({}, {}),
('test', 'Test'),
])
def test_capfirst(value, expected):
assert capfirst(value) == expected |
from datetime import datetime
from functools import partial
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import six
import sqlalchemy as sa
from sqlalchemy.ext.compiler import compiles
from .dialects.postgresql import (
CreateTemporaryTransactionTableSQL,
... |
import os
c.JupyterHub.spawner_class = 'kubespawner.KubeSpawner'
c.JupyterHub.ip = '0.0.0.0'
c.JupyterHub.hub_ip = '0.0.0.0'
c.JupyterHub.cleanup_servers = False
c.KubeSpawner.start_timeout = 60 * 5
c.KubeSpawner.singleuser_image_spec = 'yuvipanda/simple-singleuser:v1'
c.KubeSpawner.hub_connect_ip = os.environ['HUB_CON... |
"""
Module with frame/cube filtering functionalities.
"""
__author__ = 'Carlos Alberto Gomez Gonzalez'
__all__ = ['frame_filter_highpass',
'frame_filter_lowpass',
'cube_filter_highpass',
'cube_filter_lowpass',
'cube_filter_iuwt']
import warnings
try:
import cv2
no_ope... |
__all__ = (
"RSSReader",
"KeyNotFoundExcpetion",
)
import logging
import datetime
import feedparser
import sys
import re
from dataleach.sources.website import *
from dataleach.datatypes import *
logger = logging.getLogger("dataleach.sources.rssreader")
class KeyNotFoundException(Exception):
"""
Exceptio... |
import os
import logging
from ConfigParser import ConfigParser, NoSectionError, NoOptionError
logger = logging.getLogger("root")
homepath = os.path.expanduser('~')
dot_prercious = os.path.join(homepath, '.precious')
def get_config_path():
return dot_prercious
def get_config_file_path():
return os.path.join(dot_... |
"""
Functions for visualizing results of quantum dynamics simulations,
visualizations of quantum states and processes.
"""
__all__ = ['hinton', 'sphereplot', 'energy_level_diagram',
'plot_energy_levels', 'fock_distribution',
'plot_fock_distribution', 'wigner_fock_distribution',
'plot_wi... |
import unittest
from cybox.objects.win_handle_object import WinHandle
from cybox.test.objects import ObjectTestCase
class TestWinHandle(ObjectTestCase, unittest.TestCase):
object_type = "WindowsHandleObjectType"
klass = WinHandle
_full_dict = {
'id': 1234,
'name': "MyHandle",
'type':... |
import sys
import os
import os.path
import readInput
from os.path import join as pj
def write_surfrend_script(conname,connum, swd, thresh, exthresh):
"""
Writes out the m file with matlab calls to surfrend_canonical.m.
"""
mfile_script = pj(swd, conname+".m")
commands = []
commands.append("warni... |
"""Data Equivalence Tests"""
from __future__ import print_function
import os.path as op
import inspect
import warnings
from nose.tools import assert_equal, assert_true
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_raises, assert_allclose)
from scipy import i... |
"""
eve_mongoengine.schema
~~~~~~~~~~~~~~~~~~~~~~
Mapping mongoengine field types to cerberus schema.
:copyright: (c) 2014 by Stanislav Heller.
:license: BSD, see LICENSE for more details.
"""
import copy
from mongoengine import (StringField, IntField, FloatField, BooleanField,
... |
from IPython import display
from tool import Tool
JS = ['../static/polestar/scripts/vendor-2fda575321.js',
'../static/polestar/scripts/app-001ebe1cd2.js']
CSS = ['../static/polestar/styles/vendor-5779b264ab.css',
'../static/polestar/styles/app-ca269f7a84.css']
TEAMPLATE = '../static/polestar.html'
def expl... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from brigitte.accounts.models import Profile, SshPublicKey
admin.site.unregister(User)
class ProfileInline(admin.StackedInline):
model = Profile
extra = 1
max_num = 1
class SshPublicK... |
import argparse
import csv
import itertools
import json
import os
import re
import sys
from common_includes import *
CONFIG = {
"BRANCHNAME": "retrieve-v8-releases",
"PERSISTFILE_BASENAME": "/tmp/v8-releases-tempfile",
}
PUSH_MSG_SVN_RE = re.compile(r".* \(based on bleeding_edge revision r(\d+)\)$")
PUSH_MSG_GIT_RE... |
from __future__ import absolute_import
from sentry.api.serializers import Serializer, register, serialize
from sentry.models import AuditLogEntry
@register(AuditLogEntry)
class AuditLogEntrySerializer(Serializer):
def get_attrs(self, item_list, user):
# TODO(dcramer); assert on relations
actors = {
... |
import base64
import datetime
import json
import os
import pickle
import struct
import unittest
import uuid
from tornado import testing
import umsgpack
from sprockets.mixins.mediatype import content, handlers, transcoders
import examples
class UTC(datetime.tzinfo):
ZERO = datetime.timedelta(0)
def utcoffset(sel... |
"""
desispec.fiberflat
==================
Utility functions to compute a fiber flat correction and apply it
We try to keep all the (fits) io separated.
"""
from __future__ import absolute_import, division
import numpy as np
from desispec.resolution import Resolution
from desispec.linalg import cholesky_solve
from desis... |
from irckaaja.botscript import BotScript
from irckaaja.dynamicmodule import DynamicModule
class ModuleLoader(BotScript):
"""
A helper script for loading, reloading and unloading
modules dynamically on runtime. Makes developing scripts
much easier as the bot need to reconnect to irc network
between c... |
"""
This dynamically patches a bunch of code in the Django template system to cache
parsed templates instead of re-parsing them with each page load.
It works by replacing django.template.loader.get_template with a function that
stores parsed templates in-memory in a dictionary (keyed by template name). The
rest of the ... |
from wagtail.contrib.modeladmin.options import (
ModelAdmin, modeladmin_register, ModelAdminGroup)
from .models import GeneralPage, StaticContent
class GeneralPageModelAdmin(ModelAdmin):
model = GeneralPage
menu_icon = 'doc-full' # change as required
menu_order = 200 # will put in 3rd place (000 being 1... |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from mock import patch
from sentry.models import (AuthProvider, OrganizationMember)
from sentry.testutils import APITestCase
class UpdateOrganizationMemberTest(APITestCase):
@patch('sentry.models.OrganizationMember.send_invite_email... |
"""
Verify the Gymkhana.
PythonPro Limited
2013-02-21
"""
import pytest
from pp.latchpony.service import gymkhana
from pp.latchpony.service.utils import redis_from_config
pytest_plugins = [
"pkglib.testing.pytest.redis_server",
"pp.testing.redis_cleaner",
"pp.testing.logger",
]
def test_gymkana_dump_and_loa... |
import sys
from Utils import Logger
from SketchFramework.Point import Point
from SketchFramework.Annotation import Annotation, AnnotatableObject
logger = Logger.getLogger('DiGraphObserver', Logger.WARN )
class Stroke(AnnotatableObject):
"Stroke defined as a List of Points: Points"
# counter shared with all stro... |
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 field 'DMUserProfile.hobby'
db.add_column('accounts_dmuserprofile', 'hobby', self.gf('django.db.models.fields.CharField')(defa... |
"""
Generalized linear models currently supports estimation using the one-parameter
exponential families
References
----------
Gill, Jeff. 2000. Generalized Linear Models: A Unified Approach.
SAGE QASS Series.
Green, PJ. 1984. "Iteratively reweighted least squares for maximum
likelihood estimation, and some ro... |
"""
Tests for formalchemy_mustache.
""" |
"""
:copyright: (c) 2010-2012 by Andreas Madsack.
"""
from flask import Flask, render_template, url_for, request, Response
from flask import session, abort
from flaskext.babel import gettext
from webbib import app, babel, set_source
from lxml import etree
import codecs
import bibmod
import re
def create_app(source):
... |
from sklearn2sql_heroku.tests.classification import generic as class_gen
class_gen.test_model("LogisticRegression" , "FourClass_500" , "oracle") |
from Adafruit_LED_Backpack import Matrix8x8
from m64_images import *
import time
display = Matrix8x8.Matrix8x8()
display.begin()
display.clear()
for i in range(100):
set_time(3, i, display)
time.sleep(1)
display.clear() |
import glob
import imp
import inspect
import logging
import os
import socket
import sys
import time
from telemetry.core import exceptions
def GetBaseDir():
main_module = sys.modules['__main__']
if hasattr(main_module, '__file__'):
return os.path.dirname(os.path.abspath(main_module.__file__))
else:
return ... |
def extractAbloggeronhiatusBlogspotCom(item):
'''
Parser for 'abloggeronhiatus.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
... |
from __future__ import division
from vistrails.db.domain import DBPluginData
import unittest
import copy
import random
from vistrails.db.domain import IdScope
import vistrails.core
class PluginData(DBPluginData):
##########################################################################
# Constructors and copy
... |
"""
Payment module for cash on delivery handling
Automatically completes every order passed.
"""
from datetime import datetime
import logging
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from plata.payment.modules.base import ProcessorBase
from plata.product.stock.models... |
'''
The following code requires libtaxii v1.1.103 or greater installed.
For installation instructions, please refer to http://libtaxii.readthedocs.org/en/latest/installation.html
'''
import libtaxii.taxii_default_query as tdq
import libtaxii.messages_11 as tm11
from libtaxii.common import generate_message_id
from libta... |
import oval57 as oval
class cybox_oval_mappings(object):
def __init__(self, id_namespace):
self.test_id_base = 0
self.obj_id_base = 0
self.ste_id_base = 0
self.def_id_base = 0
self.id_namespace = id_namespace
#Mappings
#CybOX Condition to OVAL operation mappin... |
from __future__ import unicode_literals
from precise_bbcode import get_parser
from precise_bbcode.test import gen_bbcode_tag_klass
class TestParser(object):
DEFAULT_TAGS_RENDERING_TESTS = (
# BBcodes without errors
('[b]hello world![/b]', '<strong>hello world!</strong>'),
('[b]hello [i]world... |
import requests
import logging
import re
from django.utils import simplejson as json
from django.conf import settings
from federweb.base.rest import RestManager, RestModel, hooks
from federweb.base.utils import cached_property
logger = logging.getLogger(__name__)
class FederationManager(object):
def __init__(self, ... |
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-loggit',
version='0.1',
packages=find_packages(),
... |
from __future__ import division
""" This python module defines Connection class.
"""
import copy
from vistrails.db.domain import DBConnection
from vistrails.core.vistrail.port import PortEndPoint, Port
import unittest
from vistrails.db.domain import IdScope
class Connection(DBConnection):
""" A Connection is a conn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.