content string |
|---|
import json
import os
import unittest
from unittest.mock import MagicMock
from pywink.api import get_devices_from_response_dict
from pywink.devices import types as device_types
from pywink.devices.piggy_bank import WinkPorkfolioBalanceSensor
from pywink.devices.smoke_detector import WinkSmokeDetector, WinkCoDetector,... |
# -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""Test for Video Xmodule functional logic.
These test data read from xml, not from mongo.
We have a ModuleStoreTestCase class defined in
common/lib/xmodule/xmodule/modulestore/tests/django_utils.py.
You can search for usages of this in the cms and lms tests ... |
"""Logging control and utilities.
Control of logging for SA can be performed from the regular python logging
module. The regular dotted module namespace is used, starting at
'sqlalchemy'. For class-level logging, the class name is appended.
The "echo" keyword parameter, available on SQLA :class:`.Engine`
and :class... |
import sys
import unittest
try:
import simplejson as json
except ImportError:
import json
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import urlparse
from libcloud.utils.py3 import b
from libcloud.utils.py3 import parse_qsl
from libcloud.common.cloudstack import CloudStackConnection
from l... |
# -*- coding: utf-8 -*-
import re
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx import addnodes
from sphinx.roles import XRefRole
from sphinx.locale import l_, _
from sphinx.domains import Domain, ObjType, Index
from sphinx.directives import ObjectDescription
from sphinx.util.nod... |
# Generic tests that all raw classes should run
from os import path as op
import math
import pytest
import numpy as np
from numpy.testing import (assert_allclose, assert_array_almost_equal,
assert_equal, assert_array_equal)
from mne import concatenate_raws, create_info
from mne.datasets imp... |
from six import PY2
from tornado import escape
from tornado.web import HTTPError
# HTTP status code
HTTP_OK = 200
ERROR_BAD_REQUEST = 400
ERROR_UNAUTHORIZED = 401
ERROR_FORBIDDEN = 403
ERROR_NOT_FOUND = 404
ERROR_METHOD_NOT_ALLOWED = 405
ERROR_INTERNAL_SERVER_ERROR = 500
# Custom error code
ERROR_WARNING = 1001
ERROR... |
"""
Tests of neo.io.NSDFIO
"""
import numpy as np
import quantities as pq
from datetime import datetime
import os
import unittest
from neo.io.nsdfio import HAVE_NSDF, NSDFIO
from neo.test.iotest.common_io_test import BaseTestIO
from neo.core import AnalogSignal, Segment, Block, ChannelIndex
from neo.test.tools impor... |
"""
.. module: security_monkey.watchers.keypair
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Patrick Kelley <<EMAIL>> @monkeysecurity
"""
from security_monkey.watcher import Watcher
from security_monkey.watcher import ChangeItem
from security_monkey.constants import TROUBLE_REGIONS
from security_mo... |
"""Functional test for slot_creator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops... |
"""
This module houses the GeoIP object, a ctypes wrapper for the MaxMind GeoIP(R)
C API (http://www.maxmind.com/app/c). This is an alternative to the GPL
licensed Python GeoIP interface provided by MaxMind.
GeoIP(R) is a registered trademark of MaxMind, LLC of Boston, Massachusetts.
For IP-based geoloca... |
"""oslo.i18n integration module.
See http://docs.openstack.org/developer/oslo.i18n/usage.html .
"""
import oslo_i18n
_translators = oslo_i18n.TranslatorFactory(domain='keystone')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbrev... |
"""
Move a file in the safest way possible::
>>> from django.core.files.move import file_move_safe
>>> file_move_safe("/tmp/old_file", "/tmp/new_file")
"""
import os
from django.core.files import locks
try:
from shutil import copystat
except ImportError:
import stat
def copystat(src, dst):
... |
"""SQL connections, SQL execution and high-level DB-API interface.
The engine package defines the basic components used to interface
DB-API modules with higher-level statement construction,
connection-management, execution and result contexts. The primary
"entry point" class into this package is the Engine and it's p... |
"""Helper functions for working with signals"""
import logging
from twisted.internet.defer import maybeDeferred, DeferredList, Deferred
from twisted.python.failure import Failure
from scrapy.xlib.pydispatch.dispatcher import Any, Anonymous, liveReceivers, \
getAllReceivers, disconnect
from scrapy.xlib.pydispatch... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_vm_facts
short_description: Return basic facts pertaining to a vSphere virtual ... |
from django.template.defaultfilters import addslashes
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class AddslashesTests(SimpleTestCase):
@setup({'addslashes01': '{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }}{% endautoescape %}'})
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
TRANSFERS_FILES = False
UNUSED_PARAMS = {
'systemd': ['pattern', 'runlevel', 'sleep', 'arguments', 'args'],
}
def run(self,... |
{
'name': 'Partner Entities Menus for tko_l10n_br_base',
'version': '0.007',
'category': 'Customization',
'sequence': 18,
'complexity': 'normal',
'description': ''' This module creates partner menus for tko_l10n_br_base new fields under Settings -> Technical''',
'author': 'ThinkOpen Solution... |
import argparse
import json
from pprint import pprint
def convertToM(number, btype):
if (btype == 'KBytes' or btype == 'Kbits/sec'):
return number/1000
elif (btype == 'Bytes' or btype == 'Bits/sec'):
return number/1000000
else:
return number
def parseIPerf(file_name, json_data):
... |
import sys
import ns.applications
import ns.core
import ns.internet
import ns.mobility
import ns.network
import ns.point_to_point
import ns.wifi
# void
# DevTxTrace (std::string context, Ptr<const Packet> p, Mac48Address address)
# {
# std::cout << " TX to=" << address << " p: " << *p << std::endl;
# }
# void
# Dev... |
import unittest
import mock
from pulp.server.db.model.repository import RepoContentUnit
REPOSITORY = 'pulp.server.db.model.repository'
class TestRepoContentUnit(unittest.TestCase):
def setUp(self):
self.unit = RepoContentUnit('repo1', 'unit1', 'rpm')
def test_utc_in_iso8601(self):
# make ... |
"""Tests for the Atag integration."""
from homeassistant.components.atag import DOMAIN
from homeassistant.const import CONF_EMAIL, CONF_HOST, CONF_PORT, CONTENT_TYPE_JSON
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
USER... |
import logging
from .gui.widgets import MacroEditor
from .utils import install_locale
install_locale('pronterface')
def injector(gcode, viz_layer, layer_idx):
cb = lambda toadd: inject(gcode, viz_layer, layer_idx, toadd)
z = gcode.all_layers[layer_idx].z
z = z if z is not None else 0
MacroEditor(_("I... |
def make_factory(ziphashes):
"""ZipFileSet factory routine that looks up zipfiles in a dict;
each zipfile should also be a dict of member names -> contents."""
class MockZipFileSet(object):
def __init__(self, url):
self._url = url
self._ziphash = ziphashes[url]
def n... |
import os
from io import BytesIO
from django.utils import timezone
from django.template.loader import get_template
from django.template import Context
from django.core.mail import EmailMessage
from django.conf import settings
from reportlab.pdfgen import canvas
from reportlab.platypus import Table
from reportlab.lib.p... |
"""Contains the logic for `aq make aquilon`."""
from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611
from aquilon.worker.commands.make import CommandMake
class CommandMakeAquilon(CommandMake):
def render(self, **arguments):
arguments['archetype'] = 'aquilon'
return CommandMa... |
import rope.base.codeanalyze
import rope.base.evaluate
from rope.base import worder, exceptions, utils
from rope.base.codeanalyze import ArrayLinesAdapter, LogicalLineFinder
class FixSyntax(object):
def __init__(self, pycore, code, resource, maxfixes=1):
self.pycore = pycore
self.code = code
... |
from msrest.serialization import Model
class MetricValue(Model):
"""Represents database metrics.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar count: The number of values for the metric.
:vartype count: float
:ivar average: The average value of... |
import bson.json_util
from tests import base
from girder.constants import AccessType
from girder.models.collection import Collection
from girder.models.folder import Folder
from girder.models.item import Item
from girder.models.user import User
def setUpModule():
base.enabledPlugins.append('mongo_search')
ba... |
"""Reuters newswire topic classification dataset.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import numpy as np
from six.moves import zip # pylint: disable=redefined-builtin
from tensorflow.contrib.keras.python.keras.utils.data_utils... |
import xml.sax
import xml.sax.handler
import types
try:
_StringTypes = [types.StringType, types.UnicodeType]
except AttributeError:
_StringTypes = [types.StringType]
START_ELEMENT = "START_ELEMENT"
END_ELEMENT = "END_ELEMENT"
COMMENT = "COMMENT"
START_DOCUMENT = "START_DOCUMENT"
END_DOCUMENT = "END_DOCUMENT"
... |
# PermWrapper and PermLookupDict proxy the permissions system into objects that
# the template system can understand.
class PermLookupDict(object):
def __init__(self, user, app_label):
self.user, self.app_label = user, app_label
def __repr__(self):
return str(self.user.get_all_permissions())
... |
import argparse
import collections
import csv
import re
import json
import os
import random
import subprocess
import sys
import time
import urllib2
import zlib
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
OWNERS_PATH = os.path.abspath(
os.path.join(BASE_DIR, '..', 'test', 'test_owners.csv'))
GCS_URL_BASE ... |
class ChainException(Exception):
pass
class NodeException(Exception):
pass
class Chain:
"""Stores a list of nodes that are linked together."""
def __init__(self):
"""Initiates a node chain: (self)."""
self.chain={}
self.id=-1
def _get_id(self):
"""Gets a new i... |
import sys
from collections import OrderedDict
from django.contrib.admin import FieldListFilter
from django.contrib.admin.exceptions import (
DisallowedModelAdminLookup, DisallowedModelAdminToField,
)
from django.contrib.admin.options import (
IS_POPUP_VAR, TO_FIELD_VAR, IncorrectLookupParameters,
)
from djang... |
# encoding: utf-8
from yast import import_module
import_module('UI')
from yast import *
class CheckBox3Client:
def main(self):
# Build dialog with one check box and buttons to set its state to
# on, off or "don't care" (tri-state).
UI.OpenDialog(
VBox(
CheckBox(Id("cb"), "Forma... |
"""Disassembler of Python byte code into mnemonics."""
import sys
import types
from opcode import *
from opcode import __all__ as _opcodes_all
__all__ = ["dis", "disassemble", "distb", "disco",
"findlinestarts", "findlabels"] + _opcodes_all
del _opcodes_all
_have_code = (types.MethodType, types.FunctionT... |
import logging
import os
# Setup logging for this module.
logging.basicConfig(level=logging.INFO, format='[%(name)s] %(threadName)s: %(message)s')
LOG = logging.getLogger('query_executor')
LOG.setLevel(level=logging.INFO)
# globals.
hive_result_regex = 'Time taken: (\d*).(\d*) seconds'
## TODO: Split executors into ... |
from openerp.osv import fields, osv
from openerp.tools.sql import drop_view_if_exists
from openerp.addons.decimal_precision import decimal_precision as dp
class res_country(osv.osv):
_name = 'res.country'
_inherit = 'res.country'
_columns = {
'intrastat': fields.boolean('Intrastat member'),
}
... |
from google.appengine.api import memcache
from google.appengine.api import urlfetch
import webapp2
import base64
"""A simple appengine app that hosts .html files in src/styleguide/c++ from
chromium's git repo."""
class MainHandler(webapp2.RequestHandler):
def get(self):
handler = GitilesMirrorHandler()
... |
from education_group.ddd import command
from education_group.ddd.domain import mini_training
from education_group.ddd.repository import mini_training as mini_training_repositoty
def get_mini_training(cmd: command.GetMiniTrainingCommand) -> mini_training.MiniTraining:
mini_training_id = mini_training.MiniTrainingI... |
data = (
'Dao ', # 0x00
'Diao ', # 0x01
'Dao ', # 0x02
'Ren ', # 0x03
'Ren ', # 0x04
'Chuang ', # 0x05
'Fen ', # 0x06
'Qie ', # 0x07
'Yi ', # 0x08
'Ji ', # 0x09
'Kan ', # 0x0a
'Qian ', # 0x0b
'Cun ', # 0x0c
'Chu ', # 0x0d
'Wen ', # 0x0e
'Ji ', # 0x0f
'Dan ', # 0x10
'Xi... |
"""
Test SVAR estimation
"""
import statsmodels.api as sm
from statsmodels.tsa.vector_ar.svar_model import SVAR
from numpy.testing import assert_almost_equal, assert_equal, assert_allclose
from .results import results_svar
import numpy as np
import numpy.testing as npt
DECIMAL_6 = 6
DECIMAL_5 = 5
DECIMAL_4 = 4
class... |
"""
Totally untested thread pool class.
Tries to not get more than "maximum" (but this is not a hard limit).
Kills off up to around half of its workers when more than half are idle.
"""
from __future__ import print_function
from __future__ import with_statement
from threading import Thread, RLock
from Queue import Que... |
from ginga.canvas.CanvasObject import *
class RenderContext(object):
def __init__(self, viewer):
self.viewer = viewer
# TODO: encapsulate this drawable
#self.cr = GraphicsContext(self.viewer.pixmap)
self.cr = None
def __get_color(self, color, alpha):
# return a color ... |
from openerp import tools
from openerp.osv import osv, fields
class product_style(osv.Model):
_name = "product.style"
_columns = {
'name' : fields.char('Style Name', required=True),
'html_class': fields.char('HTML Classes'),
}
class product_pricelist(osv.Model):
_inherit = "product.pri... |
from neutron.api import extensions
EXTENDED_ATTRIBUTES_2_0 = {
'subnets': {
"enable_dhcp": {'allow_post': False, 'allow_put': False,
'default': False,
'is_visible': True},
}
}
class Subnets_quark(extensions.ExtensionDescriptor):
"""Extends subnets f... |
import warnings
import os
import pipes
import socket
import random
import logging
import traceback
import fcntl
import sys
from termios import tcflush, TCIFLUSH
from binascii import hexlify
from ansible.callbacks import vvv
from ansible import errors
from ansible import utils
from ansible import constants as C
... |
import sys, time
from file_check import *
check_data_files()
from print_trade_info import set_low_balance_msg, print_trade, reset_print_info
from db_access import db_connect, db_exists, output_records_exist, output_init_record, get_last_output_record
from balances import *
from analyst import *
from trader import *
f... |
from ctypes import c_char_p, c_int, c_size_t, c_ubyte, c_uint, POINTER
from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR, PREPGEOM_PTR, GEOS_PREPARE
from django.contrib.gis.geos.prototypes.errcheck import \
check_geom, check_minus_one, check_sized_string, check_string, check_zero
from django.contrib.gis.... |
import unittest
import sqlalchemy
import sqlalchemy.dialects.mssql as mssql
import sqlalchemy.dialects.postgresql as postgresql
from ..compiler.sqlalchemy_extensions import print_sqlalchemy_query_string
from .test_helpers import compare_sql, get_sqlalchemy_schema_info
class CommonIrLoweringTests(unittest.TestCase):... |
from __future__ import division
class SelectionAlgorithm:
'''
Implements a selective compression algorithm. This algorithm determines
whether a given file should be compressed or not.
This class is designed as a base class; actual selection algorithms should
be implemented as child classes.
... |
import win32security, ntsecuritycon, winnt
class Enum:
def __init__(self, *const_names):
"""Accepts variable number of constant names that can be found in either
win32security, ntsecuritycon, or winnt."""
for const_name in const_names:
try:
const_val=getattr(... |
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../")
import time
import datetime
from pymcda.electre_tri import MRSort
from pymcda.generate import generate_categories_profiles
from pymcda.pt_sorted import SortedPerformanceTable
from pymcda.types import CriterionValue, CriteriaValues
fr... |
from openerp.tests import common
class TestSaleTeamRoute(common.TransactionCase):
def setUp(self):
super(TestSaleTeamRoute, self).setUp()
self.sale_order_model = self.env['sale.order']
self.sale_line_model = self.env['sale.order.line']
self.product = self.env.ref('product.product_... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
# NOQA
class CloudWatchEventRule(object):
def __init__(self, module, name, client, schedule_expression=None,
event_pattern=None, description=None, role_arn=... |
from datetime import date, datetime
from decimal import Decimal
from infinity import inf
from pytest import mark
from intervals import (
DateInterval,
DateTimeInterval,
DecimalInterval,
FloatInterval,
IntInterval
)
class TestIntervalProperties(object):
@mark.parametrize(
('interval',... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .handlers_base import HandlerBase
import errno
import six
import logging
import numpy as np
import uuid
import os
import os.path as op
import datetime
import filestore.api as fsc
logger = logging.getLogg... |
from xadmin.sites import AdminSite, site
VERSION = [0,4,4]
class Settings(object):
pass
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
from django.conf... |
from nova import db
from nova.db.sqlalchemy import api as db_api
from nova.db.sqlalchemy import models
from nova import exception
from nova import objects
from nova.objects import base as obj_base
from nova.objects import fields
FLOATING_IP_OPTIONAL_ATTRS = ['fixed_ip']
# TODO(berrange): Remove NovaObjectDictCompat
... |
import datetime
from calendar import timegm
from jwt import InvalidTokenError, decode as jwt_decode
from openid.consumer.consumer import Consumer, SUCCESS, CANCEL, FAILURE
from openid.consumer.discover import DiscoveryFailure
from openid.extensions import sreg, ax, pape
from social.utils import url_add_parameters
fr... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j. F Y'
TIME_FORMAT = 'H:i:s'
DATETIME_FORMAT = 'j. F Y H:i:s'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT =... |
import datetime
import time
import logging
import uuid
from openerp import fields, _
from .base_parser import BaseSwissParser
_logger = logging.getLogger(__name__)
class G11Parser(BaseSwissParser):
"""
Parser for BVR DD type 2 Postfinance Statements
(can be wrapped in a g11 file)
"""
... |
#!/usr/bin/env python
# vim:fileencoding=utf-8
from argparse import ArgumentParser, FileType
import time
import warnings
import os, sys, io
import signal
class ArgParser(object):
def __init__(self, description, version):
self.__description = description
self.__version = version
self.... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Flask
from eduid_common.api.logging import init_logging
from eduid_common.api.exceptions import init_exception_handlers
from eduid_userdb import UserDB
from eduid_userdb.proofing import LetterProofingStateDB
from idproofing_letter.ekopos... |
"""Contains container classes to represent different protocol buffer types.
This file defines container classes which represent categories of protocol
buffer field types which need extra maintenance. Currently these categories
are:
- Repeated scalar fields - These are all repeated fields which aren't
composite (... |
class JumpBridge:
""" class representing a Jump Bridge between two systems. The order of from/to is irrelevant """
def __init__(self, sys_from, planet_from, moon_from, sys_to, planet_to, moon_to, owner, password, comment=""):
self.sys_from = sys_from
self.planet_from = planet_from
self.m... |
# -*- coding: utf-8 -*-
#
# pylearn2 documentation build configuration file
# It is based on Theano documentation build
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module impo... |
"""Shared OS X support functions."""
import os
import re
import sys
__all__ = [
'compiler_fixup',
'customize_config_vars',
'customize_compiler',
'get_platform_osx',
]
# configuration variables that may contain universal build flags,
# like "-arch" or "-isdkroot", that may need customization for
# the... |
import os
import re
import pytz3 as pytz
_cache_tz = None
def _tz_from_env(tzenv):
if tzenv[0] == ':':
tzenv = tzenv[1:]
# TZ specifies a file
if os.path.exists(tzenv):
with open(tzenv, 'rb') as tzfile:
return pytz.tzfile.build_tzinfo('local', tzfile)
# TZ specifies a zon... |
from AlgorithmImports import *
### <summary>
### This regression algorithm tests that we receive the expected data when
### we add future option contracts individually using <see cref="AddFutureOptionContract"/>
### </summary>
class AddFutureOptionContractDataStreamingRegressionAlgorithm(QCAlgorithm):
def Initiali... |
"""
Simple utility functions for computing access.
It allows us to share code between access.py and block transformers.
"""
from datetime import datetime, timedelta
from logging import getLogger
from django.conf import settings
from pytz import UTC
from courseware.access_response import AccessResponse, StartDateErro... |
"""Unit tests for the json_value module."""
import unittest
from apache_beam.internal.gcp.json_value import from_json_value
from apache_beam.internal.gcp.json_value import to_json_value
from apache_beam.options.value_provider import RuntimeValueProvider
from apache_beam.options.value_provider import StaticValueProvid... |
from __future__ import unicode_literals
import string
import warnings
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db import models
from django.db.models.signals import pre_delete, pre_save
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding... |
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, Iterable, Optional, Tuple
from pants.core.goals.style_request import StyleRequest
from pants.core.util_rules.filter_empty_sources import (
FieldSetsWithSources,
FieldSetsWithSourcesRequest,
)
from pants.engine.c... |
from __future__ import unicode_literals
import base64
import binascii
import hashlib
import importlib
from collections import OrderedDict
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import setting_changed
from django.dispatch import receiver
from d... |
import time
from openerp.osv import fields, osv
class account_partner_reconcile_process(osv.osv_memory):
_name = 'account.partner.reconcile.process'
_description = 'Reconcilation Process partner by partner'
def _get_to_reconcile(self, cr, uid, context=None):
cr.execute("""
SELEC... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import Tkinter
import tkFileDialog
from PIL import Image
import ImageDraw
import PIL.ImageOps
__DEFAULT_VAR_NAME__ = "var1"
__IS_MARK_CENTER__ = False
__INVERT_COLOR__ = False
def main():
try:
Tkinter.Tk().withdraw() # Close the root window
in_p... |
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tables
from horizon import tabs
from horizon.utils import functions as utils
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.hypervisors \
import tables as project_tables
from o... |
'''
Build cocos2d-console into executable binary file with PyInstaller
'''
import os
import json
import subprocess
import excopy
import ConfigParser
import sys
import shutil
from argparse import ArgumentParser
def run_shell(cmd, cwd=None):
p = subprocess.Popen(cmd, shell=True, cwd=cwd)
p.wait()
if p.ret... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numbers
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
f... |
"""Test BIP68 implementation."""
import time
from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment
from test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut, FromHex, ToHex
from test_framework.script import CScript
from test_framework.test_framework import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for gluon.template
"""
import unittest
from fix_path import fix_sys_path
fix_sys_path(__file__)
import template
from template import render
class TestTemplate(unittest.TestCase):
def testRun(self):
self.assertEqual(render(content='{{for ... |
import unittest
from telemetry.unittest import progress_reporter
class TestFoo(unittest.TestCase):
# Test method doesn't have test- prefix intentionally. This is so that
# run_test script won't run this test.
def RunPassingTest(self):
pass
def RunFailingTest(self):
self.fail('expected failure')
cl... |
"""\
======================
Sky & Grass background
======================
A very simple component showing a plane with the upper half coloured light blue and the lower half green. Can be used for a background.
This component is a subclass of OpenGLComponent and therefore uses the
OpenGL display service.
Example Usa... |
#! /usr/bin/env python
"""Python interface for the 'lsprof' profiler.
Compatible with the 'profile' module.
"""
__all__ = ["run", "runctx", "help", "Profile"]
import _lsprof
# ____________________________________________________________
# Simple interface
def run(statement, filename=None, sort=-1):
"""Run s... |
"""
This module defines the Link object used in Link extractors.
For actual link extractors implementation see scrapy.linkextractors, or
its documentation in: docs/topics/link-extractors.rst
"""
import six
class Link(object):
"""Link objects represent an extracted link by the LinkExtractor."""
__slots__ = [... |
import errno
import os
import subprocess
import unittest
import logging
from airflow import jobs, models
from airflow.utils.state import State
from airflow.utils.timezone import datetime
DEV_NULL = '/dev/null'
TEST_DAG_FOLDER = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'dags')
DEFAULT_DATE = date... |
## Base Exceptions
class HTTPError(Exception):
"Base exception used by this module."
pass
class HTTPWarning(Warning):
"Base warning used by this module."
pass
class PoolError(HTTPError):
"Base exception for errors caused within a pool."
def __init__(self, pool, message):
self.pool =... |
# encoding: 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):
# Adding M2M table for field committee_meetings on 'PrivateProposal'
db.create_table('laws_privateprop... |
from django.conf.urls import include, url
from astrometry.net import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = []
from astrometry.net.views.home import home, support, api_help, explore
urlpatterns.extend([
url(r'^/?$', h... |
from django.core.urlresolvers import reverse
from django import http
from mox import IsA # noqa
from openstack_dashboard.api import cinder
from openstack_dashboard.test import helpers as test
INDEX_URL = reverse('horizon:admin:volumes:index')
class VolumeSnapshotsViewTests(test.BaseAdminViewTests):
@test.crea... |
"""
Simple config
=============
Although CherryPy uses the :mod:`Python logging module <logging>`, it does so
behind the scenes so that simple logging is simple, but complicated logging
is still possible. "Simple" logging means that you can log to the screen
(i.e. console/stdout) or to a file, and that you can easily ... |
"""
Filter rule to match persons with a particular event.
"""
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext... |
import base64
import json
import os
import uuid
from multiprocessing.managers import BaseManager, DictProxy
class ServerDictManager(BaseManager):
shared_data = {}
def _get_shared():
return ServerDictManager.shared_data
ServerDictManager.register("get_dict",
callable=_get_shared,
... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class GetContactsWithQuery(Choreography):
def __init__(self, temboo_session):
"""
C... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('statmaps', '0059_auto_20160101_0410'),
]
operations = [
migrations.AlterField(
model_name='collection',
... |
from django.contrib.auth.models import UserManager as BaseUserManager
class UserManager(BaseUserManager):
"""
Much of this is just copied out of BaseUserManager, excluding the
requirement for a username.
"""
def _create_user(self, email, password, **extra_fields):
"""
Creates and ... |
#!/usr/bin/env python
import sys
from PQTokenize import *
from keyword import *
from qt import *
class PyEdit(QTextEdit):
def __init__(self, parent=None):
QTextEdit.__init__(self, parent)
# user interface setup
self.setTextFormat(QTextEdit.PlainText)
#self.setWrapPolicy(QTextEdit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.