code
stringlengths
1
199k
import os import unittest from manolo_scraper.spiders.mincu import MincuSpider from utils import fake_response_from_file class TestMincuSpider(unittest.TestCase): def setUp(self): self.spider = MincuSpider() def test_parse_item(self): filename = os.path.join('data/mincu', '18-08-2015.html') ...
from flask import Flask from flask.ext.restful import reqparse, abort, Api, Resource app = Flask(__name__) api = Api(app) TODOS = { 'todo1': {'task': 'build an API'}, 'todo2': {'task': '?????'}, 'todo3': {'task': 'profit!'}, } def abort_if_todo_doesnt_exist(todo_id): if todo_id not in TODOS: abo...
from media_tree.contrib.cms_plugins.media_tree_image.models import MediaTreeImage from media_tree.contrib.cms_plugins.helpers import PluginLink from media_tree.models import FileNode from media_tree.contrib.views.detail.image import ImageNodeDetailView from django.utils.translation import ugettext_lazy as _ from cms.ut...
"""Run all python tests in this directory.""" import sys import unittest MODULES = [ 'directory_storage_test', 'gsd_storage_test', 'hashing_tools_test', 'local_storage_cache_test', ] sys.path.insert(0, './') suite = unittest.TestLoader().loadTestsFromNames(MODULES) result = unittest.TextTestRunner(verbo...
import logging LOG_LEVEL_TOOL = 25 TERMINAL_COLOR_BLUE = '\033[94m' TERMINAL_COLOR_GREEN = '\033[92m' TERMINAL_COLOR_YELLOW = '\033[93m' TERMINAL_COLOR_RED = '\033[91m' TERMINAL_COLOR_END = '\033[0m' class ConsoleFormatter(logging.Formatter): """ Custom formatter to show logging messages differently on Console ...
""" website.api ~~~~~~~~~~~ website api blueprint. """
from cmsplugin_cascade.segmentation.mixins import EmulateUserModelMixin, EmulateUserAdminMixin from shop.admin.customer import CustomerProxy class EmulateCustomerModelMixin(EmulateUserModelMixin): UserModel = CustomerProxy class EmulateCustomerAdminMixin(EmulateUserAdminMixin): UserModel = CustomerProxy
from org.sikuli.script import VDictProxy import java.io.File class VDict(VDictProxy): ## # the default similarity for fuzzy matching. The range of this is from # 0 to 1.0, where 0 matches everything and 1.0 does exactly matching. # <br/> # The default similarity is 0.7. _DEFAULT_SIMILARITY = 0.7 _D...
from __future__ import unicode_literals """ Customize Form is a Single DocType used to mask the Property Setter Thus providing a better UI from user perspective """ import webnotes from webnotes.utils import cstr class DocType: def __init__(self, doc, doclist=[]): self.doc, self.doclist = doc, doclist self.docty...
from __future__ import absolute_import, unicode_literals import email import logging from email.utils import formataddr from collections import defaultdict from django.conf import settings from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.core.urlresolvers import rever...
""" Copyright 2011 Jeff Garzik AuthServiceProxy has the following improvements over python-jsonrpc's ServiceProxy class: - HTTP connections persist for the life of the AuthServiceProxy object (if server supports HTTP/1.1) - sends protocol 'version', per JSON-RPC 1.1 - sends proper, incrementing 'id' -...
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_UncagingControlWidget(object): def setupUi(self, UncagingControlWidget): UncagingControlWidget.setObjectName("UncagingControlWidget") UncagingControlWidget.resize(442, 354) self.gridLayout_4 = QtWidgets.QGridLayout(UncagingControlWidget) ...
import numpy as np from keras.datasets import mnist from keras.layers import Activation from keras.layers import Dense from keras.models import Sequential from keras.utils import np_utils np.random.seed(1337) nb_classes = 10 batch_size = 128 nb_epoch = 5 weighted_class = 9 standard_weight = 1 high_weight = 5 max_train_...
import zlib from test_support import TestFailed import sys import imp try: t = imp.find_module('test_zlib') file = t[0] except ImportError: file = open(__file__) buf = file.read() * 8 file.close() print hex(zlib.crc32('penguin')), hex(zlib.crc32('penguin', 1)) print hex(zlib.adler32('penguin')), hex(zlib.ad...
from django import template from django.shortcuts import render_to_response, redirect, get_object_or_404 register = template.Library()
''' Created on Nov 30, 2014 @author: letian ''' import networkx as nx from Segmentation import Segmentation import numpy as np class TextRank4Keyword(object): def __init__(self, stop_words_file = None, delimiters = '?!;?!。;…\n'): ''' `stop_words_file`:默认值为None,此时内部停止词表为空;可以设置为文件路径(字符串),将从停止词文件中提取停止词...
import numpy from chainer.backends import cuda from chainer import function_node from chainer.utils import type_check def _pair(x): if hasattr(x, '__getitem__'): return x return x, x class Shift(function_node.FunctionNode): def __init__(self, ksize=3, dilate=1): super(Shift, self).__init__()...
import itertools import json import os import unittest import numpy as np from monty.json import MontyDecoder from pymatgen.core.periodic_table import Element from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.analysis.defects.core import Interstitial, Substitution, Va...
"""Test NULLDUMMY softfork. Connect to a single node. Generate 2 blocks (save the coinbases for later). Generate 427 more blocks. [Policy/Consensus] Check that NULLDUMMY compliant transactions are accepted in the 430th block. [Policy] Check that non-NULLDUMMY transactions are rejected before activation. [Consensus] Che...
import os from django.core.exceptions import PermissionDenied from apps.gallery.models import Gallery from apps.gallery.models import Picture from apps.team.utils import assert_member from apps.team import control as team_control def can_edit(account, gallery): return not ((gallery.team and not team_control.is_memb...
"""Test the -uacomment option.""" from test_framework.test_framework import PivxTestFramework from test_framework.util import assert_equal class UacommentTest(PivxTestFramework): def set_test_params(self): self.num_nodes = 1 self.setup_clean_chain = True def run_test(self): self.log.info...
import sys import gdb import os import os.path pythondir = '/mingw32tdm/share/gcc-4.5.2/python' libdir = '/mingw32tdm/lib/gcc/mingw32/4.5.2' if gdb.current_objfile () is not None: # Update module path. We want to find the relative path from libdir # to pythondir, and then we want to apply that relative path to...
from inc_cfg import * test_param = TestParam( "Callee=optional SRTP, caller=optional SRTP", [ InstanceParam("callee", "--null-audio --use-srtp=1 --srtp-secure=0 --max-calls=1"), InstanceParam("caller", "--null-audio --use-srtp=1 --srtp-secure=0 --max-calls=1") ] )
import os from twisted.cred import credentials from twisted.internet import defer from twisted.internet import reactor from twisted.internet.endpoints import clientFromString from twisted.python import log from twisted.python import util from twisted.spread import pb from twisted.trial import unittest import buildbot f...
"""Tests for the unparse.py script in the Tools/parser directory.""" import unittest import test.support import io import os import random import tokenize import ast from test.test_tools import basepath, toolsdir, skip_if_missing skip_if_missing() parser_path = os.path.join(toolsdir, "parser") with test.support.DirsOnS...
from marvin.cloudstackTestCase import cloudstackTestCase, unittest from marvin.cloudstackAPI import deleteAffinityGroup from marvin.lib.utils import (cleanup_resources, random_gen) from marvin.lib.base import (Account, Project, ServiceOffering, ...
"""Support functions for loading the reference count data file.""" __version__ = '$Revision: 1.2 $' import os import string import sys try: p = os.path.dirname(__file__) except NameError: p = sys.path[0] p = os.path.normpath(os.path.join(os.getcwd(), p, os.pardir, "api", "refco...
from runtest import TestBase class TestCase(TestBase): def __init__(self): TestBase.__init__(self, 'float-libcall', result=""" [18276] | main() { 0.371 ms [18276] | expf(1.000000) = 2.718282; 0.118 ms [18276] | log(2.718282) = 1.000000; 3.281 ms [18276] | } /* main */ """) def b...
"""QGIS Unit tests for core additions .. 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__ = 'Denis Rouzaud'...
__doc__="""Esx Plugin to gather information about virtual machines running under a VMWare ESX server v3.0 """ import Globals from Products.DataCollector.plugins.CollectorPlugin \ import SnmpPlugin, GetTableMap from Products.DataCollector.plugins.DataMaps \ import ObjectMap class Esx(SnmpPlugin): # compnam...
import bpy for obj in bpy.context.selected_objects: if obj.type == 'MESH': bpy.data.scenes[0].objects.active = obj # make obj active to do operations on it bpy.ops.object.mode_set(mode='OBJECT', toggle=False) # set 3D View to Object Mode (probably redundant) bpy.ops.object.mode_set(mode='...
__all__ = ['MetawebError', 'MetawebSession', 'HTTPMetawebSession', 'attrdict'] __version__ = '0.1' import os, sys, re import urllib2 import cookielib import simplejson from urllib import quote as urlquote import pprint import socket import logging try: import httplib2 from httplib2cookie import CookiefulHttp ex...
import argparse import os import sys import math import pyRootPwa import pyRootPwa.core def writeParticleToFile (outFile, particleName, particleMomentum): if pyRootPwa.core.particleDataTable.isInTable(particleName): partProperties = pyRootPwa.core.particleDataTable.entry(particleName) charge = partProperties.charg...
''' Created on 24 дек. 20%0 @author: ivan ''' import random all_agents = """ Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3 Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729) Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1....
import os import numpy as np from vrml.vrml97 import basenodes, nodetypes, parser, parseprocessor class VRML_Loader(object): """ Parser for VRML files. The VRML language is described in its specification at http://www.web3d.org/documents/specifications/14772/V2.0/index.html """ def __init__(self, en...
import sys import numpy as np from scipy import stats import subprocess as sp import datetime import socket import os exec_name = sys.argv[1] max_t = int(sys.argv[2]) ntries = 5 tot_timings = [] for t_idx in range(1,max_t + 1): cur_timings = [] for _ in range(ntries): # Run the process. p = sp.Popen([exec_name,st...
"""Per-course integration tests for Course Builder.""" __author__ = [ 'Todd Larsen (tlarsen@google.com)' ] from modules.courses import courses_pageobjects from tests.integration import integration class AvailabilityTests(integration.TestBase): def setUp(self): super(AvailabilityTests, self).setUp() ...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('libreosteoweb', '0018_auto_20150420_1232'), ] operations = [ migrations.AlterField( model_name='regulardoctor', name='phone', ...
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): def...
from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from tinycss.css21 import CSS21Parser from tinycss.parsing import remove_whitespace, split_on_comma, ParseError class MediaQue...
from south.db import db from django.db import models from transifex.releases.models import * class Migration: def forwards(self, orm): "Write your forwards migration here" def backwards(self, orm): "Write your backwards migration here" models = { } complete_apps = ['releases']
from frappe.model.document import Document class QualityReviewObjective(Document): pass
import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): # Deleting field id db.delete_column('layers_layer', 'id') # set new primary key for layers_layer db.create_primary_key('la...
from nose.tools import eq_, with_setup from threading import Thread from Queue import Queue from time import sleep def setup(): global Person, neo4django, gdb, neo4jrestclient, neo_constants, settings, models from neo4django.tests import Person, neo4django, gdb, neo4jrestclient, \ neo_constants, set...
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' from flask import request, jsonify, make_response import re from octoprint.settings import settings, valid_boolean_trues from octoprint.server import printer, restricted_access, NO_CONTENT...
import time, sys, os, shutil, subprocess, distutils.dir_util sys.path.append("../../configuration") if os.path.isfile("log.log"): os.remove("log.log") log = open("log.log", "w") from scripts import * from buildsite import * from process import * from tools import * from directories import * printLog(log, "") printLog(...
from __future__ import absolute_import, print_function, unicode_literals, division from jormungandr.interfaces.v1.serializer import serialize_with def get_serializer(serpy): return serialize_with(serpy) def get_obj_serializer(obj): return get_serializer(serpy=obj.output_type_serializer)
from django.core.management import call_command from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): call_command( 'dumpdata', "waffle.flag", indent=4, use_natural_foreign_keys=True, us...
from __future__ import absolute_import from __future__ import division __all__ = ['IPythonProgressBar'] try: from IPython.display import display import ipywidgets as ipw except: display = None ipw = None class IPythonProgressBar(object): """ Represents a progress bar as an IPython widget. If the...
import tools from openerp.osv import fields, orm class hr_language(orm.Model): _name = 'hr.language' _columns = { 'name': fields.selection(tools.scan_languages(), 'Language', required=True), 'description': fields.char('Description', size=64, required=True, translate=True), 'employee_id':...
from __future__ import division from __future__ import absolute_import from builtins import range from future.utils import with_metaclass import numpy as np import scipy.stats as st import scipy.linalg as la from scipy.interpolate import interp1d from scipy.integrate import cumtrapz from scipy.spatial import ConvexHull...
from spack import * class PerlWwwRobotrules(PerlPackage): """Database of robots.txt-derived permissions""" homepage = "http://deps.cpantesters.org/?module=WWW%3A%3ARobotRules;perl=latest" url = "http://search.cpan.org/CPAN/authors/id/G/GA/GAAS/WWW-RobotRules-6.02.tar.gz" version('6.02', sha256='46b...
"""a readline console module (unix only). maxime.tournier@brain.riken.jp the module starts a subprocess for the readline console and communicates through pipes (prompt/cmd). the console is polled through a timer, which depends on PySide. """ from select import select import os import sys import signal if __name__ == '_...
from spack import * import shutil class Libiconv(AutotoolsPackage): """GNU libiconv provides an implementation of the iconv() function and the iconv program for character set conversion.""" homepage = "https://www.gnu.org/software/libiconv/" url = "http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.15....
import os print "PID:",str(os.getpid()) while True: raw_input("press <RETURN> to open file") fh = open("/tmp/test.txt",'w') print "Opened /tmp/test.txt..." raw_input("press <RETURN> to close") fh.close()
import sys sys.path.insert(1, "../../../") import h2o import pandas as pd import statsmodels.api as sm def prostate(ip,port): # Log.info("Importing prostate.csv data...\n") h2o_data = h2o.upload_file(path=h2o.locate("smalldata/logreg/prostate.csv")) #prostate.summary() sm_data = pd.read_csv(h2o.locate("smalldat...
import pytest from pyhdb.cursor import format_operation from pyhdb.exceptions import ProgrammingError import tests.helper TABLE = 'PYHDB_TEST_1' TABLE_FIELDS = 'TEST VARCHAR(255)' @pytest.fixture def test_table_1(request, connection): """Fixture to create table for testing, and dropping it after test run""" tes...
import mock from oslotest import base as test_base from oslo.db.sqlalchemy import test_migrations as migrate class TestWalkVersions(test_base.BaseTestCase, migrate.WalkVersionsMixin): def setUp(self): super(TestWalkVersions, self).setUp() self.migration_api = mock.MagicMock() self.engine = m...
"""Client for interacting with the Stackdriver Logging API""" import traceback import google.cloud.logging.client import six class HTTPContext(object): """HTTPContext defines an object that captures the parameter for the httpRequest part of Error Reporting API :type method: str :param method: The type o...
"""Common functions for Rflink component tests and generic platform tests.""" import asyncio from unittest.mock import Mock from homeassistant.bootstrap import async_setup_component from homeassistant.components.rflink import CONF_RECONNECT_INTERVAL from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF from ...
"""Cloud TPU profiler package.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from setuptools import setup _VERSION = '1.7.0' CONSOLE_SCRIPTS = [ 'capture_tpu_profile=cloud_tpu_profiler.main:run_main', ] setup( name='cloud_tpu_profiler', versi...
"""Command for creating HTTP health checks.""" from googlecloudsdk.api_lib.compute import base_classes from googlecloudsdk.api_lib.compute import health_checks_utils from googlecloudsdk.calliope import base @base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA) class Create(base_classes.BaseAsyncCreator): ...
from tempest.api.volume import base from tempest import exceptions from tempest import test class VolumeQuotasNegativeTestJSON(base.BaseVolumeV1AdminTest): _interface = "json" force_tenant_isolation = True @classmethod @test.safe_setup def setUpClass(cls): super(VolumeQuotasNegativeTestJSON,...
""" Utilities with minimum-depends for use in setup.py """ import datetime import os import re import subprocess import sys from setuptools.command import sdist def parse_mailmap(mailmap='.mailmap'): mapping = {} if os.path.exists(mailmap): fp = open(mailmap, 'r') for l in fp: l = l....
"""Copyright 2020 Google LLC 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 distri...
from __future__ import absolute_import from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_auto_20151218_1741'), ] operations = [ migrations.AddField( model_name='usersettings'...
"""Tests for documentation parser.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import inspect import os import sys from tensorflow.python.platform import googletest from tensorflow.tools.docs import parser def test_function_for_markdow...
import unittest from openmdao.main.api import set_as_top from openmdao.util.testutil import assert_rel_error from pycycle import duct, flowstation class DuctTestCase(unittest.TestCase): def test_start(self): comp = set_as_top(duct.Duct()) comp.dPqP = 0 comp.Q_dot = -237.8 comp.MNexit...
"""Utilities to help with aiohttp.""" import json from typing import Any, Dict, Optional from urllib.parse import parse_qsl from multidict import CIMultiDict, MultiDict class MockRequest: """Mock an aiohttp request.""" def __init__( self, content: bytes, method: str = "GET", stat...
import struct import numpy import io import pickle import pyctrl.packet as packet def testA(): # test A assert packet.pack('A','C') == b'AC' assert packet.pack('A','B') == b'AB' assert packet.pack('A','C') != b'AB' assert packet.unpack_stream(io.BytesIO(b'AC')) == ('A', 'C') assert packet.unpack...
import contextlib from django.core.exceptions import ValidationError as DjangoValidationError ValidationError = DjangoValidationError ValidationValueError = DjangoValidationError ValidationTypeError = DjangoValidationError class TokenError(Exception): pass class TokenHandlerNotFound(TokenError): def __init__(se...
"""Playbook Args""" from argparse import ArgumentParser class Args: """Playbook Args""" def __init__(self, parser: ArgumentParser): """Initialize class properties."""
from src.utils import glove import numpy as np import string class jester_vectorize(): def __init__(self, user_interactions, content, user_vector_type, content_vector_type, **support_files): """Set up the Jester Vectorizer. Args: user_interactions (rdd): The raw data of users interaction...
import errno import functools import os import shutil import tempfile import time import weakref from eventlet import semaphore from nova.openstack.common import cfg from nova.openstack.common import fileutils from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) util_opts = [ cfg.BoolO...
import re from wlauto import AndroidUiAutoBenchmark, Parameter, Alias from wlauto.exceptions import ConfigError class Andebench(AndroidUiAutoBenchmark): name = 'andebench' description = """ AndEBench is an industry standard Android benchmark provided by The Embedded Microprocessor Benchmark Consortium (...
"""Tests for rnn module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import time import timeit import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from tensorflow.python.util imp...
from django_sae.contrib.tasks.cron import OperationView from django_sae.contrib.tasks.operations import TaskOperationMixin class OperationViewMock(OperationView): def get_operation(self, request): return [TaskOperationMixin() for _ in range(0, 3)]
import os import yaml from google.cloud import storage from google.oauth2 import service_account from .storage import Storage class GcsStorage(Storage): def __init__(self, bucket, path, project=None, json_path=None): if bucket is None: raise ValueError('Bucket must be supplied to GCS storage') ...
import os import ssl from oslo.config import cfg from volt.openstack.common.gettextutils import _ ssl_opts = [ cfg.StrOpt('ca_file', default=None, help="CA certificate file to use to verify " "connecting clients."), cfg.StrOpt('cert_file', default...
"""Support to serve the Home Assistant API as WSGI application.""" from __future__ import annotations from ipaddress import ip_network import logging import os import ssl from typing import Any, Final, Optional, TypedDict, cast from aiohttp import web from aiohttp.typedefs import StrOrURL from aiohttp.web_exceptions im...
"""Remove uniqueness in Repo Revision ID: 51d493c4d3e1 Revises: 5ac5404bfcd9 Create Date: 2015-05-11 18:55:46.065354 """ revision = '51d493c4d3e1' down_revision = '5ac5404bfcd9' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_inde...
from traits.api import Int, Tuple from enable.tools.api import ViewportPanTool class MPViewportPanTool(ViewportPanTool): cur_bid = Int(-1) _last_blob_pos = Tuple def normal_blob_down(self, event): if self.cur_bid == -1 and self.is_draggable(event.x, event.y): self.cur_bid = event.bid ...
import unittest import networkx import pythonect.internal.parsers.p2y class TestPythonectScriptParser(unittest.TestCase): def test_program_empty(self): g = networkx.DiGraph() self.assertEqual(len(pythonect.internal.parsers.p2y.PythonectScriptParser().parse('').nodes()) == len(g.nodes()), True) d...
import numpy as np from menpo.image import Image, BooleanImage, MaskedImage from menpo.shape import PointCloud from menpo.testing import is_same_array def test_image_copy(): pixels = np.ones([1, 10, 10]) landmarks = PointCloud(np.ones([3, 2]), copy=False) im = Image(pixels, copy=False) im.landmarks['tes...
from __future__ import print_function from builtins import input import sys import pmagpy.pmag as pmag def main(): """ NAME gofish.py DESCRIPTION calculates fisher parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX ...
""" fs.tests: testcases for the fs module """ from __future__ import with_statement import sys import logging logging.basicConfig(level=logging.ERROR, stream=sys.stdout) from fs.base import * from fs.path import * from fs.errors import * from fs.filelike import StringIO import datetime import unittest import os impo...
"""Integration test for Notifications.""" import github3 from .helper import IntegrationHelper class TestThread(IntegrationHelper): """Integration test for methods on Test class""" def test_subscription(self): """Show that a user can retrieve notifications for repository""" self.token_login() ...
from __future__ import print_function from builtins import zip import pycrfsuite def compareTaggers(model1, model2, string_list, module_name): """ Compare two models. Given a list of strings, prints out tokens & tags whenever the two taggers parse a string differently. This is for spot-checking models :...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('statmaps', '0026_populate_cogatlas'), ] operations = [ migrations.AddField( model_name='statisticmap', name='cognitive_paradigm_c...
import numpy as np import cudarray as ca from .base import PickleMixin _FLT_MIN = np.finfo(ca.float_).tiny class Loss(PickleMixin): # abll: I suspect that this interface is not ideal. It would be more # elegant if Loss only provided loss() and grad(). However, where should # we place the logic from fprop()?...
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Message.updated' db.alter_column(u'mailer_message', 'updated', self.gf('django.db....
from debile.slave.wrappers.pep8 import parse_pep8 from debile.slave.utils import cd from debile.utils.commands import run_command def pep8(dsc, analysis): run_command(["dpkg-source", "-x", dsc, "source-pep8"]) with cd('source-pep8'): out, _, ret = run_command(['pep8', '.']) failed = ret != 0 ...
import logging from devil.android import device_errors class FlagChanger(object): """Changes the flags Chrome runs with. There are two different use cases for this file: * Flags are permanently set by calling Set(). * Flags can be temporarily set for a particular set of unit tests. These tests should call ...
""" This module contains the :class:`Column` class, which defines a "vertical" array of tabular data. Whereas :class:`.Row` instances are independent of their parent :class:`.Table`, columns depend on knowledge of both their position in the parent (column name, data type) as well as the rows that contain their data. ""...
from __future__ import absolute_import from .base import *
from contextlib import contextmanager import sqlalchemy as sa from sqlalchemy.ext import compiler from sqlalchemy.sql.expression import ClauseElement from sqlalchemy.sql.expression import Executable class InsertFromSelect(Executable, ClauseElement): _execution_options = \ Executable._execution_options.union...
""" A HTML5 target. """ from targets import _ from html import TYPE import html NAME = _('HTML5 page') EXTENSION = 'html' HEADER = """\ <!DOCTYPE html> <html> <head> <meta charset="%(ENCODING)s"> <title>%(HEADER1)s</title> <meta name="generator" content="http://txt2tags.org"> <link rel="stylesheet" href="%(STYLE)s"> <s...
import unittest from circular_buffer import ( CircularBuffer, BufferFullException, BufferEmptyException ) class CircularBufferTest(unittest.TestCase): def test_read_empty_buffer(self): buf = CircularBuffer(1) with self.assertRaises(BufferEmptyException): buf.read() def te...
"""Commands for interacting with Google Compute Engine firewalls.""" import socket from google.apputils import appcommands import gflags as flags from gcutil_lib import command_base from gcutil_lib import gcutil_errors from gcutil_lib import utils FLAGS = flags.FLAGS class FirewallCommand(command_base.GoogleComputeComm...
from unittest import TestCase class Test(TestCase): pass