code
stringlengths
1
199k
"""JBackend package.""" from . import views __all__ = ['views']
from tempest.api.volume import base from tempest.common.utils import data_utils from tempest import test QUOTA_KEYS = ['gigabytes', 'snapshots', 'volumes'] QUOTA_USAGE_KEYS = ['reserved', 'limit', 'in_use'] class VolumeQuotasAdminTestJSON(base.BaseVolumeV1AdminTest): _interface = "json" force_tenant_isolation =...
import conf import g import os import re import sys import time from gwis.query_overlord import Query_Overlord from item.feat import byway from item.feat import node_endpoint from item.feat import node_traverse from util_ import db_glue from util_ import geometry from util_ import gml from merge.ccp_merge_ceil import C...
import json import logging import requests import flask from werkzeug.exceptions import BadRequest from flask_restful import abort import jwt import jwt.exceptions from data_catalog.configuration import DCConfig class Security(object): def __init__(self, auth_exceptions): """ :param auth_exceptions:...
__author__ = 'ivo' """ Copyright (C) 2010 The Android Open Source Project Script for converting Google Android sparse ext4 image files to regular ext4 image file. This code is copied and rewritten from Google code. """ import argparse import logging import struct import os _log = logging.getLogger() class SparseHeader(...
if __name__ == '__main__' : # if not args.p1 or args.p1 == 'AP': # P1 = AIPlayer(1) # elif args.p1 == 'RP': # P1 = utic.RandomPlayer(1) # elif args.p1 == 'OP': # P1 = utic.OurPlayer(1) # else: # raise game.Error("Please select a valid player.") P1 = utic.OurPlayer(1) P2 = AIPlayer(2) # if not args.p2 or ...
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
from flask import request from target_lib import TargetLib from ota_interface import ProcessesManagement import flask import tempfile import os from flask import Flask import logging import json import traceback from flask_cors import CORS app = Flask(__name__, static_url_path='', static_folder='dist') CORS(app) jobs =...
import csv, logging, re, nltk from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize from sklearn import feature_extraction import tqdm class FeatureData(object): def __init__(self, article_file_path, stances_file_path): self.number_of_classes = 4 self.classes = ['agree', 'd...
from autopyfactory.interfaces import SchedInterface import logging class MaxPerCycle(SchedInterface): id = 'maxpercycle' def __init__(self, apfqueue, config, section): try: self.apfqueue = apfqueue self.log = logging.getLogger('autopyfactory.sched.%s' %apfqueue.apfqname) ...
import json import os import unittest from attributes.history import main from lib import database class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.rea...
import os,sys,string, math, numpy timelist = [] with open(sys.argv[1],'r') as fh: for line in fh: timelist.append(float(line[:-1])) timelist = sorted(timelist) print "min max median mean stddev" print timelist[0], timelist[-1], timelist[len(timelist)/2], sum(timelist)/len(timelist), numpy.std(timelist)
"""Tests for Met.no config flow.""" from unittest.mock import Mock, patch from homeassistant.components.met import config_flow from homeassistant.const import CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE from tests.common import MockConfigEntry, mock_coro async def test_show_config_form(): """Test show configurati...
import logging import threading import functools from typing import Callable, Optional def wrap_with_logs(fn: Optional[Callable] = None, target: str = __name__) -> Callable: """Calls the supplied function, and logs whether that function raised an exception or terminated normally. This is intended to be used...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('job', '0010_auto_20151208_1503'), ] operations = [ migrations.AddField( model_name='jobtype', name='max_scheduled', f...
__author__ = 'bs' import cv2 from config.Const import * from tools import Utils import numpy as np def writeImage(I): fName = SAVE_FOLDER + OUTPUT_IMAGE + JPG_EXTENSION for i in range(MAX_FILES): if not Utils.doesFileExist(fName): cv2.imwrite(SAVE_FOLDER + fName, I) break ...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from six.moves import range from pants.build_graph.build_file_aliases import BuildFileAliases from pants.base.exceptions import TaskError from pants.util.cont...
from google.cloud import dialogflow_v2beta1 def sample_list_intents(): # Create a client client = dialogflow_v2beta1.IntentsClient() # Initialize request argument(s) request = dialogflow_v2beta1.ListIntentsRequest( parent="parent_value", ) # Make the request page_result = client.list...
class Solution: def mergeStones(self, stones, K): if K > 2 and len(stones)%(K-1) != 1: return -1 ans = 0 while len(stones) != 1: print(stones, ans) tmp = [] for i in range(len(stones)-K+1): tmp.append(sum(stones[i:i+K])) x = min...
""" Template tags for rendering the sidebar. """ from django import template register = template.Library() class SidebarSelectNode(template.Node): def __init__(self, selected): self.selected = selected def render(self, context): # Store page type in template context. context['sidebar_sel...
from oslo_versionedobjects import base as ovo_base from oslo_versionedobjects import fixture import os_vif from os_vif import objects from os_vif.tests.unit import base object_data = { 'HostInfo': '1.0-4dba5ce236ea2dc559de8764995dd247', 'HostPluginInfo': '1.0-5204e579864981c9891ecb5d1c9329f2', 'HostPortProf...
"""Utility functions for point clouds.""" import gin import gin.tf import numpy as np from scipy import spatial import tensorflow as tf def flip_normals_towards_viewpoint(points, normals, viewpoint): """Flips the normals to face towards the view point. Args: points: A tf.float32 tensor of size [N, 3]. norma...
from index import app from flask import render_template, request from config import BASE_URL from closings import closings @app.route('/') def index(): page_url = BASE_URL + request.path page_title = 'School Closings' school_closings, timestamp = closings() social = { 'title': "Is Your School Cl...
import functools import json import urllib import six from tempest.common import rest_client from tempest import config CONF = config.CONF def handle_errors(f): """A decorator that allows to ignore certain types of errors.""" @functools.wraps(f) def wrapper(*args, **kwargs): param_name = 'ignore_err...
"""Info API URL handlers.""" import datetime import logging import urllib import webapp2 try: import icalendar except ImportError: icalendar = None from google.appengine.ext import db from simian import settings from simian.mac import common from simian.mac import models from simian.mac.common import applesus API_I...
import inspect import logging as std_logging import os import random from oslo.config import cfg from oslo.messaging import server as rpc_server from neutron.common import config from neutron.common import rpc as n_rpc from neutron import context from neutron.db import api as session from neutron import manager from ne...
import uuid from keystone import auth from keystone.common import config from keystone import exception from keystone import tests METHOD_NAME = 'simple_challenge_response' EXPECTED_RESPONSE = uuid.uuid4().hex DEMO_USER_ID = uuid.uuid4().hex class SimpleChallengeResponse(auth.AuthMethodHandler): method = METHOD_NAM...
""" KubeVirt API This is KubeVirt API an add-on for Kubernetes. OpenAPI spec version: 1.0.0 Contact: kubevirt-dev@googlegroups.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class V1CustomizeComponentsPatch(obje...
from geopy.geocoders import * import re import time import cPickle import datetime from datetime import timedelta import geopy.geocoders from pprint import pprint from pymongo import MongoClient import argparse geolocator = GoogleV3() #OK parser = argparse.ArgumentParser() parser.add_argument('--auth', action="store_tr...
""" Just displays a simple "welcome" page for GAEStarterKit. You will most likely want to remove this from config.installed_apps and do your own thing. """ import config from flask import Blueprint, render_template blueprint = Blueprint('welcomekit', __name__, template_folder='templates') @blueprint.route('/') def welc...
import pyeapi import replicants import os os.environ['REPLICANTS_FOLDER'] = os.path.abspath('./command_error') def main(): connection = pyeapi.client.connect( transport='https', host='localhost', username='vagrant', password='vagrant', port=12443 ) connection = replic...
r"""Benchmarks for low-level eager execution primitives. To run CPU benchmarks: bazel run -c opt benchmarks_test -- --benchmarks=. To run GPU benchmarks: bazel run --config=cuda -c opt --copt="-mavx" benchmarks_test -- \ --benchmarks=. To run a subset of benchmarks using --benchmarks flag. --benchmarks: the lis...
"""App Engine Models related to Munki.""" import datetime import logging import os import re import urllib from google.appengine.api import users from google.appengine.ext import blobstore from google.appengine.ext import db from google.appengine.ext import deferred from simian.mac import common from simian.mac.common ...
import re import Fasta classes = { 'Extended B': (14850000, 15460000), 'Class I-II': (15460000, 17100000), 'Class III': (17100000, 17950000), 'Framework': (17950000, 19265000), 'Extended A': (19265000, 19400000) } header,seq = Fasta.load('scaffold_42.fa') for name,(start,end) in classes.items(): ...
""" sslstore_api.errors ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013 by Daniel Chatfield """ class SSLStoreApiError(Exception): """The base class for all API errors""" class MalformedCSRError(SSLStoreApiError): pass class WildCardCSRError(SSLStoreApiError): pass
import sys import datetime, dateutil.parser, dateutil.tz tz_str = '''-12 Y -11 X NUT SST -10 W CKT HAST HST TAHT TKT -9 V AKST GAMT GIT HADT HNY -8 U AKDT CIST HAY HNP PST PT -7 T HAP HNR MST PDT -6 S CST EAST GALT HAR HNC MDT -5 R CDT COT EASST ECT EST ET HAC HNE PET -4 Q AST BOT CLT COST EDT FKT GYT HAE HNA PYT -3 P ...
import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." fields = orm['avocado.DataField'].objects.filter(app_name='variants', model_name='evs', fie...
import cmath from numba import types, utils from numba.typing.templates import (AbstractTemplate, ConcreteTemplate, signature, Registry) registry = Registry() infer_global = registry.register_global @infer_global(cmath.acos) @infer_global(cmath.acosh) @infer_global(cmath.asin) @infer...
import sys, rospy from pimouse_ros.msg import LightSensorValues def get_freq(): f = rospy.get_param('lightsensors_freq',10) try: if f <= 0.0: raise Exception() except: rospy.logerr("value error: lightsensors_freq") sys.exit(1) return f if __name__ == '__main__': d...
"""Test mocking utilities. """ import datetime __all__ = ('MockDateTime',) class MockDateTime(datetime.datetime): """Fake datetime class that supports moving through time. Example: MockDateTime.install() try: datetime.datetime.utcnow() datetime.datetime.modify(days=2, sec...
import nose import angr import os import logging l = logging.getLogger('angr.tests.test_multi_open_file') test_location = str(os.path.dirname(os.path.realpath(__file__))) def test_multi_open_file(): test_bin = os.path.join(test_location, "../../binaries/tests/x86_64/test_multi_open_file") b = angr.Project(test_...
create_user = None
from pprint import pprint import re import socket from struct import unpack import sys def decrypt_cnc_msg(ct): """ Decrypt strings ct: bytearray of the ciphertext returns bytearray of the plaintext """ # seed k = 0xff for i in reversed(range(len(ct))): # XOR with previous ...
""" mov eax, off_xxxx . . . . GetProcAddress mov off_yyyy, eax . . . . (repeat) off_xxxx dd aApiName Gets the ApiName, propagates the name to off_xxxx, gives the API name itself to off_yyyy, then redirects all refs to yyyy to the API name directly """ Message("start\n") def skiplines(ea, x): return ea def GetNullSt...
def parseline(ln, adds): ln = ln.lower() #definiuj słowa words = { 'def': "jest prostrzy sposób na zapisanie", 'enddef': "i taka definicja na razie wam wystarczy", 'loop': "przestań dopierko, gdy", 'endloop': "i to tyle", 'if': "zieliński, do tablicy", 'endif'...
""" Presets for the ffmpeg manager """ MP4_VIDEO = {'format':'mp4', 'vcodec':'mpeg4', 'qmin':'3', 'qmax':'5', 'g':'300', 'bitrate':'700k', 'vf':'"scale=-1:360"', } MP4_AUDIO = {'acodec':'libfaac', ...
import unittest from io import StringIO from ..helperfunctions import _xml_to_list from ...worksheet import Worksheet class TestAssembleWorksheet(unittest.TestCase): """ Test assembling a complete Worksheet file. """ def test_assemble_xml_file(self): """Test writing a worksheet with conditional ...
import numpy as np class Point2D : def __init__(self, eq): self.eq = np.array([eq[0],eq[1]]) def __getitem__(self,index): return self.eq[index] def distance(self, p): return np.linalg.norm(p.eq-self.eq) def x(self): return self.eq[0] def y(self): return self.e...
""" ACCESS MISSOURI STATS LIBRARY - EFFECTIVENESS UNIT TESTS """ import unittest from amstats import effectiveness class EffectivenessTests(unittest.TestCase): def setUp(self): self.leg_zero = { "bills_introduced": 0, "actions_committee": 0, "beyond_committee": 0, ...
"""empty message Revision ID: 150a3a473ea0 Revises: 7e379b441686 Create Date: 2017-07-12 19:57:50.342040 """ from alembic import op import sqlalchemy as sa revision = '150a3a473ea0' down_revision = '7e379b441686' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please...
from datetime import datetime from . import tools from . import bg_simulator from .bolus import bolus, generate_boluses from .wizard import wizard from .pump_settings import make_pump_settings from .cbg import cbg, apply_loess from .smbg import smbg from .basal import scheduled_basal def dfaker(num_days, zonename, date...
""" WSGI config for djangostructlog 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.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SE...
""" Convenient shortcuts to manage or check object permissions. """ from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import Q from django.shortcuts import _get_queryset from itertools import groupby from guardian.core import ObjectPermissionChecker from guard...
from kstore.models import BasicConfiguration def basic_configuration_context_processor(request): try: config = BasicConfiguration.objects.all().first() except Exception as e: config = { 'company_name': 'No company Name', 'theme': 'one' } return {'superconfig':...
""" pygments.lexers.dotnet ~~~~~~~~~~~~~~~~~~~~~~ Lexers for .net languages. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, DelegatingLexer, bygroups, include, \ using, this from pyg...
"""Models and related helpers for the membership database.""" import sqlalchemy import lass.model_base import lass.common.mixins import lass.people.mixins import lass.metadata.mixins class Person(lass.model_base.Base): """A person in the membership database.""" __tablename__ = 'member' id = sqlalchemy.Colum...
import sys import numpy from PyQt5.QtWidgets import QApplication from orangewidget import gui from orangewidget.settings import Setting from oasys.widgets import gui as oasysgui, congruence from oasys.widgets.exchange import DataExchangeObject from orangecontrib.xoppy.widgets.gui.ow_xoppy_widget import XoppyWidget clas...
class AioNapBaseException(Exception): """All AioNap exceptions inherit from this exception.""" class AioNapHttpBaseException(AioNapBaseException): """All Slumber HTTP Exceptions inherit from this exception.""" def __init__(self, *args, **kwargs): """Init.""" for key, value in kwargs.items():...
import argparse import os import numpy as np import autosklearn import autosklearn.data import autosklearn.data.data_manager import autosklearn.models.evaluator from ParamSklearn.classification import ParamSklearnClassifier parser = argparse.ArgumentParser() parser.add_argument('input') parser.add_argument('output') ar...
from __future__ import absolute_import, print_function import io import re from glob import glob from os.path import basename from os.path import dirname from os.path import join from os.path import splitext from setuptools import find_packages from setuptools import setup def read(*names, **kwargs): return io.open...
from pinry.settings import * import os DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'development.db'), } } SECRET_KEY = 'fake-key'
from __future__ import absolute_import, unicode_literals import pytest from datetime import datetime from case import Mock, patch from kombu.asynchronous.timer import Entry, Timer, to_timestamp from kombu.five import bytes_if_py2 class test_to_timestamp: def test_timestamp(self): assert to_timestamp(3.13) i...
import collections from webkitpy.common.checkout.git_mock import MockGit from webkitpy.common.host_mock import MockHost from webkitpy.common.system.executive_mock import MockExecutive from webkitpy.common.system.log_testing import LoggingTestCase from webkitpy.w3c.test_importer import TestImporter MockChromiumCommit = ...
import os import datetime as dt from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from django.contrib.a...
from statsmodels.compat.python import lrange from io import BytesIO from itertools import product import numpy as np import pandas as pd import pytest from numpy.testing import assert_, assert_raises from statsmodels.api import datasets try: import matplotlib.pyplot as plt # noqa:F401 except ImportError: pass ...
def make_url_from_lightbox(lightbox): params = lightbox.copy() params['cat_id'] = lightbox.get('category_id', 0) params['summary_year'] = lightbox.get('year', 0) params['summary_month'] = lightbox.get('month', 0) params['summary_day'] = lightbox.get('day', 0) params['type'] = lightbox.get('type', 'cat') if light...
""" Player The Player class is a simple extension of the django User model using the 'profile' system of django. A profile is a model that tack new fields to the User model without actually editing the User model (which would mean hacking into django internals which we want to avoid for future compatability reasons). ...
import unittest from cardmagic.card import Card, VALID_SUITS, VALID_RANKS from cardmagic.exceptions import InvalidRankException, InvalidSuitException class CardTests(unittest.TestCase): def setUp(self,): pass def test_valid_card(self,): for suit in VALID_SUITS: for rank in VALID_RANK...
""" Test Bar """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function def test_bar(): """ Test Bar """ assert True
def extractSoraratranslationsTumblrCom(item): ''' Parser for 'soraratranslations.tumblr.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 print_function import hashlib import time import sys def _repr_str(s): return '"%s"' % (s.replace('\\', '\\\\').replace('"', '\\"'), ) def _repr_dict(d): return ' '.join('%s %s' % (k, _repr(d[k])) for k in d.keys()) def _repr_list(l): return '[%s]' % ' '.join(_repr(x) for x in l) def ...
import datetime from django.core.urlresolvers import reverse from django.utils.feedgenerator import Atom1Feed from django.contrib.syndication.views import Feed from django.shortcuts import render from .models import Slot from utils import get_user_name class GCalAtom1Feed(Atom1Feed): def root_attributes(self): ...
import sys import os from functools import partial import ctypes as ct from ctypes.util import find_library this_dir = os.path.dirname(os.path.abspath(__file__)) is_32bit = (sys.maxsize <= 2**32) arch = "x86" if is_32bit else "x64" arch_dir = os.path.join(this_dir, arch) if is_32bit: raise NotImplementedError("...
import mostFrequent import naiveBayes import perceptron import perceptron_pacman import mira import samples import sys import util from pacman import GameState, Directions TEST_SET_SIZE = 100 DIGIT_DATUM_WIDTH=28 DIGIT_DATUM_HEIGHT=28 FACE_DATUM_WIDTH=60 FACE_DATUM_HEIGHT=70 def basicFeatureExtractorDigit(datum): "...
from datetime import timedelta from django import forms from django.db.models import Q from django.forms import widgets from django.forms.models import ( BaseModelFormSet, ModelMultipleChoiceField, modelformset_factory) from django.utils.translation import get_language, ugettext, ugettext_lazy as _ import olympia.c...
import glob import sys import os import argparse import multiprocessing import subprocess import image_compare import codecs import time import webbrowser import shlex import cdat_info root = os.getcwd() cpus = multiprocessing.cpu_count() parser = argparse.ArgumentParser(description="Run VCS tests", ...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("build", "0028_auto_20190613_1421")] operations = [ migrations.AddField( model_name="build", name="org_note", field=models.CharField(blank=True, default="", max_length=255...
command = testshade("-g 3 3 --fparam a 10 test")
"""Display the current config """ import subprocess import qisys.parsers import qibuild.parsers import qibuild.wizard from qisys import ui def configure_parser(parser): """Configure parser for this action """ qisys.parsers.worktree_parser(parser) parser.add_argument("--edit", action="store_true", he...
import os, sys, subprocess passed = [] ignore = ('fails_', 'giws_', 'unreal_', 'verilog', 'nuitka_', 'nim_', 'java_', 'custom_', 'cpython_', 'nodejs_') ignoreosx = ['hello_cpython.md'] TODO_FIX = ( 'async_channels_rust.md', # rustc: error while loading shared libraries: librustc_driver-4e7c5e5c.so: cannot open shared ...
import unittest import os import os.path import sys import re import tempfile import importlib, importlib.machinery, importlib.util import py_compile import warnings import pathlib from test.support import ( forget, make_legacy_pyc, unload, verbose, no_tracing, create_empty_file, temp_dir) from test.support.scr...
import sys import os import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '../lib')) from testlib import get_fixture, function from testlib import EapiConfigUnitTest import pyeapi.api.vrrp upd_intf = 'Vlan50' upd_vrid = 10 upd_cmd = 'interface %s' % upd_intf known_vrrps = { 'Ethernet1': { ...
from pylab import * from scipy import * from scipy import optimize import argparse import sys import os def isRectangular(obj): return (obj == 'torpedo' or obj == 'emperor' or obj == 'wire') def distancePrep(rawData): length = [] distance = [] for line in rawData: data = line.split(',') ...
from bisect import bisect_left from random import random, randint import cPickle as pickle import datetime class UserTraces(object): """ Format: ------ Each trace file contains a user session in the form: TIME IP PORT where each line represents a new stream, TIME is the stream creation timestamp in normalized secon...
def test_list_groups(qisrc_action, git_server, record_messages): git_server.create_group("default", ["foo", "bar"], default=True) git_server.create_group("spam", ["spam", "eggs"]) qisrc_action("init", git_server.manifest_url) record_messages.reset() qisrc_action("list-groups") assert record_mess...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 5, transform = "Difference", sigma = 0.0, exog_count = 100, ar_order = 0);
from selenium import webdriver import unittest import re import sys import os class ProductTest(unittest.TestCase): def setUp(self): # change path of chromedriver according to which directory you have chromedriver. self.driver = webdriver.Chrome('chromedriver') self.driver.implicitly_wait(30...
from django.core.management.base import BaseCommand, CommandError from setlist.models import * import datetime, pprint from datetime import date breaks = [ [date(1990, 1, 1), "Early Tours"], [date(1998, 1, 1), "Gangstabilly Tour"], [date(1999, 5, 7), "Pizza Deliverance Tour"], [date(2001, 8, 2), "Southern Rock ...
SYSTEM_VERSION = '2.4.0-RC1' import datetime import hashlib from google.appengine.ext import db from google.appengine.api import memcache from google.appengine.api import users class Member(db.Model): num = db.IntegerProperty(indexed=True) auth = db.StringProperty(required=False, indexed=True) deactivated =...
"""Unit tests for parser data module.""" import unittest import numpy import cclib class ccDataTest(unittest.TestCase): """Unit tests for the ccData class.""" check_array = ['atomcoords', 'scfenergies'] check_arrlist = ['mocoeffs', 'scfvalues'] check_arrdict = ['atomcharges', 'atomspins'] def setUp(...
from django.contrib.gis.gdal import DataSource from django.db.models.fields.related import ForeignKey from django.db.models import get_models, get_model from django.db import transaction class GdbLoader(): loadOrder = [ "DataSources", "Glossary", "DescriptionOfMapUnits", "MapUnitPoly...
import sys from io import StringIO from pg_bawler import gen_sql def test_simple_main(monkeypatch): stdout = StringIO() monkeypatch.setattr(sys, 'stdout', stdout) class Args: tablename = 'foo' gen_sql.main(*[Args.tablename]) sql = stdout.getvalue() assert gen_sql.TRIGGER_FN_FMT.format(ar...
from django.conf import settings from django.contrib.sitemaps import Sitemap from .models import Sitepath class SitepathSitemap(Sitemap): def items(self): items = {} objects = Sitepath.objects.filter(type='page', sitemap=True) if hasattr(settings, 'SITE_ID'): objects = objects.fi...
import os import unittest from telemetry.page import page_benchmark_results from telemetry.page import page_set from telemetry.page import perf_tests_helper def _MakePageSet(): return page_set.PageSet.FromDict({ "description": "hello", "archive_path": "foo.wpr", "pages": [ {"url": "http://ww...
from __future__ import unicode_literals import shutil import logging import datetime import os # operation system packages import ConfigParser as configparser # a package to parse INI file or confige file. import argparse # a package to parse commandline arguments. import sys from re import sub import gzip from subp...
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. Pre build plugin for koji build system """ from __future__ import absolute_import import os from atomic_reactor.plugin import PreBuildPlugin from a...
from pythonpic import plotting_parser from pythonpic.configs import run_coldplasma, run_laser from pythonpic.visualization import static_plots, time_snapshots from pythonpic.configs.run_laser import initial, impulse_duration, n_macroparticles, number_cells import pathlib args = plotting_parser("Cold plasma oscillations...
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 'Code.qr_code' db.add_column(u'base_plant', 'user', self.gf('django.db.models.fields.related.OneTo...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('products', '0001_initial'), ] operations = [ migrations.AlterField( model_name='product', name='picture', field=model...
from django.http import HttpResponseForbidden from mediasnakefiles.views import ticket_stream class SSLEnforcer(object): """ Allow non-SSL access only to the /ticket/ URLs. """ def process_view(self, request, view_func, view_args, view_kwargs): if view_func is not ticket_stream: if n...