code stringlengths 1 199k |
|---|
import logging
from sqlalchemy import *
from kallithea.lib.dbmigrate.migrate import *
from kallithea.lib.dbmigrate.migrate.changeset import *
from kallithea.model import meta
from kallithea.lib.dbmigrate.versions import _reset_base, notify
log = logging.getLogger(__name__)
def upgrade(migrate_engine):
"""
Upgra... |
../../../../../../../../share/pyshared/ubuntuone-control-panel/ubuntuone/controlpanel/gui/gtk/package_manager.py |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_facts
short_description: Gathers facts about remote ESXi hostsystem
descript... |
import uuid
from netzob.Common.Utils.Decorators import NetzobLogger
from netzob.Common.Utils.Decorators import typeCheck
from netzob.Model.Vocabulary.Domain.Variables.AbstractVariable import AbstractVariable
from netzob.Model.Vocabulary.Domain.Parser.VariableParserResult import VariableParserResult
@NetzobLogger
class ... |
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
A = [0] * (n + 1)
A[0] = 1
A[1] = 1
for i in xrange(2, n+1):
for k in xrange(0, i):
A[i] += A[k]*A[i-1-k]
return A[n]
class Solution(obj... |
from __future__ import unicode_literals
import frappe, erpnext
from frappe.utils import flt, cstr, cint
from frappe import _
from frappe.model.meta import get_field_precision
from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget
from erpnext.accounts.doctype.accounting_dimension.accounting_... |
import json
from catmaid.models import Message
from .common import CatmaidApiTestCase
class MessagesApiTests(CatmaidApiTestCase):
def test_read_message_error(self):
self.fake_authentication()
message_id = 5050
response = self.client.post(f'/messages/{message_id}/mark_read')
self.asse... |
"""DEPRECATED: use the classifier subcommand
Classify sequences by grouping blast output by matching taxonomic names
Optional grouping by specimen and query sequences
"""
import sys
import logging
from csv import DictReader, DictWriter
from collections import defaultdict
from math import ceil
from operator import itemg... |
'''
Created on Jul 28, 2013
@author: Rob
'''
import os, yaml
config = {
'names': [
'NT',
'VGTestServer'
],
'servers':{
'irc.server.tld': {
'port':6667,
'password':None,
'channels':{
'#vgstatio... |
try:
import traceback
import argparse
import textwrap
import glob
import os
import logging
import datetime
import multiprocessing
from libs import LasPyConverter
except ImportError as err:
print('Error {0} import module: {1}'.format(__name__, err))
traceback.print_exc()
e... |
import mock
import time
import json
from nose.tools import eq_, ok_, assert_raises
from socorro.submitter.submitter_app import (
SubmitterApp,
SubmitterFileSystemWalkerSource,
)
from configman.dotdict import DotDict
from socorro.external.crashstorage_base import Redactor
from socorro.unittest.testbase import Te... |
import ws
import unittest
class TestCollapse(unittest.TestCase):
def test_collapse(self):
result = ws.collapse(" ")
self.assertEqual(result, "")
result = ws.collapse(" foo")
self.assertEqual(result, "foo")
result = ws.collapse("foo ")
self.assertEqual(result, "fo... |
import logging
from django.conf import settings
from kombu import (Exchange,
Queue)
from kombu.mixins import ConsumerMixin
from treeherder.etl.common import fetch_json
from treeherder.etl.tasks.pulse_tasks import (store_pulse_jobs,
store_pulse_resultsets)... |
from __future__ import absolute_import, division, unicode_literals
from jx_base.expressions import NumberOp as NumberOp_
from jx_sqlite.expressions import _utils
from jx_sqlite.expressions._utils import SQLang, check
from mo_dots import wrap
from mo_sql import sql_coalesce
class NumberOp(NumberOp_):
@check
def ... |
""" Test the behavior of split_mongo/MongoConnection """
from __future__ import absolute_import
import unittest
from mock import patch
from xmodule.exceptions import HeartbeatFailure
from xmodule.modulestore.split_mongo.mongo_connection import MongoConnection
class TestHeartbeatFailureException(unittest.TestCase):
... |
"""
Tests for wiki views.
"""
from django.conf import settings
from django.test.client import RequestFactory
from lms.djangoapps.courseware.tabs import get_course_tab_list
from common.djangoapps.student.tests.factories import AdminFactory, UserFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCa... |
"""Contain the AskViewTests class"""
import unittest
import os
import tempfile
import datetime
import json
import humanize
from shutil import copyfile
from pyramid import testing
from pyramid.paster import get_appsettings
from askomics.libaskomics.ParamManager import ParamManager
from askomics.libaskomics.TripleStoreEx... |
from datetime import datetime, timedelta
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP, float_compare
from openerp.osv import fields, osv
from openerp.tools.safe_eval import safe_eval as eval
from openerp.tools.translate import _
import pytz
from openerp impo... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0034_auto_20170613_2039'),
]
operations = [
migrations.AddField(
model_name='siteconfiguration',
name='base_cookie_domain',
field=models.CharField(bl... |
import re
from django.core.management import call_command
from django_webtest import WebTest
from .auth import TestUserMixin
from .settings import SettingsMixin
from popolo.models import Person
from .uk_examples import UK2015ExamplesMixin
class TestSearchView(TestUserMixin, SettingsMixin, UK2015ExamplesMixin, WebTest):... |
import os
import django
from unipath import Path
BASE_DIR = Path(os.path.abspath(__file__))
BOOKTYPE_SITE_NAME = ''
BOOKTYPE_SITE_DIR = 'tests'
THIS_BOOKTYPE_SERVER = ''
BOOKTYPE_URL = ''
BOOKTYPE_ROOT = BASE_DIR.parent
STATIC_ROOT = BASE_DIR.parent.child("static")
STATIC_URL = '{}/static/'.format(BOOKTYPE_URL)
DATA_RO... |
"""This module implements functions for querying properties of the operating
system or for the specific process the code is running in.
"""
import os
import sys
import re
import multiprocessing
import subprocess
try:
from subprocess import check_output as _execute_program
except ImportError:
def _execute_progra... |
"""
Each store has slightly different semantics wrt draft v published. XML doesn't officially recognize draft
but does hold it in a subdir. Old mongo has a virtual but not physical draft for every unit in published state.
Split mongo has a physical for every unit in every state.
Given that, here's a table of semantics ... |
"""
*2014.09.10 16:10:05
DEPRECATED!!!!
please use building.models.search_building and building.models.make_building
instead of the make_unit and make_building functions found here...
out of date.
"""
import sys, os, json, codecs, re
sys.path.append(os.path.dirname(os.getcwd()))
from geopy import geocoders, distance
ge... |
import codecs
from shinken.basemodule import BaseModule
properties = {
'daemons': ['broker'],
'type': 'service_perfdata',
'phases': ['running'],
}
def get_instance(plugin):
print "Get a Service Perfdata broker for plugin %s" % plugin.get_name()
# Catch errors
path = plugin.path
if hasatt... |
import unittest
import re
from lxml import etree
from zope.testing import doctest, cleanup
import zope.component.eventtesting
from imagestore.xml import XMLValidationError, local_file
class ValidationTests(unittest.TestCase):
relaxng = etree.RelaxNG(file=local_file('rng', 'imagestore.rng'))
def validate(self, e... |
'''Simple utility functions that should really be in a C module'''
from math import *
from OpenGLContext.arrays import *
from OpenGLContext import vectorutilities
def rotMatrix( (x,y,z,a) ):
"""Given rotation as x,y,z,a (a in radians), return rotation matrix
Returns a 4x4 rotation matrix for the given rotation,... |
"""
Stores metadata about images which are built to encorporate changes to subuser images which are required in order to implement various permissions.
"""
import os
import json
from subuserlib.classes.userOwnedObject import UserOwnedObject
from subuserlib.classes.fileBackedObject import FileBackedObject
class RuntimeC... |
"""
This configuration file loads environment's specific config settings for the application.
It takes precedence over the config located in the boilerplate package.
"""
import os
if os.environ['HTTP_HOST'] == "appengine.beecoss.com":
# Load Boilerplate config only in http://appengine.beecoss.com
# this code is... |
"""The Tab Nanny despises ambiguous indentation. She knows no mercy.
tabnanny -- Detection of ambiguous indentation
For the time being this module is intended to be called as a script.
However it is possible to import it into an IDE and use the function
check() described below.
Warning: The API provided by this module... |
"""Interactive context using the GLUT API (provides navigation support)"""
from OpenGLContext import interactivecontext, glutcontext, context
from OpenGLContext.move import viewplatformmixin
from OpenGL.GLUT import *
class GLUTInteractiveContext (
viewplatformmixin.ViewPlatformMixin,
interactivecontext.Interact... |
import numpy as np
try:
import scipy.optimize as opt
except ImportError:
pass
from ase.optimize.optimize import Optimizer
class Converged(Exception):
pass
class OptimizerConvergenceError(Exception):
pass
class SciPyOptimizer(Optimizer):
"""General interface for SciPy optimizers
Only the call to ... |
from h2o.estimators.xgboost import *
from h2o.estimators.gbm import *
from tests import pyunit_utils
def xgboost_vs_gbm_monotone_test():
assert H2OXGBoostEstimator.available() is True
monotone_constraints = {
"AGE": 1
}
xgboost_params = {
"tree_method": "exact",
"seed": 123,
... |
import six
from pyface.action.menu_manager import MenuManager
from pyface.tasks.traits_dock_pane import TraitsDockPane
from traits.api import Int, Property, Button, Instance
from traits.has_traits import MetaHasTraits
from traitsui.api import (
View,
UItem,
VGroup,
InstanceEditor,
HGroup,
VSplit... |
from java.lang import Long, Object
from clamp import clamp_base, Constant
TestBase = clamp_base("org")
class ConstSample(TestBase, Object):
myConstant = Constant(Long(1234), Long.TYPE) |
"""Parent client for calling the Cloud Spanner API.
This is the base from which all interactions with the API occur.
In the hierarchy of API concepts
* a :class:`~google.cloud.spanner_v1.client.Client` owns an
:class:`~google.cloud.spanner_v1.instance.Instance`
* a :class:`~google.cloud.spanner_v1.instance.Instance` ... |
import re
from b2.util.utility import *
from b2.build import feature
from b2.util import sequence, qualify_jam_action
import b2.util.set
from b2.manager import get_manager
__re_two_ampersands = re.compile ('&&')
__re_comma = re.compile (',')
__re_split_condition = re.compile ('(.*):(<.*)')
__re_split_conditional = re.c... |
"""
Copyright 2015 SmartBear Software
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/LICENSE-2.0
Unless required by applicable law or agreed to... |
import mock
from keystone import catalog
from keystone.common import manager
from keystone.tests import unit
class TestCreateLegacyDriver(unit.BaseTestCase):
@mock.patch('oslo_log.versionutils.report_deprecated_feature')
def test_class_is_properly_deprecated(self, mock_reporter):
Driver = manager.create... |
from a10sdk.common.A10BaseClass import A10BaseClass
class SslCertKey(A10BaseClass):
""" :param action: {"optional": true, "enum": ["create", "import", "export", "copy", "rename", "check", "replace", "delete"], "type": "string", "description": "'create': create; 'import': import; 'export': export; 'copy': copy; '... |
import os
import subprocess
from typing import Sequence
from pants.util.osutil import get_os_name
class IdeaNotFoundException(Exception):
"""Could not find Idea executable."""
class OpenError(Exception):
"""Indicates an error opening a file in a desktop application."""
def _mac_open_with_idea(file_: str, lookup... |
"""
Copyright 2015 Ericsson AB
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/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distr... |
# 14.
print_log('\n14. Issuer (Trust Anchor) is creating a Credential Offer for Prover\n')
cred_offer_json = await anoncreds.issuer_create_credential_offer(issuer_wallet_handle,
cred_def_id)
print_log('Credential Of... |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('data_log', '0008_auto_20190402_2035'),
]
operations = [
migrations.AlterModelOptions(
name='craftrunelog',
options={'get_latest_by': 'ti... |
"""
Client side of the volume RPC API.
"""
from oslo.config import cfg
from cinder.openstack.common import rpc
import cinder.openstack.common.rpc.proxy
CONF = cfg.CONF
class VolumeAPI(cinder.openstack.common.rpc.proxy.RpcProxy):
'''Client side of the volume rpc API.
API version history:
1.0 - Initial ve... |
"""
Description:
Issue Transaction
Usage:
from AntShares.Core.IssueTransaction import IssueTransaction
"""
from AntShares.Core.AssetType import AssetType
from AntShares.Helper import *
from AntShares.Core.Transaction import Transaction
from AntShares.Core.TransactionType import TransactionType
from random impor... |
from plenum.common.event_bus import InternalBus
from plenum.common.startable import Mode
from plenum.common.timer import QueueTimer
from plenum.common.util import get_utc_epoch
from plenum.server.consensus.primary_selector import RoundRobinConstantNodesPrimariesSelector
from plenum.server.database_manager import Databa... |
from distutils.core import setup, Extension
module1=Extension('hamsterdb',
libraries=['hamsterdb'],
include_dirs=['../include'],
library_dirs=['../src/.libs'],
sources=['src/python.cc'])
setup(name='hamsterdb-python',
version='2.1.8',
author='Christoph Rupp',
author_email='chri... |
from google.net.proto import ProtocolBuffer
import array
import dummy_thread as thread
__pychecker__ = """maxreturns=0 maxbranches=0 no-callinit
unusednames=printElemNumber,debug_strs no-special"""
if hasattr(ProtocolBuffer, 'ExtendableProtocolMessage'):
_extension_runtime = True
_ExtendableProto... |
'''
Python Homework with Chipotle data
https://github.com/TheUpshot/chipotle
'''
'''
BASIC LEVEL
PART 1: Read in the file with csv.reader() and store it in an object called 'file_nested_list'.
Hint: This is a TSV file, and csv.reader() needs to be told how to handle it.
https://docs.python.org/2/library/csv.html
... |
from c7n.query import QueryResourceManager
from c7n.manager import resources
@resources.register('iot')
class IoT(QueryResourceManager):
class resource_type(object):
service = 'iot'
enum_spec = ('list_things', 'things', None)
name = "thingName"
id = "thingName"
dimension = No... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tilecache', '0002_auto_20160317_1519'),
]
operations = [
migrations.AlterModelOptions(
name='channel',
options={'managed': True},
... |
archs_list = ['ARM', 'ARM64', 'MIPS', 'MIPS64', 'X86', 'X86_64'] |
from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.utils.typechecks import assert_is_type
from h2o.frame import H2OFrame
def h2o_H2OFrame_ascharacter():
"""
Python API test: h2o.frame.H2OFrame.ascharacter()
Copied from pyunit_as... |
from __future__ import print_function
import transitfeed
from optparse import OptionParser
import re
stops = {}
def AddRouteToSchedule(schedule, table):
if len(table) >= 2:
r = schedule.AddRoute(short_name=table[0][0], long_name=table[0][1], route_type='Bus')
for trip in table[2:]:
if len(trip) > len(ta... |
"""A module with functions for working with GRR packages."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import importlib
import inspect
import logging
import os
import sys
import pkg_resources
from typing import Text
from grr_response_core.lib.util imp... |
import os.path
import sys
from logging import Logger
import logging.config
import traceback
from daemon import runner
import signal
from ConfigParser import SafeConfigParser, NoSectionError
from optparse import OptionParser
from bagpipe.bgp.common import utils
from bagpipe.bgp.common.looking_glass import LookingGlass, ... |
"""Contains the logic for `aq update interface --machine`."""
from aquilon.exceptions_ import ArgumentError, AquilonError
from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611
from aquilon.worker.dbwrappers.interface import (verify_port_group,
choose_p... |
''' Sample usage of function 'inventory_not_connected' to show which devices are mounted, but not connected.
Print the function's documentation then invoke the function and print the output.
'''
from __future__ import print_function as _print_function
from basics.inventory import inventory_not_connected
from basics... |
from airflow.hooks.oracle_hook import OracleHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class OracleOperator(BaseOperator):
"""
Executes sql code in a specific Oracle database
:param oracle_conn_id: reference to a specific Oracle database
:type oracle... |
from __future__ import print_function
import unittest
import numpy
import paddle.fluid.core as core
import paddle.fluid as fluid
class TestExecutor(unittest.TestCase):
def net(self):
lr = fluid.data(name="lr", shape=[1], dtype='float32')
x = fluid.data(name="x", shape=[None, 1], dtype='float32')
... |
"""Test the IPython.kernel public API
Authors
-------
* MinRK
"""
import nose.tools as nt
from IPython.testing import decorators as dec
from IPython.kernel import launcher, connect
from IPython import kernel
@dec.parametric
def test_kms():
for base in ("", "Multi"):
KM = base + "KernelManager"
yield... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import shutil
import tempfile
from pants.base.build_invalidator import CacheKey, CacheKeyGenerator
from pants.base.cache_manager import InvalidationCacheManager, Invali... |
import logging
import sys
from bs4 import BeautifulSoup
import urllib2
import re
_parser = "lxml" ## remember to pip install lxml or else use another parser
_loggingLevel = logging.DEBUG ## How much trace
class AltmetricBase:
def __init__(self, name, snLink, altmetricId, startPage, endPage):
self.name ... |
import logging
import sys
import os
import signal
import conf
import core
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol.TBinaryProtocol import TBinaryProtocolAcceleratedFactory
from thrift.server import TServer
from rpc import RndNodeApi
logger = logging.getLogger(__n... |
import lib_v2 as lib
import sys
import os
def main(argv=None):
"""
Usage is:
submit.py [--account <chargecode>] [--url <url>] -- <commandline>
Run from the working dir of the job which must contain (in addition
to the job files) a file named scheduler.conf with scheduler properties for the job.
... |
"""Tests for api module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import gc
import imp
import os
import re
import textwrap
import types
import numpy as np
from tensorflow.python.autograph import utils
from tensorf... |
import time
from headset import Headset
from stream import Stream
from common import Version, BytesStatus
class WirelessHeadset(Headset):
"""This class represents the wireless version of the mindwave
Args:
dev: device link
headset: the id of mindwave wireless version
It has the basic functio... |
"""Unit tests to cover DfpUtils."""
__author__ = 'api.jdilallo@gmail.com (Joseph DiLallo)'
import os
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.join('..', '..', '..'))
import mock
from adspygoogle import DfpClient
from adspygoogle.common.Errors import ValidationError
from adspygoogle.dfp impo... |
"""Parser for Windows EventLog (EVT) files."""
import pyevt
from plaso import dependencies
from plaso.events import time_events
from plaso.lib import errors
from plaso.lib import eventdata
from plaso.lib import specification
from plaso.parsers import interface
from plaso.parsers import manager
dependencies.CheckModuleV... |
"""A simple wrapper to send email alerts."""
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import logging
import re
import smtplib
import socket
from grr.lib import config_lib
from grr.lib import registry
from grr.lib.... |
"""
(c) 2020 Kirk Byers <ktbyers@twb-tech.com>
(c) 2016 Elisa Jasinska <elisa@bigwaveit.org>
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 as published by
the Free Software Foundation, either version 3 of the License, or... |
"""Tests for the nut integration."""
import json
from unittest.mock import MagicMock, patch
from homeassistant.components.nut.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_RESOURCES
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, load_fixture
def _... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_hackathon_name'),
]
operations = [
migrations.AlterField(
model_name='hackathon',
name='name',
field=mode... |
from . import ObjectCreationParameters
__author__ = 'Shamal Faily'
class ResponseParameters(ObjectCreationParameters.ObjectCreationParameters):
def __init__(self,respName,respRisk,tags,cProps,rType):
ObjectCreationParameters.ObjectCreationParameters.__init__(self)
self.theName = respName
self.theTags = ta... |
from openstack import profile
class Profile(profile.Profile):
def __init__(self, region, plugins=None, **kwargs):
super(Profile, self).__init__(plugins=plugins or ['rackspace'])
self.set_region(self.ALL, region)
global_services = ('cloudMetrics', 'cloudMetricsIngest',
... |
import itertools
import struct
from ryu.ofproto import ofproto_common
from ryu.lib.pack_utils import msg_pack_into
from ryu.lib import type_desc
OFPXMC_NXM_0 = 0 # Nicira Extended Match (NXM_OF_)
OFPXMC_NXM_1 = 1 # Nicira Extended Match (NXM_NX_)
OFPXMC_OPENFLOW_BASIC = 0x8000
OFPXMC_PACKET_REGS = 0x8001
OFPXMC_EXPER... |
from plow.gui.manifest import QtCore, QtGui
from plow.gui.util import formatDateTime, formatDuration
__all__ = [
"Text",
"Number",
"Decimal",
"DateTime",
"PillWidget",
"Checkbox"
]
class FormWidget(QtGui.QWidget):
"""
The base class for all form widgets.
"""
__LOCKED_PIX = None
... |
"""Tests for google.apphosting.tools.devappserver2.module."""
import httplib
import logging
import os
import re
import time
import unittest
import google
import mox
from google.appengine.api import appinfo
from google.appengine.api import request_info
from google.appengine.tools.devappserver2 import api_server
from goo... |
from pyasn1 import debug
from pyasn1 import error
from pyasn1.codec.ber import eoo
from pyasn1.compat.integer import from_bytes
from pyasn1.compat.octets import oct2int, octs2ints, ints2octs, null
from pyasn1.type import base
from pyasn1.type import char
from pyasn1.type import tag
from pyasn1.type import tagmap
from p... |
from __future__ import print_function
import unittest
import numpy as np
import paddle.fluid as fluid
import os
def data_generator():
data = [0, 1, 2, 3]
for val in data:
yield val
class TestDistributedReader(unittest.TestCase):
def test_distributed_reader(self):
trainer_num = 4
os.e... |
"""
Plots a scatter plot of 2 metrics provided.
Data could be given from postgres or a csv file.
"""
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from common import add_db... |
"""Implementation of basic magic functions."""
import argparse
import textwrap
import io
import sys
from pprint import pformat
from IPython.core import magic_arguments, page
from IPython.core.error import UsageError
from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
from IPython.utils.text i... |
"""
Django ID mapper
Modified for Evennia by making sure that no model references
leave caching unexpectedly (no use if WeakRefs).
Also adds cache_size() for monitoring the size of the cache.
"""
import os, threading
from twisted.internet.reactor import callFromThread
from django.core.exceptions import ObjectDoesNotExi... |
from unittest import mock
from django.db import connection, migrations
try:
from django.contrib.postgres.operations import (
BloomExtension, BtreeGinExtension, BtreeGistExtension, CITextExtension,
CreateExtension, CryptoExtension, HStoreExtension, TrigramExtension,
UnaccentExtension,
)
e... |
""" astropy.cosmology contains classes and functions for cosmological
distance measures and other cosmology-related calculations.
See the `Astropy documentation
<https://docs.astropy.org/en/latest/cosmology/index.html>`_ for more
detailed usage examples and references.
"""
from . import core, flrw, funcs, parameter, un... |
from django.utils.translation import ugettext_lazy as _
SEARCH_FORM_KEYWORDS = _(u'Key Words / Profession')
SEARCH_FORM_LOCATION = _(u'City, State or Zip Code')
SEARCH_FILTERS_FORM_JOB_POSITION = _(u'Job Position')
SEARCH_FILTERS_FORM_EXPERIENCE_YEARS = _(u'Experience')
SEARCH_FILTERS_FORM_DISTANCE = _(u'Distance')
SEA... |
""":mod:`itertools` is full of great examples of Python generator
usage. However, there are still some critical gaps. ``iterutils``
fills many of those gaps with featureful, tested, and Pythonic
solutions.
Many of the functions below have two versions, one which
returns an iterator (denoted by the ``*_iter`` naming pat... |
class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Prompt',
# list of one or more authors for the module
'Au... |
from __future__ import unicode_literals
from django.conf.urls import patterns
from django.conf.urls import url
from django.contrib.admin.sites import AlreadyRegistered
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
from django.db.models import signals
... |
import sys
from apps.cowry.exceptions import PaymentMethodNotFound
from django.utils.importlib import import_module
def _load_from_module(path):
package, attr = path.rsplit('.', 1)
module = import_module(package)
return getattr(module, attr)
ADAPTERS = ('apps.cowry_docdata.adapters.DocDataPaymentAdapter',)
... |
"""
Example OAuthenticator to use with My Service
"""
import json
from jupyterhub.auth import LocalAuthenticator
from oauthenticator.oauth2 import OAuthLoginHandler, OAuthenticator
from tornado.auth import OAuth2Mixin
from tornado.httputil import url_concat
from tornado.httpclient import HTTPRequest, AsyncHTTPClient, H... |
class ServiceError(Exception):
"""Base class for exceptions in this module."""
pass
class UnsupportedFormatError(ServiceError):
"""Used to raise exceptions when a response doesn't match expected semantics or for failed version checks."""
pass
class MissingLayerError(ServiceError):
"""Used if expecte... |
from django.contrib import admin
from ionyweb.page.models import Page, Layout
admin.site.register(Page)
admin.site.register(Layout) |
from distutils.core import setup
setup(
name='PyMonad',
version='1.3',
author='Jason DeLaat',
author_email='jason.develops@gmail.com',
packages=['pymonad', 'pymonad.test'],
url='https://bitbucket.org/jason_delaat/pymonad',
license=open('LICENSE.txt').read(),
description='Collection of cl... |
"""Module containing the various stages that a builder runs."""
import json
import logging
import os
from chromite.cbuildbot import commands
from chromite.cbuildbot import failures_lib
from chromite.cbuildbot import cbuildbot_run
from chromite.cbuildbot.stages import artifact_stages
from chromite.lib import cros_build_... |
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from past.utils import old_div
import unittest
import json
import logging
imp... |
"""
Module to read MODPATH output files. The module contains two
important classes that can be accessed by the user.
* EndpointFile (ascii endpoint file)
* PathlineFile (ascii pathline file)
"""
import numpy as np
from ..utils.flopy_io import loadtxt
class PathlineFile():
"""
PathlineFile Class.
Paramete... |
def iacolorhist(f, mask=None):
import numpy as np
from iahistogram import iahistogram
WFRAME=5
f = np.asarray(f)
if len(f.shape) == 1: f = f[np.newaxis,:]
if not f.dtype == 'uint8':
raise Exception,'error, can only process uint8 images'
if not f.shape[0] == 3:
raise Exception, 'e... |
from os.path import dirname
import sys
from django.test import TestCase
from django.conf import settings
from django.test.utils import override_settings
import oscar
from oscar.core.loading import (
get_model, AppNotFoundError, get_classes, get_class, ClassNotFoundError)
from oscar.test.factories import create_prod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.