content stringlengths 4 20k |
|---|
# -*- coding: utf -*-
from modularodm import fields
from website.addons.base import AddonUserSettingsBase, AddonNodeSettingsBase
from . import Badge
#TODO Better way around this, No longer needed?
class BadgesNodeSettings(AddonNodeSettingsBase):
pass
class BadgesUserSettings(AddonUserSettingsBase):
revo... |
__version__ = "0.2"
from PIL import Image, ImageFile, ImagePalette, _binary
i8 = _binary.i8
i16 = _binary.i16le
i32 = _binary.i32le
o8 = _binary.o8
#
# decoder
def _accept(prefix):
return i16(prefix[4:6]) in [0xAF11, 0xAF12]
##
# Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
# method to... |
from django.conf import settings
from django.test import SimpleTestCase, override_settings
from django.utils.six.moves.urllib.parse import urljoin
from ..utils import setup
@override_settings(MEDIA_URL="/media/", STATIC_URL="/static/")
class StaticTagTests(SimpleTestCase):
libraries = {'static': 'django.template... |
import unittest
import parse_cmake.parsing
from parse_cmake.parsing import (
File, Command, Comment, BlankLine, Arg, parse, FormattingOptions)
def prettify(src):
opts = FormattingOptions()
opts.indent = ' '
return parse_cmake.parsing.prettify(src, opts)
class ParsingTestCase(unittest.TestCase):... |
from __future__ import absolute_import
import flask
from os import walk
from os.path import join
from bokeh.settings import settings
class BokehBlueprint(flask.Blueprint):
def __init__(self, *args, **kwargs):
super(BokehBlueprint, self).__init__(*args, **kwargs)
self.debugjs = None
def setu... |
"""
homeassistant.components.modbus
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Modbus component, using pymodbus (python3 branch).
Configuration:
To use the Modbus component you will need to add something like the following
to your configuration.yaml file.
#Modbus TCP
modbus:
type: tcp
host: 127.0.0.1
port: 2020
#M... |
from django.db.models.aggregates import StdDev
from django.db.utils import NotSupportedError, ProgrammingError
from django.utils.functional import cached_property
class BaseDatabaseFeatures:
gis_enabled = False
allows_group_by_pk = False
allows_group_by_selected_pks = False
empty_fetchmany_value = []
... |
from __future__ import unicode_literals
import errno
import os
import re
import socket
import sys
from datetime import datetime
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError
from django.core.servers.basehttp i... |
from sqlalchemy.schema import Column
from sqlalchemy.schema import MetaData
from sqlalchemy.schema import Table
from melange.db.sqlalchemy.migrate_repo.schema import Boolean
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
ip_addresses = Table('ip_addresses', meta, autoload=True... |
import six
from tests import FunctionalTest
http_client = six.moves.http_client
TRIGGER_0 = {
'name': 'st2.test.triggertype0',
'pack': 'dummy_pack_1',
'description': 'test trigger',
'payload_schema': {'tp1': None, 'tp2': None, 'tp3': None},
'parameters_schema': {}
}
TRIGGER_1 = {
'name': 'st2.... |
"""
exception classes and constants handling test outcomes
as well as functions creating them
"""
from __future__ import absolute_import, division, print_function
import py
import sys
class OutcomeException(BaseException):
""" OutcomeException and its subclass instances indicate and
contain info about tes... |
from pythran.tests import TestEnv
from pythran.syntax import PythranSyntaxError
class TestNamedParameters(TestEnv):
def test_call_with_named_argument(self):
self.run_test("""
def foo(a):
return a
def call_with_named_argument(n):
return foo(a=n)""", 1, call_with_named_argument=[int])
def test_... |
# stdlib
import logging
import os.path
import tempfile
log = logging.getLogger(__name__)
class PidFile(object):
""" A small helper class for pidfiles. """
@classmethod
def get_dir(cls, run_dir=None):
if run_dir is None:
my_dir = os.path.dirname(os.path.abspath(__file__))
... |
from pyspark import since
from pyspark.rdd import ignore_unicode_prefix
from pyspark.sql.column import Column, _to_seq, _to_java_column, _create_column_from_literal
from pyspark.sql.dataframe import DataFrame
from pyspark.sql.types import *
__all__ = ["GroupedData"]
def dfapi(f):
def _api(self):
name = f... |
# Get mixpanel event data via export API
# Useful for debugging Mixpanel data weirdness
targetLevels = ['dungeons-of-kithgard', 'the-raised-sword', 'endangered-burl']
targetLevels = ['dungeons-of-kithgard']
eventFunnel = ['Started Level', 'Saw Victory']
# eventFunnel = ['Saw Victory']
# eventFunnel = ['Started Level']... |
# -*- coding: utf-8 -*-
import codecs
import io
import logging
import os
import re
import shutil
import sys
import tempfile
import unittest
from lib2to3 import main
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
PY2_TEST_MODULE = os.path.join(TEST_DATA_DIR, "py2_test_grammar.py")
class TestMain(un... |
import subprocess
import datetime
# this script is only of historical interest: it's the script that was used to
# bootstrap the dataset
def daterange(start, end):
for n in range(int((end - start).days)):
yield start + datetime.timedelta(n)
start_date = datetime.date(2017, 3, 26)
end_date = datetime.date(2017,... |
"""Affine modules.
"""
import numpy as np
import tensorflow as tf
from collections import OrderedDict
from weakly_supervised_control.disentanglement.tensorsketch import utils as tsu
from weakly_supervised_control.disentanglement.tensorsketch.modules.base import build_with_name_scope
from weakly_supervised_control.dis... |
import os.path
import sys
import shutil
from in_file import InFile
import name_macros
import name_utilities
import template_expander
def case_insensitive_matching(name):
return (name == ('HTMLEvents')
or name == 'Event'
or name == 'Events'
or name.startswith('UIEvent'))
class... |
""" Views for a student's profile information. """
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.http import Http404
from django.views.decorators.http import requi... |
import clr
clr.AddReference("System.Xml")
from System.IO import StringReader, TextReader
from System.Xml import XmlReader, XmlNodeType
# node types/categories
START = XmlNodeType.Element
DATA_TEXT = XmlNodeType.Text
DATA_CDATA = XmlNodeType.CDATA
DATA_SPACE = XmlNodeType.Whitespace
END = XmlNodeType.EndElement
def _... |
import unittest
from datetime import datetime, timedelta
from fs.memoryfs import MemoryFS
from mock import Mock, patch
import itertools
from xblock.runtime import KvsFieldData, DictKeyValueStore
import xmodule.course_module
from xmodule.modulestore.xml import ImportSystem, XMLModuleStore
from opaque_keys.edx.locati... |
"""End snippets defaults if they were untouched by the user.
We want to do this to mask out protobuf-defined defaults which will be in effect
in that case. A common case is a URL that points to a Google server.
Another one is that authentication is on by default, which is undesirable.
We do allow users to see and set ... |
from tempest.api.volume import base
from tempest.common import tempest_fixtures as fixtures
from tempest.common import waiters
from tempest.lib.common.utils import data_utils
from tempest.lib import decorators
QUOTA_KEYS = ['gigabytes', 'snapshots', 'volumes', 'backups']
QUOTA_USAGE_KEYS = ['reserved', 'limit', 'in_us... |
"""This module implements a MATLAB-like interface to the ASTRA Toolbox.
Note that all functions are called with a :class:`string` as the first
argument, specifying the operation to perform. This un-pythonic way
is used to make transitioning from MATLAB code to Python code easier, as
the MATLAB interface uses the same ... |
from django.db import models
class MyModel(models.Model):
"""
Doesn't include relationships or files for now
"""
biginteger = models.BigIntegerField()
boolean = models.BooleanField(default=False)
char = models.CharField(max_length=100)
csi = models.CommaSeparatedIntegerField(max_length=100... |
"""Support for N26 bank account sensors."""
from homeassistant.components.sensor import SensorEntity
from . import DEFAULT_SCAN_INTERVAL, DOMAIN, timestamp_ms_to_date
from .const import DATA
SCAN_INTERVAL = DEFAULT_SCAN_INTERVAL
ATTR_IBAN = "account"
ATTR_USABLE_BALANCE = "usable_balance"
ATTR_BANK_BALANCE = "bank_b... |
import ee
from .gee import get_info
class Aoi:
_table_by_data_set = {
'LANDSAT': {
'table_id': 'users/wiell/SepalResources/landsatSceneAreas',
'id_column': 'name',
'coordinates': lambda sceneArea: sceneArea[0]['coordinates'][0]
},
'SENTINEL_2': {
... |
"""
This file is part of flatlib - (C) FlatAngle
Author: João Ventura (<EMAIL>)
This module provides useful functions for handling
planetary times.
The most import element is the HourTable class
which handles all queries to the planetary rulers
and hour rulers, including th... |
"""Tests for stateless random-number generation ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.compiler.tests import xla_test
from tensorflow.python.compiler.xla import xla
from tensorflow.python.eager import def... |
# -*- coding: utf-8 -*-
from ..internal.Addon import Addon
class EventMapper(Addon):
__name__ = "EventMapper"
__type__ = "hook"
__version__ = "0.02"
__status__ = "testing"
__config__ = [("activated", "bool", "Activated", True)]
__description__ = """Map old events to new events"""
__lice... |
from __future__ import print_function, division
from builtins import range
import gym
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from gym import wrappers
from datetime import datetime
from sklearn.pipeline import FeatureUnion
from sklearn.preprocessing import StandardScaler
from sklearn.ker... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
try:
from pyVmomi import vim
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
fro... |
import sys
import threading
import warnings
from collections import Counter, OrderedDict, defaultdict
from functools import partial
from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
from django.utils import lru_cache
from .config import AppConfig
class Apps(object):
"""
A registry... |
"""distutils.command.sdist
Implements the Distutils 'sdist' command (create a source distribution)."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: sdist.py 68968 2009-01-26 17:20:15Z tarek.ziade $"
import os, string
import sys
from types import *
from glob import glob
from distutil... |
{
'name': 'Thailand - Accounting',
'version': '1.0',
'category': 'Localization/Account Charts',
'description': """
Chart of Accounts for Thailand.
===============================
Thai accounting chart and localization.
""",
'author': 'Almacom',
'website': 'http://almacom.co.th/',
'depen... |
import unittest
from alot import account
from . import utilities
class _AccountTestClass(account.Account):
"""Implements stubs for ABC methods."""
def send_mail(self, mail):
pass
class TestAccount(unittest.TestCase):
"""Tests for the Account class."""
def test_get_address(self):
"... |
import pickle
import numpy as np
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_raises_regexp
from sklearn.utils.testing import assert_true
from sklearn.utils.testing im... |
"""
Functions for working with "safe strings": strings that can be displayed safely
without further escaping in HTML. Marking something as a "safe string" means
that the producer of the string has already turned characters that should not
be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
"""
f... |
from telemetry import benchmark
from telemetry.page import page
from telemetry.page import page_test
from telemetry.story import story_set as story_set_module
from webgl_conformance import conformance_harness_script
from webgl_conformance import conformance_path
from webgl_conformance import WebglConformanceValidator
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.contrib.distributions.python.ops import operator_pd_cholesky
distributions = tf.contrib.distributions
def softplus(x):
return np.log(1 + np.exp(x... |
"""Stock Terminal page"""
import time
import logging
from . import ui, td, keyboard, usestock, stocklines, user, tillconfig
from .user import load_user
from .models import StockLine, StockAnnotation, StockItem
from sqlalchemy.sql.expression import tuple_, func, null
from sqlalchemy.sql import select, not_
from sqlalch... |
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, flt
from frappe import msgprint, _, throw
from frappe.model.mapper import get_mapped_doc
from erpnext.controllers.buying_controller import BuyingController
form_grid_templates = {
"po_details": "templates/form_grid/item_grid.html"
}
... |
import sys
try:
from sklearn import datasets
except:
print("scikit-learn is required to run this example.")
exit(1)
try:
from openann import *
except:
print("OpenANN Python bindings are not installed!")
exit(1)
#NOTE: LABELS ARE 0-INDEXED, UNLIKE WITH LOGISTIC REGRESSION
HOG_TRAINING_DATA = 'd... |
"""
Tests For Capacity Weigher.
"""
import mock
from oslo.config import cfg
from cinder import context
from cinder.openstack.common.scheduler.weights import HostWeightHandler
from cinder.scheduler.weights.capacity import CapacityWeigher
from cinder import test
from cinder.tests.scheduler import fakes
from cinder.volu... |
# -*- coding: utf-8 -*-
from numpy import log10, linspace, mean, sqrt
from SciDataTool import Data1D, DataTime
def compute_level(self, nb_points=[], start=[], stop=[]):
"""Overall Sound Pressure Level calculation from the time signal
The SPL can be computed according to a specified number of points or
d... |
from __future__ import unicode_literals
from django.conf.urls import patterns, url, include
from roundware.api1 import views
import logging
logger = logging.getLogger(__name__)
urlpatterns = patterns('',
# V1 API
url(r'^$', 'api1.views.operations'),
url(r'^auth/', include('rest_framework.urls',
... |
#! /usr/bin/python
def default(context):
minifyfiles(context)
def minifyfiles(context):
src = context.Node('jspdf.js')
dst = src.parent + 'dist/' + src.name - '.js' + '.source.js'
dst.text = src.text.replace(
"${buildDate}", timeUTC()
).replace(
"${commitID}", getCom... |
"""
Verifies that xcode-style GCC_... settings are handled properly.
"""
import TestGyp
import os
import subprocess
import sys
def IgnoreOutput(string, expected_string):
return True
def CompilerVersion(compiler):
stdout = subprocess.check_output([compiler, '-v'], stderr=subprocess.STDOUT)
return stdout.rstrip... |
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class MyFileField(models.FileField):
pass
@python_2_unicode_compatible
class Member(models.Model):
name = models.CharField(max_lengt... |
__revision__ = "$Id$"
## Description: function Send_SRV_Mail
## This function sends an email confirming the revision
## has been carried on with success
## Author: T.Baron
## PARAMETERS: addressesSRV: list of addresses to send this email to.
## c... |
# -*- coding: utf-8 -*-
"""
pygments.styles.autumn
~~~~~~~~~~~~~~~~~~~~~~
Tomorrow Night theme for ipython qtconsole (invoke with
ipython qtconsole --style=tomorrownight)
See https://github.com/chriskempson/tomorrow-theme for theme info
:copyright: Copyright 2012 André Risnes, <EMAIL>
:l... |
from openerp.osv import osv
class res_partner_bank(osv.osv):
_inherit = 'res.partner.bank'
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
if not args:
args = []
ids = []
if name:
ids = self.search(cr, user, [('acc_nu... |
"""
This page is in the table of contents.
Gcode step is an export plugin to convert gcode from float position to number of steps.
An export plugin is a script in the export_plugins folder which has the getOutput function, the globalIsReplaceable variable and if it's output is not replaceable, the writeOutput function... |
from sqlalchemy import ForeignKey
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import column_property
from sqlalchemy.sql import exists
from geonature.core.gn_commons.models import TMedias
from utils_flask_sqla.serializers import serializable
from utils_flask_sqla_geo.serializers import geoseria... |
"""
Unit tests for yaml.
"""
import os,tempfile
from nose import SkipTest
from nose.tools import assert_equal
import networkx as nx
from networkx.testing import assert_edges_equal, assert_nodes_equal
class TestYaml(object):
@classmethod
def setupClass(cls):
global yaml
try:
im... |
'''
SASSIE: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
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 3 of the License, or
(at your option) any later version.
... |
""" Objects and functions related to generating CSV reports """
from decimal import Decimal
import unicodecsv
from django.utils.translation import ugettext as _
from courseware.courses import get_course_by_id
from course_modes.models import CourseMode
from shoppingcart.models import CertificateItem, OrderItem
from s... |
from zope.interface import implementer, implements
from twisted.internet import protocol
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.internet.abstract import _ConsumerMixin
import collections
import struct
import sys
import warnings
from lumberjack.client.encoder import Encoder
cla... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
TinInterpolation.py
---------------------
Date : October 2016
Copyright : (C) 2016 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
********... |
from unittest import TestCase
from harpia.model.connectionmodel import ConnectionModel
from harpia.GUI.diagram import Diagram
class TestConnectionModel(TestCase):
def setUp(self):
"""Do the test basic setup."""
diagram = Diagram()
self.connection_model = ConnectionModel()
# --------... |
#!/usr/local/bin/python
# Translated from walkCow.tcl
import vtk
def walk_cow(file_name, figure):
figure = abs(figure)
if figure > 2:
figure = 0
colors = vtk.vtkNamedColors()
# Set the background color.
colors.SetColor("BkgColor1", [60, 93, 144, 255])
colors.SetColor("BkgColor2", [2... |
import argparse
import asyncio
import logging
import sys
import jinja2
from trafaret_config import commandline
import aiohttp_jinja2
from aiohttp import web
from aiohttpdemo_polls.db import close_pg, init_pg
from aiohttpdemo_polls.middlewares import setup_middlewares
from aiohttpdemo_polls.routes import setup_route... |
# encoding: UTF-8
import shelve
from eventEngine import *
from pymongo import Connection
from pymongo.errors import *
from strategyEngine import *
########################################################################
class LimitOrder(object):
"""限价单对象"""
#-----------------------------------------------... |
from .constants import eStart, eError, eItsMe
HZ_cls = (
1,0,0,0,0,0,0,0, # 00 - 07
0,0,0,0,0,0,0,0, # 08 - 0f
0,0,0,0,0,0,0,0, # 10 - 17
0,0,0,1,0,0,0,0, # 18 - 1f
0,0,0,0,0,0,0,0, # 20 - 27
0,0,0,0,0,0,0,0, # 28 - 2f
0,0,0,0,0,0,0,0, # 30 - 37
0,0,0,0,0,0,0,0, # 38 - 3f
0,0,0,0,0,0,0,0, # 40 - 47
0,0,0,0,0,... |
# -*- coding: utf-8 -*-
"""Multi-electrode arrays."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import os
import os.path as op
import itertools
import numpy as np
from ..utils._types imp... |
import sys, os, re
sys.path.append("lib")
import utils
import numpy as np
import sklearn
import iso8601
import datetime
print("Imports loaded...")
# Load and check the size of our training data. May take a minute.
print("Original JSON file size: {:,} Bytes".format(os.path.getsize("data/simple_flight_delay_features.js... |
STDOUT = -11
STDERR = -12
try:
import ctypes
from ctypes import LibraryLoader
windll = LibraryLoader(ctypes.WinDLL)
from ctypes import wintypes
except (AttributeError, ImportError):
windll = None
SetConsoleTextAttribute = lambda *_: None
winapi_test = lambda *_: None
else:
from ctypes i... |
from __future__ import (absolute_import, division)
__metaclass__ = type
import json
import pytest
EMPTY_INVOCATION = {u'module_args': {}}
class TestAnsibleModuleExitJson:
"""
Test that various means of calling exitJson and FailJson return the messages they've been given
"""
DATA = (
({}, {... |
"""
Save and load Small OBjects to and from files, using various formats.
Maintainer: Moshe Zadka
"""
import os, sys
try:
import cPickle as pickle
except ImportError:
import pickle
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from twisted.python import log, runtime
from twiste... |
"""Utilities for doing coverage analysis on the RPC interface.
Provides a way to track which RPC commands are exercised during
testing.
"""
import os
REFERENCE_FILENAME = 'rpc_interface.txt'
class AuthServiceProxyWrapper(object):
"""
An object that wraps AuthServiceProxy to record specific RPC calls.
... |
import textwrap
from io import StringIO
from test.test_json import PyTest, CTest
class TestIndent:
def test_indent(self):
h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
{'nifty': 87}, {'field': 'yes', 'morefield': False} ]
expect = textwrap.dedent("""\
... |
from threading import Lock
from bitcoin import Hash, hash_encode
from transaction import Transaction
from util import print_error, print_msg
class WalletSynchronizer():
'''The synchronizer keeps the wallet up-to-date with its set of
addresses and their transactions. It subscribes over the network
to wal... |
"""This module provides access to the garbage collector for reference cycles.
enable() -- Enable automatic garbage collection.
disable() -- Disable automatic garbage collection.
isenabled() -- Returns true if automatic collection is enabled.
collect() -- Do a full collection right now.
get_count() -- Return the curren... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ast
from collections import MutableMapping
from six import iteritems, string_types
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.parsing.splitter import parse_kv
from ansible.utils... |
#! /usr/bin/env python3
"""
Gramps - a GTK+/GNOME based genealogy program
Copyright (c) 2016 Gramps Development Team
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, ... |
import glob
import os
import re
import sys
import subprocess
# TODO(timurrrr): we may use it on POSIX too to avoid code duplication once we
# support layout_tests, remove Dr. Memory specific code and verify it works
# on a "clean" Mac.
testcase_name = None
for arg in sys.argv:
m = re.match("\-\-gtest_filter=(.*)", ... |
from sqlalchemy import String, Column, MetaData, Table, select
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
""" Remove availability_zone column from services model and replace with
aggregate based zone."""
def upgrade(migrate_engine):
meta = MetaData()
meta.bind =... |
"""Create or Update a codelist and optionally link it to organisations.
Usage:
python manage.py create_organisation_codelist <slug> <json-path>_[<org-ids>]
"""
import json
import sys
from django.core.management.base import BaseCommand
from akvo.rsr.models import OrganisationCodelist, Organisation
class Com... |
"""PyZMQ and 0MQ version functions."""
# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.
from zmq.backend import zmq_version_info
VERSION_MAJOR = 15
VERSION_MINOR = 2
VERSION_PATCH = 0
VERSION_EXTRA = ""
__version__ = '%i.%i.%i' % (VERSION_MAJOR, VERSION_MINOR, VERSION_PAT... |
"""
Tests For PickledScheduler.
"""
import datetime
import StringIO
from oslo_serialization import jsonutils
from nova.scheduler import scheduler_options
from nova import test
class FakeSchedulerOptions(scheduler_options.SchedulerOptions):
def __init__(self, last_checked, now, file_old, file_now, data, filedat... |
"""Provides management command calling info to tracking context."""
from django.core.management.base import BaseCommand
from eventtracking import tracker
class TrackedCommand(BaseCommand):
"""
Provides management command calling info to tracking context.
Information provided to context includes the fol... |
from matplotlib.transforms import Bbox, TransformedBbox, \
blended_transform_factory
from mpl_toolkits.axes_grid1.inset_locator import BboxPatch, BboxConnector,\
BboxConnectorPatch
def connect_bbox(bbox1, bbox2,
loc1a, loc2a, loc1b, loc2b,
prop_lines, prop_patches=None):
... |
"""Unittests for ofprotoops.py.
"""
import struct
import unittest2
import weakref
import twisted.internet.address
import twisted.internet.error
import twisted.python.failure
from openfaucet import ofproto
from openfaucet import ofprotoops
from openfaucet import mock_ofproto
from openfaucet import mock_twisted
from o... |
import h2.exceptions
import time
import enum
from mitmproxy import connections # noqa
from mitmproxy import exceptions
from mitmproxy import http
from mitmproxy import flow
from mitmproxy.proxy.protocol import base
from mitmproxy.proxy.protocol.websocket import WebSocketLayer
from mitmproxy.net import websockets
cl... |
# -*- coding: utf-8 -*-
"""
werkzeug.testsuite.iterio
~~~~~~~~~~~~~~~~~~~~~~~~~
Tests the iterio object.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import unittest
from functools import partial
from werkzeug.testsuite import WerkzeugTestCase
from werk... |
"""Test alarm notifier."""
from ceilometer.alarm import notifier
class TestAlarmNotifier(notifier.AlarmNotifier):
"Test alarm notifier."""
def __init__(self):
self.notifications = []
def notify(self, action, alarm_id, alarm_name, severity,
previous, current, reason, reason_data):... |
"""a pyqt test app that embeds javascript using QtScript,
defines qt properties and slots in py, and exposes them to js"""
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtScript import QScriptEngine, QScriptValue
from PyQt4.QtCore import QObject, pyqtSignature, pyqtProperty, QVariant, QTimer
ps1 = ">>> "
ps2... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.nxos import nxos_vxlan_vtep
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosVxlanVtepVniModule(TestNxosMod... |
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'
DATETIME_FORMAT = 'j. F Y. H:i'
YEAR_MONTH_FORMAT = 'F Y.'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = ... |
import product
import stock_landed_costs
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
# mode: run
# ticket: 5
class CyTest(object):
"""
>>> cy = CyTest()
>>> '_CyTest__private' in dir(cy)
True
>>> cy._CyTest__private()
8
>>> '__private' in dir(cy)
False
>>> '_CyTest__x' in dir(cy)
True
>>> '__x' in dir(cy)
False
"""
__x = 1
def __private(self... |
from django.test import TestCase
from django.urls import reverse
from wagtail.core.models import Page
from wagtail.tests.utils import WagtailTestUtils
class TestLoginView(TestCase, WagtailTestUtils):
fixtures = ['test.json']
def setUp(self):
self.user = self.create_test_user()
self.events_in... |
'''
Created on Aug 24, 2012
@author: u5682
'''
from GridTask import GridTask
from Host import Host
from FakeHost import FakeHost
from Pilot import Pilot
import ExecutionManager
from Infrastructure import Infrastructure
from PilotResource import PilotResource
from InformationManager import obtainGWResources
import su... |
from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ValidationError
from zerver.lib.actions import do_change_is_admin
from zerver.m... |
#-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame 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 3 of the License, or
(at your option) any later version.
OpenSesame is distri... |
from __future__ import unicode_literals
import json
import frappe
from frappe import _
from frappe.utils import flt
from frappe.utils.user import is_website_user
def get_list_context(context=None):
return {
"global_number_format": frappe.db.get_default("number_format") or "#,###.##",
"currency": frappe.db.get_def... |
from django.utils.encoding import smart_str, smart_unicode
def ssn_check_digit(value):
"Calculate Italian social security number check digit."
ssn_even_chars = {
'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,
'9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': ... |
"""
=============================
Straight line Hough transform
=============================
The Hough transform in its simplest form is a `method to detect straight lines
<http://en.wikipedia.org/wiki/Hough_transform>`__.
In the following example, we construct an image with a line intersection. We
then use the Houg... |
from m5.SimObject import SimObject
from m5.params import *
from m5.proxy import *
from Device import DmaDevice
from PciHost import PciHost
class PciDevice(DmaDevice):
type = 'PciDevice'
cxx_class = 'PciDevice'
cxx_header = "dev/pci/device.hh"
abstract = True
host = Param.PciHost(Parent.any, "PCI h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.