content stringlengths 4 20k |
|---|
from flask import Flask, g, request, request_started, request_finished
from flask.ext.pymongo import PyMongo
from core.config import ConfParser
from core import log
logger=log.getLogger("flaskserver")
from server.flask.views import ro_flask_views
from werkzeug import serving
from OpenSSL import SSL, crypto
import as... |
"""
Tools for accessing the Dota 2 match history web API
"""
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
import logging
import json
from functools import wraps
import os
API_KEY = os.environ.get("DOTA2_API_KEY")
BASE_URL = "http://api.steampowered.com/IDOTA2Matc... |
# -*- coding: utf-8 -*-
class Conversation(object):
"""Conversation management.
https://fleep.io/fleepapi/ref-conversation.html
"""
def __init__(self, server, handler='conversation'):
self._server = server
self._handler = handler
def call(self, *args, **kwargs):
"""
... |
#!/usr/bin/env python
"""SciPy: Scientific Library for Python
SciPy (pronounced "Sigh Pie") is open-source software for mathematics,
science, and engineering. The SciPy library
depends on NumPy, which provides convenient and fast N-dimensional
array manipulation. The SciPy library is built to work with NumPy
arrays, a... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
from ansible.module_utils.network.nxos.nxos import get_config, load_config, run_commands
from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args
from ansibl... |
from collections import OrderedDict
from datetime import datetime, timedelta
import Cookie
import json
import types
import uuid
import socket
from constants import response_codes
from logger import get_logger
missing = object()
class Response(object):
"""Object representing the response to a HTTP request
:p... |
import netaddr
from tempest_lib.common.utils import data_utils
from neutron.tests.api import base
from neutron.tests.tempest import config
from neutron.tests.tempest import test
CONF = config.CONF
class FloatingIPTestJSON(base.BaseNetworkTest):
"""
Tests the following operations in the Quantum API using th... |
from couchpotato.core.helpers.rss import RSS
from couchpotato.core.logger import CPLog
from couchpotato.core.media.movie.providers.automation.base import Automation
log = CPLog(__name__)
autoload = 'Moviemeter'
class Moviemeter(Automation, RSS):
interval = 1800
rss_url = 'http://www.moviemeter.nl/rss/cinem... |
import ConfigParser, io, sys
conf = ''
# read conf and skip header entries (no section)
try:
with open(sys.argv[1], 'r') as cfg:
found_section = False
for l in cfg.readlines():
if len(l.strip()) == 0:
continue
if l[0] != '[' and found_section == False:
... |
# coding: latin-1
import unittest
import ctypes
try:
ctypes.c_wchar
except AttributeError:
pass
else:
import _ctypes_test
dll = ctypes.CDLL(_ctypes_test.__file__)
wcslen = dll.my_wcslen
wcslen.argtypes = [ctypes.c_wchar_p]
class UnicodeTestCase(unittest.TestCase):
def setUp(self):... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['deprecated'],
'supported_by': 'community'}
def check_url(module, url):
parsed_url = urlparse(url)
if len(parsed_url.path) > 0:
sch = parsed_url.scheme
if (sch == 'http' or sch == 'https' or len(p... |
{
'name' : 'Custom security stuff',
'version' : '1.0.0',
'author' : 'Ivan Yelizariev',
'category' : 'Tools',
'website' : 'https://yelizariev.github.io',
'description': """
Tested on 8.0 ab7b5d7732a7c222a0aea45bd173742acd47242d.
""",
'depends' : ['access_base',
'res_user... |
"""
Import/Export pages.
"""
import time
from datetime import datetime
from bok_choy.promise import EmptyPromise
import os
import re
import requests
from ..common.utils import click_css
from .library import LibraryPage
from .course_page import CoursePage
from . import BASE_URL
class TemplateCheckMixin(object):
... |
# $Id: ip6.py 87 2013-03-05 19:41:04Z <EMAIL> $
# -*- coding: utf-8 -*-
"""Internet Protocol, version 6."""
import dpkt
from decorators import deprecated
class IP6(dpkt.Packet):
__hdr__ = (
('_v_fc_flow', 'I', 0x60000000L),
('plen', 'H', 0), # payload length (not including header)
('nxt'... |
#! /usr/bin/env python
from __future__ import print_function
from openturns import *
from math import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
# Instanciate one distribution object
dim = 2
copula = GumbelCopula(2.5)
print("Copula ", repr(copula))
print("Copula ", copula)
print("Mean "... |
# -*- coding: utf-8 -*-
import unittest
import datetime
from cwr.parser.encoder.dictionary import AcknowledgementDictionaryEncoder
from cwr.acknowledgement import AcknowledgementRecord
"""
Acknowledgement to dictionary encoding tests.
The following cases are tested:
"""
__author__ = 'Bernardo Martínez Garrido'
__l... |
# -*- coding: utf-8 -*-
from nose.tools import eq_
from bleach import clean, linkify
def test_japanese_safe_simple():
eq_(u'ヘルプとチュートリアル', clean(u'ヘルプとチュートリアル'))
eq_(u'ヘルプとチュートリアル', linkify(u'ヘルプとチュートリアル'))
def test_japanese_strip():
eq_(u'<em>ヘルプとチュートリアル</em>',
clean(u'<em>ヘルプとチュートリアル</em>'))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import shutil
from migrate.versioning.script import base
from migrate.versioning.template import Template
log = logging.getLogger(__name__)
class SqlScript(base.BaseScript):
"""A file containing plain SQL statements."""
@classmethod
def creat... |
import errno
import os
from gzip import open as gzip_open
from urlparse import urljoin
class HashFileCache(object):
def __init__(self, root, url, gzip=False):
self.root = root
self.url = url
self.gzip = gzip
def create(self, hash):
try:
os.makedirs(os.path.join(sel... |
"""Basic http server for tests to simulate PyPI or custom indexes
"""
import urllib2
import sys
from threading import Thread
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class IndexServer(HTTPServer):
"""Basic single-threaded http server simulating a package index
... |
import SCons, os
def version_flags(env):
if not env['V']:
env['VERSIONCOMSTR'] = 'Version ${TARGET}'
def version_builders(env):
def generate_version_header(target, source, env):
headername = os.path.basename(target[0].abspath)
headerdef = headername.replace('.', '_').replace('-', '_').... |
from django.core.management.base import CommandError
from django.core.management.templates import TemplateCommand
from django.utils.crypto import get_random_string
from django.utils.importlib import import_module
class Command(TemplateCommand):
help = ("Creates a Django project directory structure for the given "... |
"""fuse_gmock_files.py v0.1.0
Fuses Google Mock and Google Test source code into two .h files and a .cc file.
SYNOPSIS
fuse_gmock_files.py [GMOCK_ROOT_DIR] OUTPUT_DIR
Scans GMOCK_ROOT_DIR for Google Mock and Google Test source
code, assuming Google Test is in the GMOCK_ROOT_DIR/gtest
sub-d... |
"""Sets environment variables needed to run a chromium unit test."""
import os
import stat
import subprocess
import sys
# This is hardcoded to be src/ relative to this script.
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CHROME_SANDBOX_ENV = 'CHROME_DEVEL_SANDBOX'
CHROME_SANDBOX_PATH = '/op... |
from image_helper import image_open, local_path
from seammerging import seam_merging
from utils.tvd import TotalVariationDenoising
from utils.seams import print_seams
import cv2
from numpy import size, float64, array, abs
import time
import os
alpha = 0.5
betaEn = 0.5
iterTV = 80
makeNewDecData = False
debug = False... |
"""
DE-specific Form helpers
"""
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select, EMPTY_VALUES
from django.utils.translation import ugettext_lazy as _
import re
id_re = re.compile(r"^(?P<residence>\d{10})(?P<origin>\w{1,3})[-\ ]?(?P<birthday>\d{7})[-\ ]?(?P<validity>... |
from datetime import datetime, tzinfo
from django.template import Library, Node, TemplateSyntaxError
from django.utils import six, timezone
try:
import pytz
except ImportError:
pytz = None
register = Library()
# HACK: datetime is an old-style class, create a new-style equivalent
# so we can define additio... |
from __future__ import unicode_literals
import frappe
import json
from frappe.model.document import Document
from frappe.utils import get_fullname
subject_field = "description"
sender_field = "sender"
exclude_from_linked_with = True
class ToDo(Document):
def validate(self):
self._assignment = None
if self.is_ne... |
from enum import Enum
from flask_admin.model import filters
class BookmarkField(Enum):
ID = 0
URL = 1
TITLE = 2
TAGS = 3
DESCRIPTION = 4
def equal_func(query, value, index):
return filter(lambda x: x[index] == value, query)
def not_equal_func(query, value, index):
return filter(lambda... |
import sys
from collections import Counter
#@lint-avoid-python-3-compatibility-imports
title_words = Counter()
article_words = Counter()
limit = int(sys.argv[3])
for l in open(sys.argv[1]):
splits = l.strip().split("\t")
if len(splits) != 4:
continue
title_parse, article_parse, title, article = l.... |
from django.conf.urls import patterns, include, url
from aspc.housing.views import home, RoomDetail, \
BrowseBuildings, BrowseBuildingFloor, ReviewRoom, ReviewRoomWithChoice, \
search
from django.contrib.auth.decorators import login_required
urlpatterns = [
url(r'^$', home, name="housing_home"),
url(r'... |
from distutils.core import setup, Extension
module = Extension('_lxc', sources=['lxc.c'], libraries=['lxc'])
setup(name='_lxc',
version='0.1',
description='LXC',
packages=['lxc'],
package_dir={'lxc': 'lxc'},
ext_modules=[module]) |
from oslo.config import cfg
import six
from sahara import conductor as c
from sahara import context
from sahara.openstack.common import log as logging
from sahara.utils.openstack import neutron
from sahara.utils.openstack import nova
LOG = logging.getLogger(__name__)
conductor = c.API
CONF = cfg.CONF
def init_inst... |
import unittest
import lib.configurationmanager as conf
from lib.phrase import *
CONFIG_FILE = "../../config/abbr.ini"
class LegacyImporterTest(unittest.TestCase):
def setUp(self):
self.importer = conf.LegacyImporter()
self.importer.load_config(CONFIG_FILE)
def testGlobalSetting... |
from rally.common import db
from rally import consts
from rally import exceptions
_MAP_OLD_TO_NEW_STATUSES = {
"OK": "success",
"FAIL": "fail",
"SKIP": "skip"
}
class Verification(object):
"""Represents results of verification."""
def __init__(self, db_object=None, deployment_uuid=None):
... |
import urllib
import os
def get_ccmp_data(destination='./'):
base_url = 'ftp://podaac-ftp.jpl.nasa.gov/allData/ccmp/L3.5a/monthly/flk/'
for year in range(1987, 2011):
url = base_url + str( year ) + '/'
#print url
for month in range(1,13):
mnth = str( month ) if month >... |
"""
E-commerce Tab Instructor Dashboard Coupons Operations views
"""
import datetime
import logging
import pytz
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _
from django.views.decorators.http import req... |
from nose import SkipTest
import networkx as nx
from networkx.generators.degree_seq import havel_hakimi_graph
class TestSpectrum(object):
@classmethod
def setupClass(cls):
global numpy
global assert_equal
global assert_almost_equal
try:
import numpy
from... |
"""Update third_party/WebKit using git.
Under the assumption third_party/WebKit is a clone of git.webkit.org,
we can use git commands to make it match the version requested by DEPS.
See http://code.google.com/p/chromium/wiki/UsingWebKitGit for details on
how to use this.
"""
import logging
import optparse
import os
... |
import pandas as pd
import requests
import json
import collections
from datetime import datetime
from queries import *
import numpy as np
from pandas import DataFrame
import os
URL_BASE = "https://api.mercadolibre.com/"
def get_selling_speeds(itemids):
"""
Given a list of itemids it calculates
the... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Rename 'date' field to 'created'
db.rename_column('student_courseenrollment', 'date', 'created')
def ... |
from ordereddict import OrderedDict
from qapi import *
import re
import sys
import os
import getopt
import errno
def type_visitor(name):
if type(name) == list:
return 'visit_type_%sList' % name[0]
else:
return 'visit_type_%s' % name
def generate_command_decl(name, args, ret_type):
arglist=... |
import yaml
import json
import os
def loadFromFile(file_name):
fileContents = ''
path = '/'.join(os.path.dirname(__file__).split('/')[0:-1])
with open((os.path.join(path,file_name)), 'r') as file:
fileContents = file.read()
file.close()
return fileContents
def loadConfig(file_name):
... |
from .protocol import TBinaryProtocol
from .transport import TTransport
def serialize(thrift_object,
protocol_factory=TBinaryProtocol.TBinaryProtocolFactory()):
transport = TTransport.TMemoryBuffer()
protocol = protocol_factory.getProtocol(transport)
thrift_object.write(protocol)
return ... |
# -*- coding: utf-8 -*-
from ..Qt import QtCore, QtGui
import weakref
class Container(object):
#sigStretchChanged = QtCore.Signal() ## can't do this here; not a QObject.
def __init__(self, area):
object.__init__(self)
self.area = area
self._container = None
self._stretch =... |
'''
This reads a configuration file and checks for functioning
network links in /sys/class/net/*, then emits a ks.cfg network line.
'''
import os
import re
# Global bad:
global DEBUG
DEBUG = True
global TO_LOG
# This "logs" to stdout which is captured during kickstart
TO_LOG = True
# This is the stan... |
from broccoli_base import *
import numpy
from nibabel import nifti1
import os
import site
import shutil
BROCCOLI_LIB_BASE = BROCCOLI_LIB
# DONE: Check that passing arrays to C method as 1D packed arrays is the same as passing arays using the 3D array wrappers
# DONE: Check that packing (packVolume) and unpacking (u... |
from __future__ import unicode_literals, print_function
import six
import os
__all__ = (
'has_command_handler',
'call_command_handler',
)
COMMANDS_TO_HANDLERS = {} # Global mapping Vi commands to their handler.
COMMANDS_TAKING_FILENAMES = set() # Name of commands that accept files.
SET_COMMANDS = {} # Map... |
from __future__ import absolute_import
import warnings
from .decorators import apply_defaults as _apply_defaults
def apply_defaults(func):
warnings.warn_explicit(
"""
You are importing apply_defaults from airflow.utils which
will be deprecated in a future version.
Please use :
... |
from datetime import date, timedelta
from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.test import TestCase
class TokenGeneratorTest(TestCase):
def test_make_token(self):
"""
... |
"""Fill in this module with configuration data to use in tests.
See comments in the source code for explanations of the settings.
"""
import os
# To actually run the tests which use this configuration information you must
# change RUN_LIVE_TESTS to True.
RUN_LIVE_TESTS = False
# If set to True, the client will sa... |
#!/usr/bin/python
import unittest
from PySide2.QtXml import QXmlSimpleReader
class QXmlSimpleReaderTest(unittest.TestCase):
def testQXmlSimpleReaderInstatiation(self):
'''QXmlSimpleReader must be a concrete class not an abstract one.'''
reader = QXmlSimpleReader()
def testQXmlSimpleReaderFeat... |
# -*- coding: utf-8 -*-
from gluon import *
from s3 import *
from s3layouts import *
try:
from .layouts import *
except ImportError:
pass
import s3menus as default
# Below is an example which you can base your own template's menus.py on
# - there are also other examples in the other templates folders
# =====... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import crypt
from datetime import date, timedelta
from ansible.module_utils.basic import A... |
print('main.py was successfully called')
print('this is the new main.py')
import sys
print('python version is: ' + sys.version)
print('python path is', sys.path)
import os
print('imported os')
print('contents of this dir', os.listdir('./'))
from flask import (
Flask,
render_template,
request,
Markup
... |
#coding=utf-8
#-*- encoding: utf-8 -*-
from datetime import datetime, timedelta
from MySQL import MySQL
from random import randint
import Config
import Utils
import UserService
def space_list(data):
userId = UserService.user_id(data['UserKey'])
db = MySQL()
spaceListInstance = db.list('SELECT * FROM `space` WHE... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ast
import sys
import yaml
from ansible.module_utils._text import to_text
# There are currently defaults for all metadata fields so we can add it
# automatically if a file doesn't specify it
DEFAULT_METADATA = {'metadata... |
# coding: utf-8
from openerp import models, api, _
from openerp.exceptions import Warning
class sale_order_line(models.Model):
_inherit = 'sale.order.line'
@api.multi
def _check_routing(self, product, warehouse):
""" skip stock verification if the route goes from supplier to customer
... |
from __future__ import unicode_literals, division, absolute_import
import glob
import logging
import os
import urllib
import urlparse
import os.path
from sqlalchemy import Column, Integer, String, ForeignKey, or_, and_, DateTime, Boolean
from sqlalchemy.orm import backref, relationship
from sqlalchemy.schema import Ta... |
import fnmatch
import optparse
import os
import sys
from util import build_utils
from util import md5_check
def DoJar(options):
class_files = build_utils.FindInDirectory(options.classes_dir, '*.class')
for exclude in build_utils.ParseGypList(options.excluded_classes):
class_files = filter(
lambda f: ... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'community'}
import os
import re
import time
HAS_XMPP = True
try:
import xmpp
except ImportError:
HAS_XMPP = False
def main():
module = AnsibleModule(
argument_s... |
# -*- coding: utf-8 -*-
import re
import short_url
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from pdl_scraper.items import PdlScraperItem
LEGISLATURA = 2006
class ProyectoSpider2006(CrawlSpider):
name = "proyecto_2006"
allowed_domains = ["ww... |
from openerp import tools
from openerp.osv import osv, fields
from openerp.tools.translate import _
class base_language_install(osv.osv_memory):
""" Install Language"""
_name = "base.language.install"
_description = "Install Language"
_columns = {
'lang': fields.selection(tools.scan_languages(... |
"""This code example creates new orders.
To determine which orders exist, run get_all_orders.py."""
__author__ = ('Nicholas Chen',
'Joseph DiLallo')
import uuid
# Import appropriate modules from the client library.
from googleads import dfp
COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
SALESPERSON... |
#!/usr/bin/env python
from translate.convert import json2po, test_convert
from translate.misc import wStringIO
from translate.storage import jsonl10n
class TestJson2PO:
def json2po(self, jsonsource, template=None, filter=None):
"""helper that converts json source to po source without requiring files"""
... |
class Cud():
def __init__(self):
print("__init__ called")
def __repr__(self):
print("__repr__ called")
return ""
def __lt__(self, other):
print("__lt__ called")
def __le__(self, other):
print("__le__ called")
def __eq__(self, other):
print("__eq__... |
#!/usr/bin/python
__author__ = 'Wei'
from Tkinter import *
import Tkinter as tk
import tkMessageBox
import serial
import time
import thread
import traceback
import binascii
class ScrolledText(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent)
self.text = tk.Te... |
import argparse
import os
import re
import sys
import mxnet as mx
if sys.version_info >= (3, 0):
import configparser
else:
import ConfigParser as configparser
def parse_args(file_path):
default_cfg = configparser.ConfigParser()
default_cfg.read(file_path)
parser = argparse.ArgumentParser()
... |
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
from openerp.tools.translate import _
class CashBox(osv.osv_memory):
_register = False
_columns = {
'name' : fields.char('Reason', required=True),
# Attention, we don't set a domain, because there is a journal_typ... |
"""
Script to check for new clusterfuzz issues since the last rolled v8 revision.
Returns a json list with test case IDs if any.
Security considerations: The security key and request data must never be
written to public logs. Public automated callers of this script should
suppress stdout and stderr and only process c... |
from vcdtestutil import VCDTestCase, VCDTestLoader, mSec
class TestCase(VCDTestCase):
p2irq = {
"atmega128": "IRQ.VECTOR14",
"at90s4433": "IRQ.VECTOR5",
"at90s8515": "IRQ.VECTOR6",
"atmega48": "IRQ.VECTOR13",
}
def setUp(self):
self.getVCD()
self.setClock(4000000)
self.processo... |
#!/usr/local/bin/python
import sys
import getopt
from genxmlif import GenXmlIfError
from xsvalErrorHandler import ErrorHandler, XsvalError
from minixsv import *
from pyxsval import parseAndValidate
##########################################
# minixsv Wrapper for calling minixs... |
import sys
try:
reversed = reversed
except NameError:
def reversed(sequence):
"""reversed(sequence) -> reverse iterator over values of the sequence
Return a reverse iterator
"""
if hasattr(sequence, '__reversed__'):
return sequence.__reversed__()
if not hasa... |
from ltk.actions.action import *
class RmAction(Action):
def __init__(self, path):
Action.__init__(self, path)
self.use_delete = False
def rm_action(self, file_patterns, **kwargs):
try:
removed_folder = False
for pattern in file_patterns:
if os.p... |
from __future__ import unicode_literals
import datetime
import os
import subprocess
def get_version(version=None):
"Returns a PEP 386-compliant version number from VERSION."
if version is None:
from django import VERSION as version
else:
assert len(version) == 5
assert version[3] i... |
from gnuradio import gr, blocks
from gnuradio.eng_option import eng_option
from optparse import OptionParser
import os, sys
try:
from gnuradio import qtgui
from PyQt4 import QtGui, QtCore
import sip
except ImportError:
print "Error: Program requires PyQt4 and gr-qtgui."
sys.exit(1)
try:
import... |
import types
def is_valid_signed(bits, val):
if type(val) not in (types.IntType, types.LongType): return False
e = bits - 1
min_val = -(2 ** e)
if val < min_val: return False
max_val = (2 ** e) - 1
if val > max_val: return False
return True
def is_valid_unsigned(bits, val):
... |
# Run the _testcapi module tests (tests for the Python/C API): by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.
from __future__ import with_statement
import sys
import time
import random
import unittest
from test import test_support
try:
import thread
import threading
excep... |
from django.db.backends.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict_... |
# pylint: disable=invalid-name
"""
Utility library for working with the edx-milestones app
"""
from django.conf import settings
from django.utils.translation import ugettext as _
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from openedx.core.djangoapps.content.course_overviews.m... |
from lintreview.review import Problems
from lintreview.review import Comment
from lintreview.tools.pep8 import Pep8
from unittest import TestCase
from nose.tools import eq_
class TestPep8(TestCase):
fixtures = [
'tests/fixtures/pep8/no_errors.py',
'tests/fixtures/pep8/has_errors.py',
]
d... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, cint
from erpnext.accounts.report.trial_balance.trial_balance import validate_filters
def execute(filters=None):
validate_filters(filters)
show_party_name = is_party_name_visible(filters)
columns = get_colu... |
import asyncio
from pulsar import when_monitor_start, get_application, task, send
from pulsar.apps.data import create_store
from pulsar.apps.ds import PulsarDS
def start_pulsar_ds(arbiter, host, workers=0):
lock = getattr(arbiter, 'lock', None)
if lock is None:
arbiter.lock = lock = asyncio.Lock()
... |
"""
Unit Tests for cells scheduler filters.
"""
from nova.cells import filters
from nova import context
from nova.db.sqlalchemy import models
from nova import test
from nova.tests.unit.cells import fakes
class FiltersTestCase(test.NoDBTestCase):
"""Makes sure the proper filters are in the directory."""
def ... |
"""
Base/mixin classes for the spatial backend database operations and the
`SpatialRefSys` model the backend.
"""
import re
from django.contrib.gis import gdal
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class BaseSpatialOperations(object):
"""
This module holds... |
"""
Tests for the Video Branding configuration.
"""
from django.test import TestCase
from django.core.exceptions import ValidationError
from nose.plugins.attrib import attr
from branding.models import BrandingInfoConfig
@attr('shard_1')
class BrandingInfoConfigTest(TestCase):
"""
Test the BrandingInfoConfig ... |
import logging
import re
import time
from autotest.client.shared import error
from autotest.client import utils
from virttest import data_dir, storage, utils_disk, utils_test, env_process
from virttest import funcatexit
@error.context_aware
def run(test, params, env):
"""
Timer device boot guest:
1) Sync... |
tests = r"""
# ZAIDField #################################################################
ZAIDField validates that the date is a valid birthdate and that the value
has a valid checksum. It allows spaces and dashes, and returns a plain
string of digits.
>>> from django.contrib.localflavor.za.forms import ZAIDField
>>... |
from PyQt4.QtGui import QKeySequence
from PyQt4.QtCore import Qt
# A-G
STAGE_MODIFIED = Qt.AltModifier | Qt.Key_A
WORD_LEFT = Qt.Key_B
BRANCH = Qt.ControlModifier | Qt.Key_B
CHECKOUT = Qt.AltModifier | Qt.Key_B
CHERRY_PICK = Qt.ControlModifier | Qt.ShiftModifier | Qt.Key_C
DIFFSTAT = Qt.AltModifier | Qt.Key_D
DIFF = Q... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
class TestPythonConstants(unittest.TestCase):
def testStrings(self):
from .constants import constants
self.assertEquals(constants.apo... |
from __future__ import unicode_literals
import binascii
import unittest
from django.contrib.gis import memoryview
from django.utils.unittest import skipUnless
from ..import HAS_GEOS
if HAS_GEOS:
from .. import GEOSGeometry, WKTReader, WKTWriter, WKBReader, WKBWriter, geos_version_info
@skipUnless(HAS_GEOS, "G... |
"""Config flow to configure deCONZ component."""
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.core import callback
from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT
from homeassistant.helpers import aiohttp_client
from homeassistant.util.json import load_json
... |
import os
from .. import errors
from .. import udev
from ..size import Size
LINUX_SECTOR_SIZE = Size(512)
def get_device_majors():
majors = {}
for line in open("/proc/devices").readlines():
try:
(major, device) = line.split()
except ValueError:
continue
try:
... |
import sys
if sys.version_info[0] >= 3:
import builtins as __builtin__ # Py3
else:
import __builtin__
try:
import java.lang #@UnusedImport
from _pydev_bundle import _pydev_jy_imports_tipper
_pydev_imports_tipper = _pydev_jy_imports_tipper
except ImportError:
IS_JYTHON = False
from _pydev_b... |
from . import get_desired_value
import sys
import os
import tempfile
import shutil
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
from cloudify.decorators import operation
from cloudify.excepti... |
jA0EAwMCWguE8aVZVWVgyey4FXnPY1gLFI14rvxeJekDYz0ux5SwAl3Loh3iLdQN
W3XHLJhfj+ygfQuY+ol2b21gh7VswD7w4NZ2Grkdo5lDH4DP5X0tlGi+jsRNe9WS
vS5qYn+nO54KxgzIRQdSneALo3vCBm+waDnsuMSTpGOIXIujdOZJd2LacUMNXbhx
ViCl9T788kkWKVGv8i/AOfYfafaCKdp8S1Ycc9Lo62iOyP0dOdfjAvg9Mx7iMVH7
5XDRwP3wvizS/NKgH6eP0Cp3VR+XLMyvrTrzAKCej8TIEQYHq92Z4ToPcNj0... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
time.py - Tests the output coming from an Arduino with FreeIMU for speed.
Load the Arduino with the FreeIMU_serial program.
Copyright (C) 2012 Fabio Varesano <<EMAIL>>
Development of this code has been supported by the Department of Computer Science,
Universita' degli S... |
"""This module constructs Hamiltonians for the uniform electron gas."""
from __future__ import absolute_import
import numpy
from projectq.ops import QubitOperator
from fermilib.ops import FermionOperator
# Exceptions.
class OrbitalSpecificationError(Exception):
pass
def orbital_id(grid, grid_coordinates, spi... |
"""distutils.bcppcompiler
Contains BorlandCCompiler, an implementation of the abstract CCompiler class
for the Borland C++ compiler.
"""
# This implementation by Lyle Johnson, based on the original msvccompiler.py
# module and using the directions originally published by Gordon Williams.
# XXX looks like there's a L... |
"""
Views for login / logout and associated functionality
Much of this file was broken out from views.py, previous history can be found there.
"""
import logging
from django.conf import settings
from django.contrib.auth import authenticate, login as django_login
from django.contrib.auth.decorators import login_requi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.