content
stringlengths
4
20k
import unittest from test import test_support import zlib import binascii import random class ChecksumTestCase(unittest.TestCase): # checksum test cases def test_crc32start(self): self.assertEqual(zlib.crc32(""), zlib.crc32("", 0)) self.assert_(zlib.crc32("abc", 0xffffffff)) def test_crc3...
# coding=utf-8 """ This collector uses the [ipmitool](http://openipmi.sourceforge.net/) to read hardware sensors from servers using the Intelligent Platform Management Interface (IPMI). IPMI is very common with server hardware but usually not available in consumer hardware. #### Dependencies * [ipmitool](http://ope...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action import ActionBase class ActionModule(ActionBase): ''' Fail with custom message ''' TRANSFERS_FILES = False def run(self, tmp=None, task_vars=None): if task_vars is None: ...
"""test utilities (part of web.py) """ import unittest import sys, os import web TestCase = unittest.TestCase TestSuite = unittest.TestSuite def load_modules(names): return [__import__(name, None, None, "x") for name in names] def module_suite(module, classnames=None): """Makes a suite from a module.""" ...
import datetime from helpers import unittest, in_parse import luigi import luigi.interface class DateTask(luigi.Task): day = luigi.DateParameter() class DateHourTask(luigi.Task): dh = luigi.DateHourParameter() class DateMinuteTask(luigi.Task): dm = luigi.DateMinuteParameter() class MonthTask(luigi....
import os import math from pyglet import media class PlayerReader(object): def __init__(self, player): self.player = player def line(self, line, lineno): parts = line.split() if parts[0] == 'position': if len(parts) < 4: raise ReaderException('Invalid posit...
# -*- encoding: utf8 -*- import os import linguistica as lxa from linguistica.datasets import brown as corpus_path data_dir = os.path.join(os.path.dirname(__file__), 'data') def test_broken_words_left_to_right(): lxa_object = lxa.read_corpus(corpus_path, max_word_tokens=50000) test_object = lxa_object.brok...
from __future__ import with_statement import atexit import errno import os import signal import sys def daemonize(pidfile=None, progname=None, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null', umask=022): """Fork a daemon process.""" if pidfile: # Check whether the pid file alr...
import functools import weakref from pytestqt.wait_signal import SignalBlocker, MultiSignalBlocker, SignalTimeoutError from pytestqt.qt_compat import QtTest, QApplication def _inject_qtest_methods(cls): """ Injects QTest methods into the given class QtBot, so the user can access them directly without havi...
from UIDs import UID_KEYS from UIDs import UID_KINDS from UIDs import UID_REQUESTS def check_uid_duplication(): all_external_names = [K.externalName for K in UID_KEYS] + \ [R.externalName for R in UID_REQUESTS] + \ [K.externalName for K in UID_KINDS] return len(all_external_names)...
"""Context management API of mxnet.""" from __future__ import absolute_import class Context(object): """Constructs a context. MXNet can run operations on CPU and different GPUs. A context describes the device type and ID on which computation should be carried on. One can use mx.cpu and mx.gpu for sho...
import logging import sys from errbot.backends.base import RoomError, Identifier, Person, RoomOccupant, Stream, ONLINE, Room from errbot.core import ErrBot from errbot.rendering import text from errbot.rendering.ansiext import enable_format, TEXT_CHRS log = logging.getLogger(__name__) TELEGRAM_MESSAGE_SIZE_LIMIT = 1...
#!/usr/bin/env python """ The same (small) array, interpolated with three different interpolation methods. The center of the pixel at A[i,j] is plotted at i+0.5, i+0.5. If you are using interpolation='nearest', the region bounded by (i,j) and (i+1,j+1) will have the same color. If you are using interpolation, the pi...
import signal import weakref from functools import wraps __unittest = True class _InterruptHandler(object): def __init__(self, default_handler): self.called = False self.original_handler = default_handler if isinstance(default_handler, int): if default_handler ==...
from __future__ import unicode_literals from django.contrib.auth.models import User, Permission, Group from django.db import models from django.test import TestCase from django.utils import unittest from rest_framework import generics, status, permissions, authentication, HTTP_HEADER_ENCODING from rest_framework.compat...
from msrest.serialization import Model class QueryTroubleshootingParameters(Model): """Parameters that define the resource to query the troubleshooting result. :param target_resource_id: The target resource ID to query the troubleshooting result. :type target_resource_id: str """ _validatio...
"""SCons.Tool.mslib Tool-specific initialization for lib (MicroSoft library archiver). There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, ...
"""Tests the text output of Google C++ Testing Framework. SYNOPSIS gtest_output_test.py --gtest_build_dir=BUILD/DIR --gengolden # where BUILD/DIR contains the built gtest_output_test_ file. gtest_output_test.py --gengolden gtest_output_test.py """ __author__ = '<EMAIL> (Zhanyong Wan)' i...
from django.contrib.gis.geos import * from django.contrib.gis.geos.error import GEOSIndexError from django.utils import unittest def getItem(o,i): return o[i] def delItem(o,i): del o[i] def setItem(o,i,v): o[i] = v def api_get_distance(x): return x.distance(Point(-200,-200)) def api_get_buffer(x): return x.buffer(10)...
import datetime as dt import pendulum from airflow.settings import TIMEZONE # UTC time zone as a tzinfo instance. utc = pendulum.timezone('UTC') def is_localized(value): """ Determine if a given datetime.datetime is aware. The concept is defined in Python's docs: http://docs.python.org/library/date...
#!/usr/bin/env python """Datastore Input Reader Base Test for the map_job API.""" import unittest from google.appengine.api import datastore_types from google.appengine.api import namespace_manager from google.appengine.datastore import datastore_stub_util from google.appengine.ext import testbed from testlib import t...
{ 'name': 'Base', 'version': '1.3', 'category': 'Hidden', 'description': """The kernel of OpenERP, needed for all installation.""", 'author': 'OpenERP SA', 'maintainer': 'OpenERP SA', 'website': 'http://www.openerp.com', 'depends': [], 'init_xml': [ 'base_data.xml', '...
import sys sys.path.append("../common/tests") from test_utils import * import test_common sys.path.insert(0, '../../../../build/production/config/device-manager/') from vnc_api.vnc_api import * import uuid from ncclient import manager from flexmock import flexmock class DMTestCase(test_common.TestCase): def setUp...
#!/usr/bin/env python """ Project-wide application configuration. DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE. They will be exposed to users. Use environment variables instead. See get_secrets() below for a fast way to access them. """ import os from authomatic.providers import oauth2 from authomatic import ...
from tests.unit import unittest from boto.glacier.layer1 import Layer1 class TestGlacierLayer1(unittest.TestCase): glacier = True def delete_vault(self, vault_name): pass def test_initialiate_multipart_upload(self): # Create a vault, initiate a multipart upload, # then cancel it...
#!/usr/bin/env python """ PySlideshow - A simple image slideshow viewer written in Python using PySide. """ import sys from pathlib import Path from random import randint from PySide import QtCore from PySide.QtGui import QApplication, QMainWindow, QFileDialog, QImage, QPixmap, QIcon, QInputDialog, QMessageBox __ver...
from __future__ import division, print_function, unicode_literals import os dirs = ["../test", "../utest", "../cocos", "../cocos/layer", "../cocos/scenes", "../cocos/actions", "../samples", "../samples/balldrive_toy_game", "../samples/tetrico", "...
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( remove_end, parse_duration, ) class NBAIE(InfoExtractor): _VALID_URL = r'https?://(?:watch\.|www\.)?nba\.com/(?:nba/)?video(?P<id>/[^?]*?)/?(?:/index\.html)?(?:\?.*)?$' _TESTS = [{ 'url': 'http://w...
""" This module contains external, potentially separately licensed, packages that are included in spack. So far: argparse: We include our own version to be Python 2.6 compatible. distro: Provides a more stable linux distribution detection. functools: Used for implementation of total_ordering. ...
from m5.params import * from m5.proxy import * from MemObject import MemObject from Prefetcher import BasePrefetcher from Tags import * class BaseCache(MemObject): type = 'BaseCache' abstract = True cxx_header = "mem/cache/base.hh" size = Param.MemorySize("Capacity") assoc = Param.Unsigned("Associ...
from __future__ import unicode_literals """ frappe.translate ~~~~~~~~~~~~~~~~ Translation tools for frappe """ import frappe, os, re, codecs, json from frappe.utils.jinja import render_include from jinja2 import TemplateError import itertools, operator def guess_language(lang_codes): """Set `frappe.local.lang` ...
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http:...
# -*- coding: utf-8 -*- """ babel.messages.pofile ~~~~~~~~~~~~~~~~~~~~~ Reading and writing of files in the ``gettext`` PO (portable object) format. :copyright: (c) 2013 by the Babel Team. :license: BSD, see LICENSE for more details. """ import os import re from babel.messages.catalog import...
from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.forms import Form from django.forms.fields import BooleanField, IntegerField from django.forms.utils import ErrorList from django.forms.widgets import HiddenInput from django.utils import six from django.utils.encodi...
from common_kube import KubeTest class TestDeleteAction(KubeTest): def test_delete_action(self): factory = self.replay_flight_data() p = self.load_policy( { 'name': 'delete-namespace', 'resource': 'k8s.namespace', 'filters': [ ...
from __future__ import unicode_literals from django import http from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.contrib.sites.requests import RequestSite from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ def sh...
def variations(items, r, strResult = False): ''' Calculates all r length variations of items @arg items - list of items @arg r - length of variations @arg strResult - if True, returns result as multi-line string @returns two-dimensional list of variations or multi-line string ''' if ite...
__all__ = ['SecondaryAuthority', 'SecondaryAuthorityService'] from twisted.internet import task, defer from twisted.names import dns from twisted.names import common from twisted.names import client from twisted.names import resolve from twisted.names.authority import FileAuthority from twisted.python import log, fai...
"""Tests and benchmarks for interacting with the `tf.Session`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import numpy as np from tensorflow.python.client import session from tensorflow.python.framework import dtypes from tensorflow.py...
# -*- coding: utf-8 -*- """ Neural network - nsp """ import numpy as np from nn_forward import nn_forward from nn_norm import weight_norm def nn_cost_quad(Wi, Wo, input, target): """ Calculate the value of the quadratic cost function, i.e. 0.5*(sum of squared error) """ # Calculate networ...
""" .. _ex-opm-resting-state: ====================================================================== Compute source power spectral density (PSD) of VectorView and OPM data ====================================================================== Here we compute the resting state from raw for data recorded using a Neurom...
import glob import os from django.test import TestCase from django.contrib.auth.models import User from onadata.apps.logger.models import XForm, Instance def open_all_files(path): file_paths = glob.glob(os.path.join(path, "*")) result = {} for file_path in file_paths: if file_path.endswith(".jpg...
import time def dijkstra(graph, node_a, node_z): """ Implementation of dijkstra shortest path algorithm. Find the shortest path between vertex 'a' and 'z' from a weighted graph with links. Args: graph: Dictionary-like Graph with all the nodes and its weighted links. node_a: Node ...
from openerp.osv import fields, osv import os from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) class wizard_multi_charts_accounts(osv.osv_memory): """ Change wizard that a new account chart for a company. * Add option to install languages during the setup ...
# Django settings for obi project. from os.path import abspath, dirname DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '<EMAIL>'), ) MANAGERS = ADMINS DATABASES = { 'default': { # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'ENGINE': 'django.db.backends.', ...
from __future__ import absolute_import import re from collections import namedtuple from ..exceptions import LocationParseError from ..packages import six url_attrs = ["scheme", "auth", "host", "port", "path", "query", "fragment"] # We only want to normalize urls with an HTTP(S) scheme. # urllib3 infers URLs withou...
import pytest from tests.providers.google.cloud.utils.gcp_authenticator import GCP_FUNCTION_KEY from tests.test_utils.gcp_system_helpers import CLOUD_DAG_FOLDER, GoogleSystemTest, provide_gcp_context @pytest.mark.backend("mysql", "postgres") @pytest.mark.credential_file(GCP_FUNCTION_KEY) class GcpFunctionExampleDags...
# coding: utf-8 from __future__ import unicode_literals import json import re from .common import InfoExtractor class BuzzFeedIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?buzzfeed\.com/[^?#]*?/(?P<id>[^?#]+)' _TESTS = [{ 'url': 'http://www.buzzfeed.com/abagg/this-angry-ram-destroys-a-punchin...
""" toposort.py Sorts dictionary keys based on lists of dependencies. """ class MissingDependency(Exception): """Exception raised when a listed dependency is not in the dictionary.""" class Sorter(object): def __init__(self, dependencies): self.dependencies = dependencies self.visited = set() ...
#._cv_part guppy.etc.FSA class FiniteAutomaton: def __init__(self, start_state, dump_state=''): self.start_state = start_state self.dump_state = dump_state self.table = {self.dump_state:{}} self.unresolved_composites = [] self.resolved_composites = [] self.composite_memo = {} self.is_updated = 1 def __...
import argparse import os import shutil import subprocess import tempfile import logging from contextlib import contextmanager import charmtools.utils from charmtools.build.tactics import Tactic description = """ Update addon manifests for the charm. This will clone the kubernetes repo and place the addons in <char...
class Solution: # @param {character[][]} board # @return {void} Do not return anything, modify board in-place instead. def solveSudoku(self, board): self.solveSudokuRec(board,0,0) def solveSudokuRec(self, board,row,col): if row == 9: return True if col == 8: ...
#!/usr/bin/python # -*- coding: utf8 -*- import numpy as np import pandas as pd import collections import pandas_ml as pdml from pandas_ml.confusion_matrix.stats import binom_interval, class_agreement, prop_test class ConfusionMatrixAbstract(object): """ Abstract class for confusion matrix You shouldn'...
""" Run unit tests for Cosimulation """ from __future__ import absolute_import import gc import os import random import sys from myhdl import Signal from myhdl._compat import to_bytes from myhdl._Cosimulation import Cosimulation, CosimulationError, _error from utils import raises_kind random.seed(1) # random, but d...
'''Audio and video player with simple GUI controls. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import sys from pyglet.gl import * import pyglet from pyglet.window import key def draw_rect(x, y, width, height): glBegin(GL_LINE_LOOP) glVertex2f(x, y) glVertex2f(x + width, y) glVerte...
#!/usr/bin/env python from __future__ import division import matplotlib as mpl #mpl.use('Agg') import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-paper') import matplotlib.animation as animation mpl.rcParams.update({'text.usetex': True, 'lines.linewidth': 2.5, ...
""" Asset compilation and collection. """ from __future__ import print_function import argparse import glob import traceback from paver import tasks from paver.easy import sh, path, task, cmdopts, needs, consume_args, call_task, no_help from watchdog.observers import Observer from watchdog.events import PatternMatch...
import pygame import sys from math import * SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 400, 300 BLACK = [0, 0, 0] WHITE = [255, 255, 255] screen_center = center_width, center_height = (SCREEN_WIDTH // 2), (SCREEN_HEIGHT // 2) upper_left_corner = upper_left_x, upper_left_y = 0, 0 screen = pygame.display.set_mode(SC...
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import TestCmd import TestSCons test = TestSCons.TestSCons(match = TestCmd.match_re) test.write('SConstruct', "") # Construct the standard copyright marker so it doesn't get replaced # by the packaging build. copyright_marker = '__' + 'COPYRIGHT' + '__' ...
from flatland import ( Dict, Form, Integer, ) from flatland.validation import ( Converted, Present, Validator, ) class Age(Integer): class IsNumber(Converted): incorrect = u'%(label)s is not a valid number.' class ValidAge(Validator): minage = 1 maxage...
import os from setuptools import setup setup( name='django-seed', version=__import__('django_seed').__version__, author='Tobin Brown', author_email='<EMAIL>', packages=['django_seed', 'django_seed.management', 'django_seed.management.commands'], include_package_data=True, url='http://github...
import test_framework.loginit from test_framework.nodemessages import * import time import sys if sys.version_info[0] < 3: raise "Use Python 3" import logging logging.getLogger().setLevel(logging.INFO) logf = open("ctorout.txt","a") logging.getLogger().addHandler(logging.StreamHandler(logf)) from test_framework.te...
from django.contrib.messages import constants from django.contrib.messages.tests.base import BaseTest from django.contrib.messages.storage.base import Message from django.contrib.messages.storage.session import SessionStorage from django.utils.safestring import SafeData, mark_safe def set_session_data(storage, messag...
from tempest_lib.common.utils import data_utils from tempest.api.identity import base from tempest import test class CredentialsTestJSON(base.BaseIdentityV3AdminTest): @classmethod def resource_setup(cls): super(CredentialsTestJSON, cls).resource_setup() cls.projects = list() cls.cre...
"""Basic http server for tests to simulate PyPI or custom indexes """ import time import threading from setuptools.compat import BaseHTTPRequestHandler from setuptools.compat import HTTPServer, SimpleHTTPRequestHandler class IndexServer(HTTPServer): """Basic single-threaded http server simulating a package index ...
from sqlalchemy import Column, String, DateTime, LargeBinary from sqlalchemy.ext.declarative import declarative_base SessionBase = declarative_base() class Session(SessionBase): __tablename__ = 'Sessions' sess_id = Column(String(100), primary_key = True) session_pool_id = Column(String(100), nul...
from django.contrib.sites.models import Site from django.core import urlresolvers, paginator from django.core.exceptions import ImproperlyConfigured from django.utils.six.moves.urllib.parse import urlencode from django.utils.six.moves.urllib.request import urlopen PING_URL = "http://www.google.com/webmasters/tools/pin...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from unittest import skipUnless from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH, BasePasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1Pass...
from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import tabs from openstack_dashboard.api import nova from openstack_dashboard.dashboards.admin.hypervisors.compute import tables class ComputeHostTab(tabs.TableTab): table_classes = (tables.ComputeHostTable,) ...
""" Library Content XBlock Wrapper """ from bok_choy.page_object import PageObject class LibraryContentXBlockWrapper(PageObject): """ A PageObject representing a wrapper around a LibraryContent block seen in the LMS """ url = None BODY_SELECTOR = '.xblock-student_view div' def __init__(self, ...
from __future__ import print_function from . import Image, _imagingmorph import re LUT_SIZE = 1 << 9 class LutBuilder(object): """A class for building a MorphLut from a descriptive language The input patterns is a list of a strings sequences like these:: 4:(... .1. 11...
import sys from cStringIO import StringIO from time import time,sleep, gmtime from django.conf import settings from django import http from django.core.mail import mail_admins from django.core.exceptions import SuspiciousOperation from django.dispatch import Signal from userdata import UserData from theapps.superviso...
"""Unit tests for Cells4.""" import sys import unittest2 as unittest from nupic.math import lgamma class LGammaTest(unittest.TestCase): @unittest.skipIf(sys.platform.startswith("win32"), "Skipping failed test on Windows.") def testLgamma(self): items = ( (0.1, 2.25271265), ...
""" Vend OAuth2 backend: """ from social.backends.oauth import BaseOAuth2 class VendOAuth2(BaseOAuth2): name = 'vend' AUTHORIZATION_URL = 'https://secure.vendhq.com/connect' ACCESS_TOKEN_URL = 'https://{0}.vendhq.com/api/1.0/token' ACCESS_TOKEN_METHOD = 'POST' REDIRECT_STATE = False EXTRA_DAT...
"""Helper functions for the Device Actions.""" import concurrent.futures import logging import sys key_inputs_ = 'inputs' key_intent_ = 'intent' key_payload_ = 'payload' key_commands_ = 'commands' key_id_ = 'id' class DeviceRequestHandler(object): """Asynchronous dispatcher for Device actions commands. Di...
from asignatura import Asignatura class Alumno: UV_MAXIMA = 25 def __init__(self, nombre, numero_cuenta, carrera): self.nombre = nombre self.numero_cuenta = numero_cuenta self.carrera = carrera self.uv_tomadas = 0 self.secciones = [] def adicionar(self, seccion): ...
"""The Dirichlet distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.distributions.python.ops import distribution from tensorflow.contrib.distributions.python.ops import distribution_util from te...
import glob import os import shutil import subprocess import tarfile import tempfile import time from cStringIO import StringIO as CStringIO import requests from .base import Browser, ExecutorBrowser, require_arg from .base import get_timeout_multiplier # noqa: F401 from ..executors import executor_kwargs as base_e...
#!/usr/bin/env python # set air data rate import serial, sys, optparse, time, fdpexpect parser = optparse.OptionParser("show_regs") parser.add_option("--baudrate", type='int', default=57600, help='baud rate') parser.add_option("--rtscts", action='store_true', default=False, help='enable rtscts') parser.add_option("--...
"""Handle events that were forwarded from the segment.io webhook integration""" import datetime import json import logging from django.conf import settings from django.contrib.auth.models import User from django.http import HttpResponse from django.views.decorators.http import require_POST from django.views.decorator...
from functools import wraps from django.conf import settings from django.http import JsonResponse from django.shortcuts import Http404 from ..tasks import * def _onlydebug(f): """ Decorator: Only run the view if we're in debug mode """ @wraps(f) def wrapped(*args, **kwargs): if not settings.DEB...
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsExpression. .. 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. """ __a...
import github.GithubObject import datetime class Rate(github.GithubObject.NonCompletableGithubObject): """ This class represents Rates. The reference can be found here http://developer.github.com/v3/rate_limit """ def __repr__(self): return self.get__repr__({"limit": self._limit.value, "remai...
import logging import fnmatch from dionaea.core import g_dionaea, ihandler from dionaea import ServiceLoader, load_config_from_files, load_submodules logger = logging.getLogger('services') # global slave # keeps track of running services (daemons) # able to restart them g_slave = None g_service_configs = [] clas...
# -*- coding: utf-8 -*- """ werkzeug.exceptions ~~~~~~~~~~~~~~~~~~~ This module implements a number of Python exceptions you can raise from within your views to trigger a standard non-200 response. Usage Example ------------- :: from werkzeug.wrappers import BaseRequest ...
"""Wrong web_socket_transfer_data() signature. """ def web_socket_do_extra_handshake(request): pass def no_web_socket_transfer_data(request): request.connection.write( 'sub/wrong_transfer_sig_wsh.py is called for %s, %s' % (request.ws_resource, request.ws_protocol)) # vi:sts=4 sw=4...
import re __all__ = ['Range', 'ContentRange'] _rx_range = re.compile('bytes *= *(\d*) *- *(\d*)', flags=re.I) _rx_content_range = re.compile(r'bytes (?:(\d+)-(\d+)|[*])/(?:(\d+)|[*])') class Range(object): """ Represents the Range header. """ def __init__(self, start, end): assert end is...
from __future__ import unicode_literals from django import template from temba.contacts.models import Contact, ContactURN, FACEBOOK_SCHEME, TEL_SCHEME, TWITTER_SCHEME, TWILIO_SCHEME, URN_ANON_MASK register = template.Library() URN_SCHEME_ICONS = {TEL_SCHEME: 'icon-mobile-2', TWITTER_SCHEME: 'icon...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.contrib.postgres.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='CharArrayModel', fields=[...
import sys if sys.version >= '3': basestring = str from pyspark.rdd import RDD, ignore_unicode_prefix from pyspark.mllib.common import callMLlibFunc, JavaModelWrapper from pyspark.mllib.linalg import Matrix, _convert_to_vector from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.stat.test import Ch...
# Pipe pipe_926a27580e74684fc63559b92bddaa30 generated by pipe2py from pipe2py import Context from pipe2py.modules.pipeforever import pipe_forever from pipe2py.modules.pipefetch import pipe_fetch from pipe2py.modules.pipeuniq import pipe_uniq from pipe2py.modules.pipefilter import pipe_filter from pipe2py.modules.pipe...
from ..abstract_command import AbstractModelCommand class Command(AbstractModelCommand): help = 'Creates new basic identity for existing principal.' def add_command_arguments(self, parser): principal_parser = parser.add_mutually_exclusive_group(required=True) principal_parser.add_argument( ...
from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options from webkitpy.common.system.executive import ScriptError class DiscardLocalChanges(AbstractStep): @classmethod def options(cls): return AbstractStep.options() + [ Options.clean, ...
from __future__ import unicode_literals import frappe from frappe import msgprint, _ from frappe.utils import getdate, add_days, add_years, cstr from dateutil.relativedelta import relativedelta from frappe.model.document import Document class FiscalYear(Document): def set_as_default(self): frappe.db.set_value("Glo...
""" Flask-Security ============== """ import multiprocessing # pragma: no flakes import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand def get_requirements(suffix=''): with open('requirements%s.txt' % suffix) as f: rv = f.read().splitlines() ...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from transifex.txcommon.fields import UnicodeRegexField help_text...
#!/usr/bin/env python """ A text box stimulus. This module contains a class implementing a text box stimulus. """ __author__ = 'Florian Krause <<EMAIL>>, \ Oliver Lindemann <<EMAIL>>' __version__ = '' __revision__ = '' __date__ = '' import os import re import pygame from . import defaults from .. import _intern...
#! /usr/bin/env python import os import sys import glob version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])) def substitute_file(name): subst = '' f = open(name) for l in f: if '#define LIBTORRENT_VERSION_MAJOR' in l and name.endswith('.hpp'): l = '#define LIBTORRENT_VERSION_MAJO...
from django.contrib.auth.models import User from django.test import TestCase from registration import forms class RegistrationFormTests(TestCase): """ Test the default registration forms. """ def test_registration_form(self): """ Test that ``RegistrationForm`` enforces username const...
from pybench import Test class CreateInstances(Test): version = 2.0 operations = 3 + 7 + 4 rounds = 80000 def test(self): class c: pass class d: def __init__(self,a,b,c): self.a = a self.b = b self.c = c ...