content
stringlengths
4
20k
# -*- coding: utf-8 -*- """ jinja2.tests ~~~~~~~~~~~~ Jinja test functions. Used with the "is" operator. :copyright: (c) 2017 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import re from collections import Mapping from jinja2.runtime import Undefined from jinja2._compat impor...
import collections import mock from oslo_vmware import vim_util from nova import exception from nova import test from nova.tests.unit.virt.vmwareapi import fake from nova.tests.unit.virt.vmwareapi import stubs from nova.virt.vmwareapi import driver from nova.virt.vmwareapi import network_util from nova.virt.vmwareapi...
""" Unit tests for checklist methods in views.py. """ from contentstore.utils import reverse_course_url from contentstore.views.checklist import expand_checklist_action_url from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.django import modulestore import json from contentstore.tes...
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt fig = plt.figure() # global geostationary map centered on lon_0 lon_0=57. # resolution = None means don't process the boundary datasets. m1 = Basemap(projection='geos',lon_0=lon_0,resolution=None) # add an axes with a black back...
''' Character data ''' from rest_framework.reverse import reverse class Character(object): def __init__(self, pk, name, en_face, top_down, width, height): self.id = self.pk = pk self.name = name self.en_face = en_face self.top_down = top_down self.width = width ...
"""Test utilities for writing NDB tests. Useful set of utilities for correctly setting up the appengine testing environment. Functions and test-case base classes that configure stubs and other environment variables. """ import logging import unittest from google.appengine.ext import testbed from . import model fro...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.docker_common import AnsibleDockerClient, DockerBaseClass, HAS_DO...
# -*- coding: utf-8 -*- 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): # Adding field 'Project.use_repo_fabfile' db.add_column(u'projects_projec...
"""The WaveBlocks Project This file contains code for constructing phase space lattices. @author: R. Bourquin @copyright: Copyright (C) 2013 R. Bourquin @license: Modified BSD License """ from numpy import array, sqrt, pi, mgrid, complexfloating, einsum, product, sum __all__ = ["PhaseSpaceLattice"] class PhaseSpa...
from opbeat.instrumentation.packages.base import AbstractInstrumentedModule from opbeat.traces import trace class DjangoTemplateInstrumentation(AbstractInstrumentedModule): name = 'django_template' instrument_list = [ ("django.template", "Template.render"), ] def call(self, module, method, w...
import BaseHTTPServer import cgi from .linkedin import LinkedInApplication, LinkedInAuthentication, PERMISSIONS def quick_api(api_key, secret_key): """ This method helps you get access to linkedin api quickly when using it from the interpreter. Notice that this method creates http server and wait for...
"""Tests for useful utilities for higher level polynomial classes. """ from sympy import S, Integer, sin, cos, sqrt, symbols, pi, Eq, Integral, exp from sympy.utilities.pytest import raises from sympy.polys.polyutils import ( _nsort, _sort_gens, _unify_gens, _analyze_gens, _sort_factors, paral...
#!/usr/bin/env python2 import errno import fcntl import re import os import subprocess import socket import sys import threading import tempfile import codexconfig # verboseness options WRITE_TO_STDOUT=True LOG_REPLAY_RECORDS=False XV6_KERNEL=os.path.dirname(os.path.realpath(__file__)) + '/../o.codex/kernel.elf' QEM...
"""fuse_gtest_files.py v0.2.0 Fuses Google Test source code into a .h file and a .cc file. SYNOPSIS fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR Scans GTEST_ROOT_DIR for Google Test source code, and generates two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc. Then yo...
from tests import BaseTestCase from redash.models import Organization class TestOrganizationSettings(BaseTestCase): def test_post(self): admin = self.factory.create_admin() rv = self.make_request( "post", "/api/settings/organization", data={"auth_password_login_...
import hashlib, hmac, sys from struct import pack from operator import xor from itertools import starmap class RC4: def __init__(self, key, drop): self.s = [] self.i = 0; self.j = 0; self.s = [0] * 256 for i in range(0, len(self.s)): self.s[i] = i for ...
import wx import os import armid from EditorBase import EditorBase from GoalsGrid import GoalsGrid from datetime import datetime NAME_POS = 0 DEFINITION_POS = 1 CATEGORY_POS = 2 PRIORITY_POS = 3 FITCRITERION_POS = 4 ISSUE_POS = 5 ORIGINATOR_POS = 6 class GMPanel(EditorBase): def __init__(self,parent,id): self.o...
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache class SessionStore(DBStore): """ Implements cached, database backed sessions. """ def __init__(self, session_key=None)...
""" Verifies the use of the environment during regeneration when the gyp file changes, specifically via build of an executable with C preprocessor definition specified by CFLAGS. In this test, gyp and build both run in same local environment. """ import TestGyp # CPPFLAGS works in ninja but not make; CFLAGS works in...
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) class Token(object): def __init__(self, start_mark, end_mark): self.start_mark = start_mark self.end_mark = end_mark def __repr__(self): attributes = [ key for key in self.__dict__ if not ...
from django.conf import settings class PayPalSettingsError(Exception): """Raised when settings be bad.""" RECEIVER_EMAIL = settings.PAYPAL_RECEIVER_EMAIL # API Endpoints. POSTBACK_ENDPOINT = "https://www.paypal.com/cgi-bin/webscr" SANDBOX_POSTBACK_ENDPOINT = "https://www.sandbox.paypal.com/cgi-bin/webscr" # ...
from testtools import TestCase from testtools.helpers import ( try_import, try_imports, ) from testtools.matchers import ( Equals, Is, ) class TestTryImport(TestCase): def test_doesnt_exist(self): # try_import('thing', foo) returns foo if 'thing' doesn't exist. marker = ob...
import numpy import matplotlib.pyplot as plt import pycbc.coordinates as co from mpl_toolkits.mplot3d import Axes3D from pycbc import distributions # We can choose any bounds between 0 and pi for this distribution but in units # of pi so we use between 0 and 1. theta_low = 0. theta_high = 1. # Units of pi for the bou...
import keyword, os, sys import cgi, string, cStringIO import token, tokenize, glob import getopt, webbrowser, time __title__ = 'PySourceColor' __version__ = "ver.1" __date__ = '2 August 2004' __author__ = "M.E.Farmer Jr." __credits__ = '''This was originally submitted / written by Jurgen Hermann to ASPN python recipes...
import hotshot import hotshot.log import os import pprint import unittest import _hotshot import gc from test import test_support from hotshot.log import ENTER, EXIT, LINE def shortfilename(fn): # We use a really shortened filename since an exact match is made, # and the source may be either a Python source...
from ordereddict import OrderedDict def tokenize(data): while len(data): if data[0] in ['{', '}', ':', ',', '[', ']']: yield data[0] data = data[1:] elif data[0] in ' \n': data = data[1:] elif data[0] == "'": data = data[1:] string...
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) from powerline.lib.vcs import guess, tree_status from powerline.segments import Segment, with_docstring from powerline.theme import requires_segment_info, requires_filesystem_watcher @requires_filesyste...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import logging import time from django.db import migrations from ureport.utils import chunk_list logger = logging.getLogger(__name__) class Migration(migrations.Migration): def populate_age_and_gender_on...
import re import urllib.parse import requests from lxml import etree from cloudbot import hook from cloudbot.util import web, formatting # security parser = etree.XMLParser(resolve_entities=False, no_network=True) api_url = 'http://api.wolframalpha.com/v2/query' query_url = 'http://www.wolframalpha.com/input/?i={}'...
def main(): startApplication("fatcrm") # load methods import campaignsHandling import mainWindowHandling # create a campaign # data to be registered name = "TestCampaign" status = "In Queue" detailsList = [name, status, "1/1", "2/2", "Radio", "US Dollars : $", "100000", "200000"...
import cgi import subprocess import sys def GetOutput(*args): try: return subprocess.check_output([sys.argv[1]] + list(args)) except subprocess.CalledProcessError: return '' def ParseTopLevel(out): commands = [] output = [] for line in out.splitlines(): if line.startswith(' '): command,...
"""Receives documents from the oplog worker threads and indexes them into the backend. This file is a document manager for MongoDB, but the intent is that this file can be used as an example to add on different backends. To extend this to other systems, simply implement the exact same class and rep...
from bjec.htcondor import _args_to_str, _environment_to_str, _file_remaps_to_str def test_args_to_str() -> None: """ These test cases are based on testing conducted with HTCondor v8.9.4. """ assert _args_to_str([]) == '""' assert _args_to_str(['a']) == '"a"' assert _args_to_str(['a and b']) == '"\'a and b\'"' ...
# -*- coding: utf-8 -*- 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): # Adding field 'UserProfile.date_modified' db.add_column(u'main_userprofi...
from html5lib.constants import scopingElements, tableInsertModeElements, namespaces try: frozenset except NameError: # Import from the sets module for python 2.3 from sets import Set as set from sets import ImmutableSet as frozenset # The scope markers are inserted when entering object elements, # marq...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } from traceback import format_exc from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.digit...
from __future__ import absolute_import, print_function from packaging.requirements import Requirement import os import re import subprocess import sys from pebble_tool.exceptions import ToolError from pebble_tool.version import __version__ __author__ = 'katharine' __all__ = ['Requirements'] class Requirements(obje...
import time import unittest import config import node LEADER = 1 ROUTER1 = 2 ED = 3 ROUTER2 = 4 ROUTER3 = 5 class Cert_6_1_7_EDSynchronization(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} for i in range(1,6): self.nod...
"""The volumes api.""" from webob import exc import webob from nova.api.openstack import common from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import exception from nova import flags from nova import log as logging from nova import volume from nova.volume import volume_types LO...
#! /usr/bin/env python from __future__ import division from __future__ import print_function from builtins import range from past.utils import old_div import numpy import math def get_zdata_segment(zdata, t_Arai, tmin, tmax): # lower_bound = t_Arai.index(tmin) upper_bound = t_Arai.index(tmax) zdata_segm...
""" Test cases for L{twisted.names.srvconnect}. """ from twisted.internet import defer, protocol from twisted.names import client, dns, srvconnect from twisted.names.common import ResolverBase from twisted.names.error import DNSNameError from twisted.internet.error import DNSLookupError from twisted.trial import unitt...
#!/usr/bin/python from twisted.internet import reactor from twisted.web import http from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient from ImageFile import Parser from StringIO import StringIO class InterceptingProxyClient(ProxyClient): def __init__(self, *args, **kwargs): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # setup.py - distutils configuration for pygtk '''Python Bindings for the GTK+ Widget Set. PyGTK is a set of bindings for the GTK+ widget set. It provides an object oriented interface that is slightly higher level than the C one. It automatically does all the type cast...
# vim: set fileencoding=utf-8 : """ Link Model module """ from sqlalchemy import ( Column, String, Integer, ForeignKey, ) from sqlalchemy.orm import relationship from . import ( Dateable, BASE, ) class Link(Dateable, BASE): # pylint: disable=R0903 # Too fee pyblic methods: we are ...
"""Tools and API for translation and localization engineering. The `Translate Toolkit <http://toolkit.translatehouse.org/>`_ is created by localizers for localizers. It contains several utilities, as well as an API for building localization tools. Some of the **tools** include: - File format `converters <http://do...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.0'} DOCUMENTATION = r''' --- author: - Alain Dejoux (@adejoux) module: aix_lvol short_descri...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import copy from ansible import constants as C from ansible.plugins.action.normal import ActionModule as _ActionModule from ansible.module_utils.dellos9 import dellos9_provider_spec from ansible.module_utils.network_com...
"""Test RPC commands for signing and verifying messages.""" from test_framework.test_framework import PivxTestFramework from test_framework.util import assert_equal class SignMessagesTest(PivxTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_t...
#!/usr/bin/env python """ Draws an simple RGB image - Left-drag pans the plot. - Mousewheel up and down zooms the plot in and out. - Pressing "z" brings up the Zoom Box, and you can click-drag a rectangular region to zoom. If you use a sequence of zoom boxes, pressing alt-left-arrow and alt-right-arrow moves ...
from __future__ import division import json import weakref from twisted.internet import defer from twisted.protocols import basic from twisted.python import failure, log from twisted.web import client, error from p2pool.util import deferral, deferred_resource, memoize class Error(Exception): def __init__(self, ...
import re from capstone import * class ROPMakerX86: def __init__(self, binary, gadgets, liboffset=0x0): self.__binary = binary self.__gadgets = gadgets # If it's a library, we have the option to add an offset to the addresses self.__liboffset = liboffset self.__genera...
"""`ReaderSource` produces `Tensor`s of keys and values using a `tf.Reader`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.dataframe import transform from tensorflow.python.ops import io_ops from tensorflow.py...
from __future__ import absolute_import from __future__ import print_function class AbandonChain(Exception): """A series of chained steps can raise this exception to indicate that one of the intermediate RunProcesses has failed, such that there is no point in running the remainder. 'rc' should be the non-...
""" 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 ...
import re import logging from lxml import etree, html from odoo import api, models _logger = logging.getLogger(__name__) class IrFieldsConverter(models.AbstractModel): _inherit = "ir.fields.converter" @api.model def imgs_from_html(self, html_content, limit=None, fail=False): """Extract all image...
# Задача 12. Вариант 21. #Разработайте игру "Крестики-нолики". (см. М.Доусон Программируем на Python гл. 6). # Platonova O. A. # 30.05.2016 def display_instruct(): print(""" Приветствуем Вас в игре "Крестики-нолики". Ниже представлено игровое поле. Каждая цифра соответствует номеру поля для игры. ...
from openerp.osv import fields, osv class l10n_ma_report(osv.osv): _name = 'l10n.ma.report' _description = 'Report for l10n_ma_kzc' _columns = { 'code': fields.char('Code', size=64), 'name': fields.char('Name'), 'line_ids': fields.one2many('l10n.ma.line', 'report_id', 'Lines', copy=...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..compat import compat_urllib_parse_urlparse from ..utils import ( determine_ext, float_or_none, ) class SpiegeltvIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?spiegel\.tv/(?:#/)?filme/(?P<id>[\-a-z0-9]+...
import os # Create the various paths of interest SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) SDK_SRC_DIR = os.path.dirname(SCRIPT_DIR) SDK_EXAMPLE_DIR = os.path.join(SDK_SRC_DIR, 'examples') SDK_LIBRARY_DIR = os.path.join(SDK_SRC_DIR, 'libraries') SDK_RESOURCE_DIR = os.path.join(SDK_SRC_DIR, 'resources') S...
from ..Qt import QtGui, QtCore from ..SignalProxy import SignalProxy import sys from ..pgcollections import OrderedDict from ..python2_3 import asUnicode class ComboBox(QtGui.QComboBox): """Extends QComboBox to add extra functionality. * Handles dict mappings -- user selects a text key, and the ComboBox indic...
try: from pyVmomi import vim, vmodl HAS_PYVMOMI = True except ImportError: HAS_PYVMOMI = False def configure_dns(host_system, hostname, domainname, dns_servers): changed = False host_config_manager = host_system.configManager host_network_system = host_config_manager.networkSystem config ...
import datetime from django.contrib.sessions.models import Session from django.contrib.sessions.backends.base import SessionBase, CreateError from django.core.exceptions import SuspiciousOperation from django.db import IntegrityError, transaction from django.utils.encoding import force_unicode class SessionStor...
"""Tests for Discriminative Layer Training Optimizer for TensorFlow.""" import pytest import numpy as np import tensorflow as tf from tensorflow_addons.optimizers.discriminative_layer_training import MultiOptimizer from tensorflow_addons.utils import test_utils def assert_list_allclose(a, b): for x, y in zip(a,...
# -*- coding: utf-8 -*- import re from module.plugins.internal.Crypter import Crypter class UlozToFolder(Crypter): __name__ = "UlozToFolder" __type__ = "crypter" __version__ = "0.22" __status__ = "testing" __pattern__ = r'http://(?:www\.)?(uloz\.to|ulozto\.(cz|sk|net)|bagruj\.cz|zachowajt...
from __future__ import with_statement import errno import filecmp import os.path import re import tempfile import sys # A minimal memoizing decorator. It'll blow up if the args aren't immutable, # among other "problems". class memoize(object): def __init__(self, func): self.func = func self.cache = {} de...
#!/usr/bin/env python """Schema validation of ansible-base's ansible_builtin_runtime.yml and collection's meta/runtime.yml""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import datetime import os import re import sys from distutils.version import StrictVersion from functools...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleM...
""" sentry.client.handlers ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import logging import sys import traceback class SentryHandler(logging.Handler): def emit(self, record): from sentry.client.models impo...
import datetime import decimal from django.db import connection, models from django.db.models.functions import Cast from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from ..models import Author, DTModel, Fan, FloatModel class CastTests(TestCase): @classmethod def setUpTestData(self): ...
"""Tokenization classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import unicodedata import six import io def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if s...
"""Module for testing cursor objects.""" import cx_Oracle import sys class TestCursor(BaseTestCase): def testExecuteNoArgs(self): """test executing a statement without any arguments""" result = self.cursor.execute("begin null; end;") self.failUnlessEqual(result, None) def testExecute...
# -*- coding: utf-8 -*- """ *************************************************************************** readwritecontextentercategory.py --------------------- Date : May 2018 Copyright : (C) 2018 by Denis Rouzaud Email : <EMAIL> ****************************...
import urllib import datetime import logging import re import unicodedata from django.conf import settings from django.db import models from django.utils.translation import ugettext as _ import jsonfield.fields class Gateway(models.Model): """ A Gateway is a sending endpoint, and associated authentication in...
import json from allauth.socialaccount.providers.oauth.client import OAuth from allauth.socialaccount.providers.oauth.views import ( OAuthAdapter, OAuthCallbackView, OAuthLoginView, ) from .provider import VimeoProvider class VimeoAPI(OAuth): url = 'http://vimeo.com/api/rest/v2?method=vimeo.people.g...
import asyncio import meteorish import datetime from . import utils as test_utils from nose.tools import (assert_raises, assert_true, assert_not_in, assert_is_none, assert_false, with_setup) from .utils import assert_socket_sent_json from unittest import mock def setup_socket_message(): gl...
from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase from django.contrib.auth.models import User from bucketlist.models import BucketList, BucketListItem from faker import Factory fake = Factory.create() class UserTests(APITestCase): """ Tests ...
from couchpotato.core.event import fireEvent from couchpotato.core.helpers.encoding import tryUrlencode from couchpotato.core.logger import CPLog from couchpotato.core.media._base.providers.torrent.torrentshack import Base from couchpotato.core.media.movie.providers.base import MovieProvider log = CPLog(__name__) aut...
import time import redis from wsgiref.simple_server import make_server from pyramid.config import Configurator from restless.pyr import PyramidResource class UserResource(PyramidResource): def __init__(self, *args, **kwargs): super(UserResource, self).__init__(*args, **kwargs) self.conn = redis.St...
from tempest import cli from tempest import config from tempest.openstack.common import log as logging from tempest import test CONF = config.CONF LOG = logging.getLogger(__name__) class SimpleReadOnlyCeilometerClientTest(cli.ClientTestBase): """Basic, read-only tests for Ceilometer CLI client. Checks retu...
import unittest import gevent from conpot.core.loggers.mysql_log import MySQLlogger class Test_MySQLlogger(unittest.TestCase): def test_mysqllogger(self): """ Objective: Test if events can be stored to and retrieved from mysql properly. """ # instanciate our mysql logging infrast...
#!/usr/bin/env python """Pi digits example Example shows arbitrary precision using mpmath with the computation of the digits of pi. """ from mpmath import libmp, pi from mpmath import functions as mpf_funs import math from time import clock import sys def display_fraction(digits, skip=0, colwidth=10, columns=5): ...
# -*- coding: utf-8 -*- """Tests that the tslibs API is locked down""" from pandas._libs import tslibs def test_namespace(): submodules = ['ccalendar', 'conversion', 'fields', 'frequencies', 'nattype', 'np_datetime', ...
import os from helpers import unittest import luigi import luigi.notifications from luigi import postgres """ Typical use cases that should be tested: * Daily overwrite of all data in table * Daily inserts of new segment in table * (Daily insertion/creation of new table) * Daily insertion of multiple (different) ne...
""" Utility Widgets not specific to alot """ import urwid class AttrFlipWidget(urwid.AttrMap): """ An AttrMap that can remember attributes to set """ def __init__(self, w, maps, init_map='normal'): self.maps = maps urwid.AttrMap.__init__(self, w, maps[init_map]) def set_map(self, ...
""" shared options and groups The principle here is to define options once, but *not* instantiate them globally. One reason being that options with action='append' can carry state between parses. pip parse's general options twice internally, and shouldn't pass on state. To be consistent, all options will follow this d...
import numpy as np from ase.lattice.spacegroup import crystal from ase.io import write # A diamond unit cell diamond = crystal('C', [(0, 0, 0)], spacegroup=227, cellpar=[3.57, 3.57, 3.57, 90, 90, 90]) # Check that we can write to trajectory: write('c.traj', diamond) assert len(diamond) == 8 corre...
#!/usr/bin/env python """ Commandline tool for doing operations on Problems """ from __future__ import unicode_literals import argparse import logging import sys from path import path from cStringIO import StringIO from calc import UndefinedVariable from capa.capa_problem import LoncapaProblem from mako.lookup impor...
""" Depth Spider Middleware See documentation in docs/topics/spider-middleware.rst """ from scrapy import log from scrapy.http import Request class DepthMiddleware(object): def __init__(self, maxdepth, stats=None, verbose_stats=False, prio=1): self.maxdepth = maxdepth self.stats = stats ...
import wx import msikeys class KeyboardFrame(wx.Frame): def __init__(self, keyboard): super(KeyboardFrame, self).__init__(None, title='MSI Keys', size=(400, 150)) self.keyboard = keyboard self.selected_regions = [] sizer = wx.BoxSizer(wx.VERTICAL) region_buttons = [] ...
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from tests import IntegrationTestCase from tests.holodeck import Request from twilio.base.exceptions import TwilioException from twilio.http.response import Response class ParticipantTestCase(Integ...
from __future__ import unicode_literals import logging import sys import types from django import http from django.conf import settings from django.core import exceptions from django.core import urlresolvers from django.core import signals from django.utils.encoding import force_text from django.utils.importlib impor...
import base64 import zlib from pyramid.response import Response from pyramid.decorator import reify from .pony import PONY, UNICORN, TEMPLATE class Pony(object): def __init__(self, request): self.request = request data = PONY link = "add horn!" @reify def animal(self): data = s...
from __future__ import print_function from LogAnalyzer import Test,TestResult import DataflashLog from math import sqrt class TestIMUMatch(Test): '''test for empty or near-empty logs''' def __init__(self): Test.__init__(self) self.name = "IMU Mismatch" def run(self, logdata, verbose): ...
""" Given a list of integers, made up of (hopefully) a small number of long runs of consecutive integers, compute a representation of the form ((start1, end1), (start2, end2) ...). Then answer the question "was x present in the original list?" in time O(log(# runs)). """ import bisect def intranges_from_list(list_): ...
from __future__ import absolute_import, division, unicode_literals from xml.dom import minidom, Node import weakref from . import _base from .. import constants from ..constants import namespaces from ..utils import moduleFactoryFactory def getDomBuilder(DomImplementation): Dom = DomImplementation class A...
try: import jenkins python_jenkins_installed = True except ImportError: python_jenkins_installed = False try: from lxml import etree as ET python_lxml_installed = True except ImportError: python_lxml_installed = False class JenkinsJob: def __init__(self, module): self.module = modu...
""" Marathon puzzle in Google CP Solver. From Xpress example http://www.dashoptimization.com/home/cgi-bin/example.pl?id=mosel_puzzle_5_3 ''' Dominique, Ignace, Naren, Olivier, Philippe, and Pascal have arrived as the first six at the Paris marathon. Reconstruct their arrival order from the following i...
"""Provides factories for student models.""" import random from datetime import datetime from uuid import uuid4 import factory from django.contrib.auth.models import AnonymousUser, Group, Permission from django.contrib.contenttypes.models import ContentType from factory import lazy_attribute from factory.django import...
#@+leo-ver=5-thin #@+node:2014spring.20140520155021.4821: * @file walker.py #@@language python #@@tabwidth -4 #@+<<declarations>> #@+node:2014spring.20140520155021.4822: ** <<declarations>> (walker) import cherrypy #@-<<declarations>> #@+others #@+node:2014spring.20140520155021.4823: ** class WALKER # 這是 WALKER 類別的定義 ...
from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin as AuthUserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from .models import User class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = User ...