code
stringlengths
1
199k
"""Starter script for Cinder Volume Backup.""" import logging as python_logging import shlex import sys import eventlet eventlet.monkey_patch() from oslo_config import cfg from oslo_log import log as logging from oslo_privsep import priv_context from oslo_reports import guru_meditation_report as gmr from oslo_reports i...
from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import quota QUOTAS = quota.QUOTAS XMLNS = "http://docs.openstack.org/compute/ext/used_limits/api/v1.1" ALIAS = "os-used-limits" authorize = extensions.soft_extension_authorizer('compute', 'use...
try: import unittest2 as unittest except ImportError: import unittest # noqa import difflib from mock import Mock import six, logging, sys, traceback from cassandra import AlreadyExists, OperationTimedOut from cassandra.cluster import Cluster from cassandra.metadata import (Metadata, KeyspaceMetadata, TableMet...
from setuptools import setup,find_packages setup( name="HelloWorld", version="0.1", packages=find_packages(), )
""" See COPYING for license information """ import sys import os from string import Template from swift_setup.common.exceptions import ConfigFileError, \ ResponseError, TemplateFileError from swift_setup.common.utils import readconf class TemplateGen(object): """ This class is used for generation of the tem...
import time import errno import socket from weakref import ref as weakref from itertools import izip from redis import StrictRedis from redis.client import list_or_args from redis.exceptions import ConnectionError try: from redis.exceptions import TimeoutError except ImportError: TimeoutError = ConnectionError ...
from ocs_sample_library_preview import OCSClient, Streams import configparser config = configparser.ConfigParser() config.read('config.ini') client: OCSClient = OCSClient(config.get('Access', 'ApiVersion'),config.get('Access', 'Tenant'), config.get('Access', 'Resource'), config.get('Credentials', '...
get_ipython().run_line_magic('cat', '0Source_Citation.txt') get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'retina'") import matplotlib.pyplot as plt import numpy as np from uncertainties import unumpy as unp import pytheos as eos eta = np.lins...
import pytest from Fixture.application import Application @pytest.fixture(scope="session") def app(request): fixture = Application() request.addfinalizer(fixture.destroy) return fixture
class TestCase: def __init__(self): self.audience_count = 0 self.audience = 0 def compute_friend(self): standing_ovation_count = 0 friend = 0 for x in range(len(self.audience)): if (standing_ovation_count >= x): standing_ovation_count += self.a...
from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.rst', encoding='utf-8') as f: long_description = f.read() setup( name='overpass', packages=['overpass'], version='0.3.1', description='Python wrapper for the OpenStreetMap Overpass API', l...
import requests import json from requests.auth import HTTPBasicAuth def enum(**enums): return type('Enum', (), enums) class OpServerUtils(object): POST_HEADERS = {'Content-type': 'application/json; charset="UTF-8"'} @staticmethod def post_url_http(logger, url, data, user, password, headers=None): ...
""" Symlink Middleware Symlinks are objects stored in Swift that contain a reference to another object (hereinafter, this is called "target object"). They are analogous to symbolic links in Unix-like operating systems. The existence of a symlink object does not affect the target object in any way. An important use case...
import sys import os import time import datetime import traceback from threading import Thread from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.support.select import Select TEST_RANGE=[ list(range(1,5)), list(range(5,27)), list(range(27,30)), list(range(30,31)), list(ra...
from solumclient.openstack.common.apiclient import fake_client from solumclient.tests import base from solumclient.v1 import client as sclient from solumclient.v1 import component component_list = [ { 'uri': 'http://example.com/v1/components/c1', 'name': 'php-web-app', 'type': 'component', ...
import netaddr from tempest_lib import exceptions as lib_exc from tempest import clients from tempest.common.utils import data_utils from tempest import config from tempest import exceptions from tempest.openstack.common import log as logging import tempest.test CONF = config.CONF LOG = logging.getLogger(__name__) clas...
from lxml import etree from webob import exc from nova.api.openstack.compute.contrib import hypervisors from nova.api.openstack import extensions from nova import context from nova import db from nova import exception from nova import test from nova.tests.api.openstack import fakes TEST_HYPERS = [ dict(id=1, ...
from __future__ import print_function import numpy as np import scipy as sp import matplotlib.pyplot as plt import sys import argparse import gzip import re import os import math def main(): parser=argparse.ArgumentParser(description='signal pile up plot for bedGraph/wiggle tracks',formatter_class=argparse.Argument...
UNITS_PER_CONCEPT = { "Bandwidth": "GB", } def default_total_calc(entries): return sum([int(entry.value) for entry in entries]) def bytes_total_calc(entries): return default_total_calc(entries) / 1073741824 def bytehrs_total_calc(entries): totals = {} for entry in entries: if entry.value not...
import collections import json import os import tensorflow as tf import utils INPUT_FILES = 'gs://tabletalk-wit/wit/split/wit_v1.ai.{}.en.recordio-*' EVAL_DATA_DIR = 'gs://mmt/wit/inference_data/all' INPUT_FILES = 'gs://tabletalk-wit/wit/split/wit_v1.ai.{}.en.recordio-0000*' EVAL_DATA_DIR ='gs://mmt/wit/inference_data/...
from .core import Captcha from .exceptions import CaptchaVerifyFailed from inspect import getargspec def check_captcha(field_name = 'captcha'): def outer(func): def func_inner(request, *args, **kwargs): captcha = Captcha(request) if not captcha.check(request.DATA.get(field_name, None)): raise CaptchaVerify...
from alembic import context from sqlalchemy import create_engine, pool from storyboard.db import models config = context.config storyboard_config = config.storyboard_config target_metadata = models.Base.metadata def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with ...
from prime_check import isprime from string import maketrans list_of_primes = [] for i in range(49999,499999): j = 2*i + 1 sj = str(j) f = False if sj.count('0') == 3: f = True elif sj.count('1') == 3: if sj[5:] != '1': f = True elif sj.count('2') == 3: f = Tr...
from typing import ( Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, ) from google.cloud.recommendationengine_v1beta1.types import ( prediction_apikey_registry_service, ) class ListPredictionApiKeyRegistrationsPager: """A pager for iterating through ...
""" Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class V1NamespaceSpec(obje...
import os from oslo_log import log as logging from oslo_utils import netutils from trove.common import cfg from trove.common import exception from trove.common import utils from trove.common.db.postgresql import models from trove.guestagent.common import operating_system from trove.guestagent.common.operating_system im...
"""Defines the class that manages the syncing of the scheduler with the job type models""" from __future__ import unicode_literals import logging import threading from job.models import JobType from job.seed.exceptions import InvalidSeedMetadataDefinition logger = logging.getLogger(__name__) class JobTypeManager(object...
import unittest from rx.observable import Observable from rx.testing import TestScheduler, ReactiveTest from rx.disposables import Disposable, SerialDisposable on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = Reactiv...
from django import forms from import_export.forms import ConfirmImportForm, ImportForm from .models import Author class AuthorFormMixin(forms.Form): author = forms.ModelChoiceField(queryset=Author.objects.all(), required=True) class CustomImportForm(AuthorFormMixin, ImportForm): ...
import io import psycopg2 from psycopg2 import sql from psycopg2.extras import RealDictCursor import sys import json import datetime import decimal import time import os import binascii from distutils.sysconfig import get_python_lib import multiprocessing as mp class pg_encoder(json.JSONEncoder): def default(self, ...
""" This defines the :class:`Plugin` and :class:`Site` classes. """ import os from os.path import normpath, dirname, join, isdir import inspect import datetime import warnings from atelier.utils import AttrDict, ispure, date_offset PLUGIN_CONFIGS = {} def configure_plugin(app_label, **kwargs): cfg = PLUGIN_CONFIG...
from django.conf import settings from django.core.exceptions import ( PermissionDenied, ValidationError ) from django.core.mail import send_mail from django.core.urlresolvers import reverse_lazy from django.http import Http404, HttpResponseServerError from django.shortcuts import render from django.template imp...
"""The binary column class of the dataframe creator, create binary sparse data (e.g. NLP outputs)""" import numpy as np import warnings __author__ = "Peter J Usherwood" __python_version__ = "3.6" class Binary: """ Produce a column of binary 1,0 values at a given ratio. """ def __init__(self, name='Test ...
import random import math import sys import getopt import array import os import copy def usage(): print "\ Usage: genparams.py -[hs:p:i:d:o:m:a:b:t:]\n\ -h --help print this help\n\ -s --size= specify size (max) of priority queue\n\ -p --priority= specify the initial priority range to g...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0007_auto_20170220_1242'), ] operations = [ migrations.AlterField( model_name='scholariumprofile', name='kaeufe', ...
from numba import cuda from numba.cuda.cudadrv.driver import driver from numba import numpy_support as nps import math def transpose(a, b=None): """Compute the transpose of 'a' and store it into 'b', if given, and return it. If 'b' is not given, allocate a new array and return that. This implements the ...
from django.core import management if __name__ == "__main__": management.execute_from_command_line()
import unittest from tap.directive import Directive from tap.line import Line, Result class TestLine(unittest.TestCase): """Tests for tap.line.Line""" def test_line_requires_category(self): line = Line() with self.assertRaises(NotImplementedError): line.category class TestResult(unit...
""" @package mi.dataset.driver.mflm.flort.test.test_driver @file marine-integrations/mi/dataset/driver/mflm/flort/driver.py @author Emily Hahn @brief Test cases for mflm_flort driver USAGE: Make tests verbose and provide stdout * From the IDK $ bin/dsa/test_driver $ bin/dsa/test_driver -i [-t testname...
import pygtk import gtk from optparse import OptionParser import glob import os class Aligner: """ Create a class for the main application. """ def __init__(self, folder): """ Intialize the Aligner class. Load the image files, create the window and context, and show the first ima...
from __future__ import unicode_literals from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from djam.riffs.base import Riff from djam.views.dashboard import DashboardView class DashboardRiff(Riff): dashboard_view = DashboardView display_name = _('Dashboard') s...
''' Created by auto_sdk on 2015.04.21 ''' from aliyun.api.base import RestApi class Ess20140828DeleteScalingConfigurationRequest(RestApi): def __init__(self,domain='ess.aliyuncs.com',port=80): RestApi.__init__(self,domain, port) self.ScalingConfigurationId = None def getapiname(self): return 'ess.aliyuncs.com.D...
import logging l = logging.getLogger(name=__name__) import claripy from .plugin import SimStatePlugin class SimStateScratch(SimStatePlugin): """ Implements the scratch state plugin. """ def __init__(self, scratch=None): super().__init__() # info on the current run self.irsb = Non...
from collections import Iterable from django.contrib.auth.models import Group, Permission, User from django.db.models.query import QuerySet from notifier.models import Notification, Backend, UserPrefs def create_notification(name, display_name=None, permissions=None, backends=None, public=True):...
"""Collection of utility functions for matplotlib""" from contextlib import contextmanager, suppress import numpy as np import matplotlib as mpl import matplotlib.style as mpl_style import matplotlib.pyplot as plt from .utils import with_defaults __all__ = ['cm2inch', 'colorbar', 'despine', 'despine_all', 'get_palette'...
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.conf import settings class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Trek.publication_date' db.add_column('o_t_itinerair...
import json from dsat.data import create_rrd_if , open_rrd, write_rrd from dsat.state import Connector from time import time import sys cfg = json.load(open("rrd.json")) rrd_l = dict() for rrd_db in cfg.keys(): if rrd_db.startswith("_"): continue else: this_cfg = cfg[rrd_db] if isinstance...
from beehive import then from beehive4cmd0.command_steps import \ step_command_output_should_contain_text, \ step_command_output_should_not_contain_text CSI = u"\x1b[" @then(u'the command output should contain ANSI escape sequences') def step_command_ouput_should_contain_ansi_sequences(context): step_comman...
from redis_monitor import get_instance import time class MonitoredCursorWrapper(object): def __init__(self, cursor, db): self.cursor = cursor self.db = db self.rm = get_instance('sqlops') def execute(self, sql, params=()): start = time.time() try: return self....
""" Created on Tue May 2 12:39:23 2017 @author: carl """ import numpy as np import tensorflow as tf from tensorflow.contrib import rnn import os class RNN: def __init__(self,features,targ,val,val_targ,filename,n_hidden=[100,100],n_layers=2,cell_type='LSTMP',dropout=0.25,init_method='zero',truncated=1000,optimizer=...
""" Module that defines all actions in this world. """ from pddlpy.predicate import Predicate from pddlpy.scope import Scope class Action(object): """ Base class for all actions. """ def __init__(self): pass def __getattr__(self, item): """ Attempt to resolve unknown attribut...
""" Slice implementation. """ from __future__ import print_function, division, absolute_import from itertools import starmap from flypy import sjit, jit, typeof, conversion import flypy.runtime @sjit('Slice[start, stop, step]') class Slice(object): layout = [('start', 'start'), ('stop', 'stop'), ('step', 'step')] ...
import subprocess import paths import os.path class CRFClassifier: def __init__(self, name, model_type, model_path, model_file, verbose): self.verbose = verbose self.name = name self.type = model_type self.model_fname = model_file self.model_path = model_path if not o...
class RedisError(Exception): pass class ConnectionError(RedisError): pass class RequestError(RedisError): def __init__(self, message, cmd_line=None): self.message = message self.cmd_line = cmd_line def __repr__(self): if self.cmd_line: return 'RequestError (on %s [%s,...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('retailers', '0005_auto_20150220_0027'), ] operations = [ migrations.AlterField( model_name='retailer', name='slug', f...
import functools from django.db import migrations, models import dash.utils class Migration(migrations.Migration): dependencies = [ ("orgs", "0028_alter_org_config"), ] operations = [ migrations.AlterField( model_name="org", name="logo", field=models.Image...
import os, sys sys.path.insert(0, os.path.join("..","..")) from nodebox.graphics.context import * from nodebox.graphics import * def draw(canvas): canvas.clear() # Set the background color to a specific hue of red background(0.16, 0, 0) # Set filling off, so ovals will be stroked only nofill() f...
""" .. argparse:: :module: py_trees.demos.dot_graphs :func: command_line_argument_parser :prog: py-trees-demo-dot-graphs .. graphviz:: dot/demo-dot-graphs.dot """ import argparse import subprocess import py_trees import py_trees.console as console def description(): name = "py-trees-demo-dot-graphs" co...
from os import environ import re from logging import getLogger, NullHandler import time import simplejson from otto.lib.otypes import InitiatorError, ReturnCode from otto.lib.contextmanagers import cd from otto.lib.common import wait_file_exists, exists from otto.lib.decorators import wait_until instance = environ.get(...
from __future__ import absolute_import from django.conf import settings from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ from sentry import roles from sentry.web.frontend.base import Orga...
__author__ = 'mdavid' import base64 import json import logging import os import re import tempfile from dns import rdatatype, rdataclass from unbound import ub_ctx from namecoin import NamecoinClient log = logging.getLogger() class NamecoinValueException(Exception): pass class NoNameserverException(Exception): ...
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 'TeamResult.referee' db.add_column('scorebrd_teamresult', 'referee', self.gf('django.db.models.fie...
""" WSGI config for noclite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "noclite.settings") from django.core.wsgi ...
import os import threading import _magic __version__ = '0.0.1' def open(mime=False, magic_file=None, mime_encoding=False, keep_going=False): flags = _magic.MAGIC_NONE if mime: flags |= _magic.MAGIC_MIME_TYPE elif mime_encoding: flags |= _magic.MAGIC_MIME_ENCODING if kee...
"""Tests for tools and arithmetics for monomials of distributed polynomials.""" import functools import pytest from diofant import Monomial, itermonomials from diofant.abc import a, b, c, x, y, z __all__ = () def test_monomials(): assert set(itermonomials([], 0)) == {1} assert set(itermonomials([], 1)) == {1} ...
""" Indiweb endpoint urls. Add these to your root URLconf if you're using the indieweb endpoints: urlpatterns = [ ... url(r'^indieweb/', include('indieweb.urls', namespace='indieweb')) ] In Django versions older than 1.9, the urls must be namespaced as 'indieweb'. """ from __future__ import unic...
from __future__ import division from itertools import product import numpy as np from numpy.linalg import norm from numpy.testing import (assert_, assert_allclose, assert_raises, assert_equal) from scipy._lib._numpy_compat import suppress_warnings from scipy.sparse import issparse, lil_matrix...
from pandas.io.excel._base import ExcelWriter from pandas.io.excel._util import _validate_freeze_panes class _OpenpyxlWriter(ExcelWriter): engine = 'openpyxl' supported_extensions = ('.xlsx', '.xlsm') def __init__(self, path, engine=None, mode='w', **engine_kwargs): # Use the openpyxl module as the ...
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import pytest from byceps.util.iterables import index_of @pytest.mark.parametrize('predicate, iterable, expected', [ ( lambda x: x > 3, [], None, ), ( lambda x: x > 1, ...
''' Provide data from the `Palmer Archipelago (Antarctica) penguin dataset`_. Derived from https://github.com/mwaskom/seaborn-data/blob/master/penguins.csv Data distributed under the `CC-0`_ license. This module contains one pandas Dataframe: ``data``. .. rubric:: ``data`` :bokeh-dataframe:`bokeh.sampledata.penguins.da...
import qisrc.sync import qisrc.manifest import qisrc.git from qisrc.test.conftest import TestGitWorkTree import qisys.sh def test_stores_url_and_groups(git_worktree, git_server): git_server.create_group("mygroup", ["foo", "bar"]) manifest_url = git_server.manifest_url worktree_syncer = qisrc.sync.WorkTreeSy...
from datetime import date, datetime, timedelta from django.db import models from django.db.models.query import QuerySet def get_current_date(): return date(datetime.now().year, datetime.now().month, datetime.now().day) class EntryTermManager(models.Manager): """ Return all terms which need to fetch as query...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 12, transform = "Difference", sigma = 0.0, exog_count = 20, ar_order = 0);
import os import logging from datetime import timedelta import sys gettext = lambda x: x DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'NAME': 'dev.db', 'ENGINE': 'django.db.backends.sqlite3', }, } TIME...
"""Grab documentation from spm.""" import os from nipype.interfaces import matlab def grab_doc(task_name): """Grab the SPM documentation for the given SPM task named `task_name` Parameters ---------- task_name : string Task name for which we are grabbing documentation. Example task name...
LOG_FORMAT="%(asctime)s [%(process)s] [%(levelname)s] [%(name)s] %(message)s" DATE_FORMAT="%Y-%m-%d %H:%M:%S" API_ADDRESS = "tcp://127.0.0.1:5000"
import unittest from telemetry.internal.platform import android_platform_backend from telemetry.internal.platform.power_monitor import sysfs_power_monitor class SysfsPowerMonitorMonitorTest(unittest.TestCase): initial_freq = { 'cpu0': '1700000 6227\n1600000 0\n1500000 0\n1400000 28\n1300000 22\n' '120...
import structlog import libtaxii.messages_11 as tm11 import libtaxii.messages_10 as tm10 from libtaxii.constants import ( SD_SUPPORTED_CONTENT, ST_UNSUPPORTED_CONTENT_BINDING, SD_ITEM, ST_NOT_FOUND, ST_BAD_MESSAGE, ACT_SUBSCRIBE, ACT_UNSUBSCRIBE, ACT_PAUSE, ACT_RESUME, ACT_STATUS, ACT_TYPES_11, ACT_...
import os from django.conf import settings from django.core.cache import get_cache from django.core.cache.backends.db import BaseDatabaseCache from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.creation import DatabaseCreation class SpatiaLiteCreation(DatabaseCreation): def crea...
from Acquisition import aq_parent from BTrees.OOBTree import OOBTree from Products.CMFCore.utils import getToolByName from Products.CMFPlone.i18nl10n import ulocalized_time from Products.CMFPlone.utils import safe_unicode from bda.plone.cart import CartItemStateBase from bda.plone.cart import aggregate_cart_item_count ...
""" tests.redis_test ~~~~~ Testing Flask-Redis :copyright: (c) 2013 by netzinformatik UG. :author: Tobias Werner <mail@tobiaswerner.net> :license: BSD, see LICENSE for more details. """ import mock from tests import FlaskRedisTestCase class RedisTestCase(FlaskRedisTestCase): def test_app(sel...
import unittest from unittest.case import expectedFailure from warnings import warn from rdflib import DCTERMS from rdflib.graph import Graph from rdflib.namespace import ( FOAF, OWL, RDF, RDFS, SH, DefinedNamespaceMeta, Namespace, ClosedNamespace, URIPattern, ) from rdflib.term impo...
import os import sys join = os.path.join split = os.path.split splitext = os.path.splitext relpath = os.path.relpath def _verbose(msg): print( "%s" % msg ) def _silent(msg): pass verbose = _verbose #_silent def mkdir_if_not_exists(path): if not os.path.exists(path): os.mkdir(path) def replace_tags(i...
from __future__ import absolute_import from django.conf import settings from django.db import IntegrityError, models, transaction from django.utils import timezone from enum import Enum from sentry.db.models import FlexibleForeignKey, Model, UUIDField from sentry.db.models import ArrayField, sane_repr from sentry.db.mo...
from __future__ import unicode_literals import math import unittest from nose.tools import * from py_stringmatching.similarity_measure.soundex import Soundex class SoundexTestCases(unittest.TestCase): def setUp(self): self.sdx = Soundex() def test_valid_input_raw_score(self): self.assertEqual(se...
import json import os import re import sys root = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../../..')) with open(os.path.join(root, 'tools', 'run_tests', 'sources_and_headers.json')) as f: js = json.loads(f.read()) re_inc1 = re.compile(r'^#\s*include\s*"([^"]*)"') assert re_inc1.match('#include "fo...
import matplotlib matplotlib.use('Agg') # plotting backend compatible with screen import sys import scanpy.api as sc sc.settings.verbosity = 2 # show logging output sc.settings.autosave = True # save figures, do not show them sc.settings.set_figure_params(dpi=300) # set sufficiently high resolution for saving filen...
import random import tensorflow as tf import numpy as np import sys import z3 sys.path.append('..') # so that amnet can be imported import amnet from amnet import tf_utils from amnet import smt from tensorflow.examples.tutorials.mnist import input_data from PIL import Image def pca(A, dim): M = (A-np.mean(A.T,axis=...
""" Helper functions for serializing (and deserializing) requests. """ from ants.http import Request def request_to_dict(request, spider=None): """Convert Request object to a dict. If a spider is given, it will try to find out the name of the spider method used in the callback and store that as the callback...
""" Functions to test that map measurements haven't changed. Use generate() to save data, and test() to check that the data is unchanged in a later version. Results from generate() are already checked into svn, so intentional changes to map measurement mean new data must be generated and committed. E.g. $ ./topographic...
from django.utils import translation from django.core.cache import cache from unittest import TestCase from olympia.lib.cache import ( Message, Token, memoize, memoize_key, cache_get_or_set, make_key) def test_make_key(): with translation.override('en-US'): assert make_key(u'é@øel') == 'é@øel:en-us'...
import logging import hashlib import base64 import random import re import json try: import cPickle as pickle except ImportError: import pickle from django.conf import settings from django.db import models, transaction from django.db.models import Q from django.contrib.auth.models import User as _User from djan...
"""cl.result""" from __future__ import absolute_import from __future__ import with_statement from kombu.pools import producers from .exceptions import clError, NoReplyError __all__ = ["AsyncResult"] class AsyncResult(object): Error = clError NoReplyError = NoReplyError def __init__(self, ticket, actor): ...
import logging import pywintypes try: import win32com.client import win32api except: #Temp workaround for ci. pass log = logging def set_priority(pid=None,priority=1): """ Set The Priority of a Windows Process. Priority is a value between 0-5 where 2 is normal priority. Default sets the pr...
import collections import os import tempfile import unittest import shutil import numpy as np import torch from torch import nn from scripts.average_checkpoints import average_checkpoints class ModelWithSharedParameter(nn.Module): def __init__(self): super(ModelWithSharedParameter, self).__init__() ...
""" tests.tests_errors ~~~~~~~~~~~~~~~~~~ """ from jsonspec.validators import load from jsonspec.validators.exceptions import ValidationError from . import fixture def test_check(): validator = load(fixture('five.schema.json')) try: validator.validate({ 'creditcard': { ...
""" Tests for Skeleton object """ import pathlib import pytest import numpy as np import astropy.units as u import astropy.constants as const import astropy.time from astropy.coordinates import SkyCoord from sunpy.coordinates import HeliographicStonyhurst import distributed from distributed.utils_test import client, lo...
""" Testing signals emitted on changing m2m relations. """ from django.db import models from django.test import TestCase from .models import Car, Part, Person, SportsCar class ManyToManySignalsTest(TestCase): def m2m_changed_signal_receiver(self, signal, sender, **kwargs): message = { 'instance'...
from iconizer.django_in_iconizer.django_starter import DjangoStarter from iconizer.django_in_iconizer.postgresql_checker import PostgreSqlChecker class DjangoPostgreSqlStarter(DjangoStarter): def get_cleanup_task_descriptors(self): return [{"stop_postgresql": ["scripts\\postgresql_stop.bat"]}] def get_f...
"""Run test matrix.""" import argparse import multiprocessing import os import sys import python_utils.jobset as jobset import python_utils.report_utils as report_utils from python_utils.filter_pull_request_tests import filter_tests _ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..')) os.chdir(_...