code stringlengths 1 199k |
|---|
from sqlalchemy.testing import eq_, is_
from sqlalchemy.orm import backref, configure_mappers
from sqlalchemy import testing
from sqlalchemy import desc, select, func, exc
from sqlalchemy.orm import mapper, relationship, create_session, Query, \
attributes, exc as orm_exc, Session
from sqlalchemy.or... |
import collections
import errno
import re
import sys
try:
import multiprocessing
except ImportError: # Python 2.5
multiprocessing = None
import pep8
__all__ = ['multiprocessing', 'BaseQReport', 'QueueReport']
class BaseQReport(pep8.BaseReport):
"""Base Queue Report."""
_loaded = False # Windows su... |
import argparse
import copy
import numpy as np
import chainer
from chainer.datasets import ConcatenatedDataset
from chainer.datasets import TransformDataset
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.t... |
"""
pgoapi - Pokemon Go API
Copyright (c) 2016 tjado <https://github.com/tejado>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use,... |
from __future__ import division
import numpy as np
from chainer.backends import cuda
import chainer.functions as F
from chainercv import transforms
exp_clip = np.log(1000 / 16)
def smooth_l1(x, t, beta):
return F.huber_loss(x, t, beta, reduce='no') / beta
def argsort(x):
xp = cuda.get_array_module(x)
i = np... |
"""
PageLayout
==========
.. image:: images/pagelayout.gif
:align: right
The :class:`PageLayout` class is used to create a simple multi-page
layout, in a way that allows easy flipping from one page to another using
borders.
:class:`PageLayout` does not currently honor the
:attr:`~kivy.uix.widget.Widget.size_hint`,
... |
import pytest
import numpy as np
from pandas import Series, Timestamp
from pandas.compat import range, lmap
import pandas.core.common as com
import pandas.util.testing as tm
def test_mut_exclusive():
msg = "mutually exclusive arguments: '[ab]' and '[ab]'"
with tm.assert_raises_regex(TypeError, msg):
com... |
import functools
import pfp.interp
def native(name, ret, interp=None, send_interp=False):
"""Used as a decorator to add the decorated function to the
pfp interpreter so that it can be used from within scripts.
:param str name: The name of the function as it will be exposed in template scripts.
:param pfp.fields.Fie... |
import MalmoPython
import os
import sys
import time
import json
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # flush print output immediately
def Menger(xorg, yorg, zorg, size, blocktype, variant, holetype):
#draw solid chunk
genstring = GenCuboidWithVariant(xorg,yorg,zorg,xorg+size-1,yorg+size-1,zorg+s... |
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from . import views
urlpatterns = [
url(r"^$", csrf_exempt(views.SamlView.as_view())),
url(r"^metadata/$", views.serve_metadata),
] |
"""
Contains functions related to working with the Nectar downloading library.
"""
from functools import partial
from nectar.config import DownloaderConfig
from pulp.common.plugins import importer_constants as constants
def importer_config_to_nectar_config(importer_config):
"""
Translates the Pulp standard impo... |
"""QGIS Unit tests for edit widgets.
.. 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 version.
"""
__author__ = 'Matthias Kuhn'
... |
__doc__='''
Delete the previous DRAC and Storage Controllers reports.
$Id:$
'''
from Products.ZenModel.ZenPack import ZenPackMigration
from Products.ZenModel.migrate.Migrate import Version
class removeOldDellReports(ZenPackMigration):
version = Version(2, 3)
def migrate(self, pack):
if hasattr(pack.dmd.... |
import unittest
from PyFoam.Applications.ConvertToCSV import ConvertToCSV
theSuite=unittest.TestSuite() |
"""HEPData application factories."""
import os
import sys
from invenio_base.app import create_app_factory
from invenio_base.wsgi import create_wsgi_factory
from invenio_config import create_config_loader
from . import config
env_prefix = 'APP'
conf_loader = create_config_loader(config=config, env_prefix=env_prefix)
ins... |
from datetime import datetime
from fixture import DataSet
class OaiREPOSITORYData(DataSet):
class OaiREPOSITORY_2:
f1 = u'reportnumber'
f2 = u'division'
f3 = u''
setRecList = None
setDefinition = u'c=;p1=CERN;f1=reportnumber;m1=a;p2=(EP|PPE);f2=division;m2=r;p3=;f3=;m3=;'
... |
"""
File format:
- <hostname>
or
- host: <hostname>
vars:
- myvar: value
- myvbr: vblue
groups:
- mygroup1
- mygroup2
or
- group: <groupname>
vars:
- groupvar: value
hosts:
- myhost1
- myhost2
groups:
- subgroup1
- subgroup2
Any statement except the first definition is optional.
"""
import j... |
"""
This file is part of L3Morpho.
Author: Michael Gasser <gasser@cs.indiana.edu>
-----------------------------------------------------------------
internals.py is part of
Natural Language Toolkit: Internal utility functions
Copyright (C) 2001-2008 University of Pennsylvania
Author: Steven Bird <sb@csse.unimelb.edu.au>... |
__author__ = 'hal9000'
__all__ = ['Cache', 'CacheServer']
import socket
import time
import json
import hashlib
from sqlite3 import dbapi2 as sqlite
import xbmc
import log
import gui
import system
SOCKET = '127.0.0.1', 59999
CLEAR = 60*60*24 # 1 day
class SQL:
def __init__(self, name, version):
self.fs = sys... |
import numpy as np
from gpaw import KohnShamConvergenceError
class SCFLoop:
"""Self-consistent field loop.
converged: Do we have a self-consistent solution?
"""
def __init__(self, eigenstates=0.1, energy=0.1, density=0.1, maxiter=100,
fixdensity=False, niter_fixdensity=None):
se... |
from .base import Result, ParsingDict
class Response(ParsingDict):
def __init__(self, data, **kwargs):
ParsingDict.__init__(self, **kwargs)
self.raw_data = data
self.af = self.ensure("af", int)
self.body_size = self.ensure("bsize", int)
self.head_size = self.ensure("hsize", i... |
"""Baked query extension.
Provides a creational pattern for the :class:`.query.Query` object which
allows the fully constructed object, Core select statement, and string
compiled result to be fully cached.
"""
import copy
import logging
from .. import exc as sa_exc
from .. import util
from ..orm import exc as orm_exc
f... |
import math
import re
EVERYTHING_BEFORE_PARAMS = """id: qtgui_time_sink_x
label: QT GUI Time Sink
parameters:
- id: type
label: Type
dtype: enum
default: complex
options: [complex, float, msg_complex, msg_float]
option_labels: [Complex, Float, Complex Message, Float Message]
option_attributes:... |
import os
import sys
import nupic.bindings.engine_internal as engine
from nupic.support.lockattributes import LockAttributesMixin
import functools
basicTypes = ['Byte', 'Int16', 'UInt16', 'Int32', 'UInt32', 'Int64', 'UInt64', 'Real32', 'Real64', 'Handle']
arrayTypes = [t + 'Array' for t in basicTypes[:-1]]
for a in arr... |
import copy
import Queue
import thread
import time
from ..core.Threadable import Threadable
from ..reconstruction.Buffer import Buffer
from ..settings import Arguments
from Packet import Packet
from TDMA_Scheduler import TDMA_Scheduler
__all__ = [
"RF_Sensor_Simulator", "RF_Sensor_Physical_XBee",
"RF_Sensor_Phy... |
try:
import ovirtsdk4.types as otypes
from ovirtsdk4.types import StorageDomainStatus as sdstate
except ImportError:
pass
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
BaseModule,
check_sdk,
create_connection,
equal,
ovirt_... |
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from gnuradio import gr, digital, filter
from gnuradio import blocks
from gnuradio import channels
from gnuradio import eng_notation
from gnuradio.eng_arg import eng_float, intx
from argparse import ArgumentPar... |
source("../../shared/qtcreator.py")
def main():
startApplication("qtcreator" + SettingsPath)
if not startedWithoutPluginError():
return
checkedTargets, projectName = createNewQtQuickApplication(tempDir(), "SampleApp")
# run project for debug and release and verify results
runVerify(checkedTa... |
"""
Copyright (c) 2012, CCL Forensics
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the fol... |
from ._commandbase import RadianceCommand
from ..datatype import RadiancePath
import os
class Epw2wea(RadianceCommand):
"""epw2wea transforms an EnergyPlus weather data (.epw) file into
the DAYSIM weather file format, for use with the RADIANCE gendaymtx
program.
Attributes:
epw_file: Filepath of... |
"""
Tests for L{twisted.conch.telnet}.
"""
from __future__ import absolute_import, division
from zope.interface import implementer
from zope.interface.verify import verifyObject
from twisted.internet import defer
from twisted.conch import telnet
from twisted.trial import unittest
from twisted.test import proto_helpers
... |
import logging
import superdesk
import superdesk.publish
from datetime import timedelta
from eve.utils import config, ParsedRequest
from flask import current_app as app
from superdesk import get_resource_service
from superdesk.celery_task_utils import get_lock_id
from superdesk.errors import PublishHTTPPushClientError
... |
from django.db import models
from helusers.models import AbstractUser
class User(AbstractUser):
pass |
import os
from queue import Queue
from bears.general.LicenseHeaderBear import LicenseHeaderBear
from coalib.testing.LocalBearTestHelper import LocalBearTestHelper
from coalib.results.Result import Result
from coalib.settings.Section import Section
from coalib.settings.Setting import Setting
def get_testfile_path(name):... |
import sys
import os
import shlex
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'pi-manage'
copyright = u'2015, privacyIDEA'
author = u'privacyIDEA'
version = '2.8'
release = '2.8'
language = None
exclude_patterns = ['_build']
pygments_style = 'sphinx'
todo_inclu... |
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 'Issue.status'
db.add_column('core_issue', 'status',
self.gf('django.db.models.fields.CharField')(... |
from spack import *
class PyMarkupsafe(PythonPackage):
"""MarkupSafe is a library for Python that implements a unicode
string that is aware of HTML escaping rules and can be used to
implement automatic string escaping. It is used by Jinja 2, the
Mako templating engine, the Pylons web framework and many ... |
from spack import *
import glob
class Guidance(MakefilePackage):
"""Guidance: Accurate detection of unreliable alignment regions accounting
for the uncertainty of multiple parameters."""
homepage = "http://guidance.tau.ac.il/ver2/"
url = "http://guidance.tau.ac.il/ver2/guidance.v2.02.tar.gz"
... |
import os
from smart_open import smart_open
try:
import cPickle as _pickle
except ImportError:
import pickle as _pickle
from gensim.models.doc2vec import Doc2Vec
from gensim.models.word2vec import Word2Vec
try:
from annoy import AnnoyIndex
except ImportError:
raise ImportError("Annoy has not been instal... |
HAS_MODULES = False
try:
from icalendar import vDatetime
HAS_MODULES = True
except ImportError:
pass
import os
import tempfile
import time
from datetime import datetime, timedelta
from flumotion.common import testsuite
from twisted.trial import unittest
from twisted.internet import defer
from flumotion.comm... |
import curses
import functools
from stem.control import EventType, Controller
from stem.util import str_tools
COLOR_LIST = {
"red": curses.COLOR_RED,
"green": curses.COLOR_GREEN,
"yellow": curses.COLOR_YELLOW,
"blue": curses.COLOR_BLUE,
"cyan": curses.COLOR_CYAN,
"magenta": curses.COLOR_MAGENTA,
"black": ... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class TumblrIE(InfoExtractor):
_VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/(?:post|video)/(?P<id>[0-9]+)(?:$|[/?#])'
_TESTS = [{
'url': 'http://tatianamaslanydaily.tumblr.com/post/54196191430/orphan-black-dvd-e... |
import abc
from trove.common.strategies.strategy import Strategy
class Storage(Strategy):
"""Base class for Storage Strategy implementation."""
__strategy_type__ = 'storage'
__strategy_ns__ = 'trove.common.strategies.storage'
def __init__(self, context):
self.context = context
super(Stor... |
from oslo_config import cfg
consoleauth_topic_opt = cfg.StrOpt('consoleauth_topic',
default='consoleauth',
help='The topic console auth proxy nodes listen on')
console_token_ttl = cfg.IntOpt('console_token_ttl',
default=600,
help='How many seconds before deleting tokens')
CONSOLEAUTH_OPTS = [consoleauth... |
"""Support for Soma sensors."""
from datetime import timedelta
import logging
from requests import RequestException
from homeassistant.const import DEVICE_CLASS_BATTERY, PERCENTAGE
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
from . import DEVICES, SomaEntity
from .const impor... |
import glob
import copy
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32, String
import rospkg
class Hear_orders:
def __init__(self):
self.speech_subscriber = rospy.Subscriber("/speech_recognition", String, self.publish_emotion)
self.... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
def main():
info('Evacuate Microbone')
close(description='Jan Inlet')
open(description='Jan Ion Pump')
#close(description='Minibone to Bone')
open(description='Minibone to Bone')
#close(description='Microbone to Minibone')
open(description='Microbone to Minibone')
open('C')
close('P'... |
"""SequenceQueueingStateSaver and wrappers.
Please see the reading data how-to for context.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numbers
import six
from tensorflow.python.framework import dtypes
from tensorflow.python.... |
from pycuda.compiler import SourceModule
from pycuda.tools import context_dependent_memoize
"""
CUDA kernels for ROI pooling layers.
There is a fprop function, a bprop function.
The fprop and bprop CUDA-C code are adapted from Fast R-CNN model.
Each of the kernels uses templating to perform %(type)
conversion so it wor... |
import outer_packages
from trex_stl_lib.trex_stl_hltapi import *
import traceback
import sys, time
from pprint import pprint
import argparse
def error(err = None):
if not err:
raise Exception('Unknown exception, look traceback')
if type(err) is str and not err.startswith('[ERR]'):
err = '[ERR] '... |
from st2api.controllers.resource import ResourceController
from st2common.models.api.trace import TraceAPI
from st2common.persistence.trace import Trace
from st2common.rbac.types import PermissionType
__all__ = ["TracesController"]
class TracesController(ResourceController):
model = TraceAPI
access = Trace
... |
"""Common test objects."""
import copy
from datetime import datetime
import json
from unittest.mock import ANY, patch
from homeassistant.components import mqtt
from homeassistant.components.mqtt import debug_info
from homeassistant.components.mqtt.const import MQTT_DISCONNECTED
from homeassistant.components.mqtt.mixins... |
"""Script to generate unannotated baseline stubs using stubgen.
Basic usage:
$ python3 scripts/create_baseline_stubs.py <project on PyPI>
Run with -h for more help.
"""
import argparse
import os
import re
import shutil
import subprocess
import sys
from typing import Optional, Tuple
PYRIGHT_CONFIG = "pyrightconfig.stric... |
"""Provides concept object."""
from __future__ import absolute_import
from .. import t1types
from ..entity import Entity
class Concept(Entity):
"""Concept entity."""
collection = 'concepts'
resource = 'concept'
_relations = {
'advertiser',
}
_pull = {
'advertiser_id': int,
... |
from __future__ import absolute_import
from __future__ import print_function
import collections
import math
import os
import random
import zipfile
import numpy as np
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
url = 'http://mattmahoney.net/dc/'
... |
"""Utilty functions for control flow.
This file is necessary to avoid cyclic dependencies between ops.py and
control_flow_ops.py.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import traceback
from tensorflow.python.platform import tf_logging ... |
import logging
import threading
import uuid
import dcm.agent.utils as agent_utils
from dcm.agent.events.globals import global_space as dcm_events
_g_logger = logging.getLogger(__name__)
_g_message_uuid = str(uuid.uuid4()).split("-")[0]
_g_message_id_count = 0
_g_guid_lock = threading.RLock()
def new_message_id():
#... |
"""Test the openml loader.
"""
import gzip
import warnings
import json
import os
import re
from importlib import resources
from io import BytesIO
import numpy as np
import scipy.sparse
import sklearn
import pytest
from sklearn import config_context
from sklearn.datasets import fetch_openml as fetch_openml_orig
from skl... |
from glob import glob
import os
try:
from skimage.io import imread as sk_imread
except ImportError:
pass
from .core import Array
from ..base import tokenize
def add_leading_dimension(x):
return x[None, ...]
def imread(filename, imread=None, preprocess=None):
""" Read a stack of images into a dask array
... |
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
import pyglet
from pyglet.libs.darwin import carbon, _oscheck, create_cfstring
from pyglet.libs.darwin.constants import *
from base import Device, Control, AbsoluteAxis, RelativeAxis, Button
from base import Joystick, AppleRemote
from base ... |
import numpy as np
import regreg.api as rr
from selection.randomized.glm import pairs_bootstrap_glm, bootstrap_cov
from selection.randomized.query import query
from selection.randomized.randomization import split
import functools
def pairs_bootstrap_glm(glm_loss,
active,
... |
"""Compressed Sparse Column matrix format"""
from __future__ import division, print_function, absolute_import
__docformat__ = "restructuredtext en"
__all__ = ['csc_matrix', 'isspmatrix_csc']
import numpy as np
from scipy._lib.six import xrange
from ._sparsetools import csc_tocsr
from . import _sparsetools
from .sputils... |
"""Implementation of __array_function__ overrides from NEP-18."""
import collections
import functools
import os
import textwrap
from numpy.core._multiarray_umath import (
add_docstring, implement_array_function, _get_implementing_args)
from numpy.compat._inspect import getargspec
ARRAY_FUNCTION_ENABLED = bool(
... |
import numpy as np
from bokeh.models import ColumnDataSource, Plot, LinearAxis, Grid
from bokeh.models.markers import Diamond
from bokeh.io import curdoc, show
N = 9
x = np.linspace(-2, 2, N)
y = x**2
sizes = np.linspace(10, 20, N)
source = ColumnDataSource(dict(x=x, y=y, sizes=sizes))
plot = Plot(
title=None, plot... |
def reference_case_attachment_view(request, domain, case_id, attachment_id):
raise NotImplemented("This view is to be overrided by the specific implementations for retrieving case attachments") |
import warnings
from django.views.generic.dates import ArchiveIndexView, DateDetailView, DayArchiveView, MonthArchiveView, \
YearArchiveView
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.base import RedirectView
from django.core.urlresolv... |
"""
This script runs swarming_xcode_install on the bots. It should be run when we
need to upgrade all the swarming testers. It:
1) Packages two python files into an isolate.
2) Runs the isolate on swarming machines that satisfy certain dimensions.
Example usage:
$ ./build/run_swarming_xcode_install.py --luci_... |
Experiment(description='Synthetic data sets of interest',
data_dir='../data/synth/',
max_depth=9,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=2,
jitter_sd=0.1,
max_jobs=300,
... |
"""events
Revision ID: 9c92c85163a9
Revises: 666668eae682
Create Date: 2016-05-09 19:04:44.498817
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision = '9c92c85163a9'
down_revision = '666668eae682'
def upgrade():
op.create_table('event',
sa.Column('id', sa.... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import euclidean_distances
from .datasets import make_wave
from .plot_helpers import cm3
def plot_knn_regression(n_neighbors=1):
X, y = make_wave(n_samples=40)
X_test = np.array([[-1.5], [0.... |
__author__ = 'Anatoli Kalysch' |
from pypinyin.phrases_dict import phrases_dict
from pypinyin import pinyin, TONE
phrases_list = set()
phrases_same = set()
for han, pys in phrases_dict.items():
if pinyin(han, style=TONE, heteronym=True) != pys:
phrases_list.add(han)
else:
phrases_same.add(han)
if __name__ == '__main__':
wit... |
"""
Misago default settings
This fille sets everything Misago needs to run.
If you want to add custom app, middleware or path, please update setting vallue
defined in this file instead of copying setting from here to your settings.py.
Yes:
INSTALLED_APPS += (
'myawesomeapp',
)
No:
INSTALLED_APPS = (
'django.con... |
"""
***************************************************************************
lassplit.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*******************************************************... |
import sys
import csv
import lxml.etree as ET
xccdf_ns = "http://checklists.nist.gov/xccdf/1.1"
disa_cciuri = "http://iase.disa.mil/stigs/cci/Pages/index.aspx"
disa_srguri = "http://iase.disa.mil/stigs/srgs/Pages/index.aspx"
def parse_xml_file(xmlfile):
with open(xmlfile, 'r') as xml_file:
filestring = xml_... |
version_info = (1, 4, 2)
__version__ = '.'.join(map(str, version_info)) |
"""Unit tests for WebJournal."""
__revision__ = \
"$Id$"
import unittest
from invenio.webjournal_utils import compare_issues
from invenio.webjournal import issue_is_later_than
from invenio.testutils import make_test_suite, run_test_suite
class TestCompareIssues(unittest.TestCase):
"""Tests for comparing issues.... |
import os
import sys
import datetime as dt
import json
from itertools import groupby
from kivy.properties import (StringProperty,
DictProperty,
ListProperty,
BooleanProperty)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scr... |
import gzip
import logging
import zlib
from io import BytesIO
from .exceptions import HTTPError
try:
basestring = basestring
except NameError: # Python 3
basestring = (str, bytes)
log = logging.getLogger(__name__)
def decode_gzip(data):
gzipper = gzip.GzipFile(fileobj=BytesIO(data))
return gzipper.read(... |
import clv_insured_card |
from oslo_log import log as logging
from oslo_serialization import jsonutils
import six
from nova.scheduler import filters
from nova.scheduler.filters import extra_specs_ops
LOG = logging.getLogger(__name__)
class ComputeCapabilitiesFilter(filters.BaseHostFilter):
"""HostFilter hard-coded to work with InstanceType ... |
"""Unit tests for Cisco fc zone client cli."""
from mock import patch
from cinder import exception
from cinder.openstack.common import processutils
from cinder import test
from cinder.zonemanager.drivers.cisco.cisco_fc_zone_client_cli \
import CiscoFCZoneClientCLI
import cinder.zonemanager.drivers.cisco.fc_zone_con... |
"""Build tool setup for MacOS.
This module is a SCons tool which should be include in the topmost mac
environment.
It is used as follows:
env = base_env.Clone(tools = ['component_setup'])
mac_env = base_env.Clone(tools = ['target_platform_mac'])
"""
import SCons.Script
def ComponentPlatformSetup(env, builder_name):... |
"""Command-line flag library.
Emulates gflags by wrapping cfg.ConfigOpts.
The idea is to move fully to cfg eventually, and this wrapper is a
stepping stone.
"""
import socket
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import netutils
from cinder.i18n import _
CONF = cfg.CONF
logging... |
from django.conf.urls import url
from dispatch.topology import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
] |
import abc
import six
from mongoengine import NotUniqueError
from st2common import log as logging
from st2common.exceptions.db import StackStormDBObjectConflictError
from st2common.models.system.common import ResourceReference
from st2common.transport.reactor import TriggerDispatcher
__all__ = [
'Access',
'Cont... |
import json
import mock
import webob
from nova.api.openstack.compute.contrib import server_external_events
from nova import context
from nova import exception
from nova.objects import instance as instance_obj
from nova import test
fake_instances = {
'00000000-0000-0000-0000-000000000001': instance_obj.Instance(
... |
def convert(font):
for c in range(96):
i, j = c % 16, c / 16
word, shift = 0, 0
for y in range(6):
for x in range(3):
p = ((j * 6 + y) * 16 + i) * 4 + x + 1
if font[p] == '@':
if y == 5 and shift == 0:
shift, word = 1, word << 1
word |= 1 << (5*(3-x) -... |
from unittest import mock
import os
import pytest
from django.conf import settings
from waffle.testutils import override_switch
from olympia import amo
from olympia.addons.tasks import (
recreate_theme_previews,
update_addon_average_daily_users,
update_addon_hotness,
update_addon_weekly_downloads,
)
fro... |
from __future__ import unicode_literals
from django.test import SimpleTestCase
from localflavor.is_.forms import (ISIdNumberField, ISPhoneNumberField,
ISPostalCodeSelect)
class ISLocalFlavorTests(SimpleTestCase):
def test_ISPostalCodeSelect(self):
f = ISPostalCodeSelect()
... |
default_app_config = 'hs_tracking.apps.HSTrackingAppConfig' |
import unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.tool.mocktool import MockOptions, MockTool
class CommandsTest(unittest.TestCase):
def assert_execute_outputs(self, command, args=[], expected_stdout="", expected_stderr="", expected_exception=None, expected_logs=None, optio... |
"""
.. todo::
WRITEME
"""
import os
import gc
import warnings
try:
import tables
except ImportError:
warnings.warn("Couldn't import tables, so far SVHN is "
"only supported with PyTables")
import numpy
from theano import config
from pylearn2.datasets import dense_design_matrix
from pylearn2.util... |
"""
This module contains query handlers responsible for calculus queries:
infinitesimal, bounded, etc.
"""
from __future__ import print_function, division
from sympy.logic.boolalg import conjuncts
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler
class AskInfinitesimalHandler(Com... |
from StringIO import StringIO
from webkitpy.common.system.environment import Environment
from webkitpy.common.system.executive_mock import MockExecutive
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.platforminfo_mock import MockPlatformInfo
from webkitpy.common.system.use... |
from nbgrader import utils
from nbgrader.preprocessors import NbGraderPreprocessor
class ComputeChecksums(NbGraderPreprocessor):
"""A preprocessor to compute checksums of grade cells."""
def preprocess_cell(self, cell, resources, cell_index):
# compute checksums of grade cell and solution cells
... |
NAME = 'F5 Trafficshield'
def is_waf(self):
for hv in [['cookie', '^ASINFO='], ['server', 'F5-TrafficShield']]:
r = self.matchheader(hv)
if r is None:
return
elif r:
return r
# the following based on nmap's http-waf-fingerprint.nse
if self.matchheader(('server... |
from django.conf import settings
from django.contrib.comments.managers import CommentManager
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core import urlresolvers
from django.db import models
from djan... |
import unittest
from rmgpy.molecule.molecule import Molecule
from .parser import *
class ParserTest(unittest.TestCase):
def test_fromAugmentedInChI(self):
aug_inchi = 'InChI=1S/CH4/h1H4'
mol = fromAugmentedInChI(Molecule(), aug_inchi)
self.assertTrue(not mol.InChI == '')
aug_inchi = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.