content stringlengths 4 20k |
|---|
import json
import sys
import traceback
from django.test import TestCase
from django.core.urlresolvers import reverse
from .models import Service
class ServicesTests(TestCase):
"""Tests geonode.services app/module
"""
fixtures = ['initial_data.json', 'bobby.json', 'people_data.json']
def setUp(sel... |
"""OAuth2Server errors."""
class OAuth2ServerError(Exception):
"""Base class for errors in oauth2server module."""
class ScopeDoesNotExists(OAuth2ServerError):
"""Scope is not registered it scopes registry."""
def __init__(self, scope, *args, **kwargs):
"""Initialize exception by storing inva... |
"""Makes sure files have the right permissions.
Some developers have broken SCM configurations that flip the executable
permission on for no good reason. Unix developers who run ls --color will then
see .cc files in green and get confused.
- For file extensions that must be executable, add it to EXECUTABLE_EXTENSIONS... |
from django.test import SimpleTestCase
from ..utils import setup
class IfEqualTagTests(SimpleTestCase):
@setup({'ifequal01': '{% ifequal a b %}yes{% endifequal %}'})
def test_ifequal01(self):
output = self.engine.render_to_string('ifequal01', {'a': 1, 'b': 2})
self.assertEqual(output, '')
... |
r"""Evaluation executable for detection models.
This executable is used to evaluate DetectionModels. There are two ways of
configuring the eval job.
1) A single pipeline_pb2.TrainEvalPipelineConfig file maybe specified instead.
In this mode, the --eval_training_data flag may be given to force the pipeline
to evaluate... |
import sys
import re
if sys.version_info[:2] >= (3, 2):
from configparser import Error
from configparser import MissingSectionHeaderError
from configparser import ConfigParser as _BaseParser
elif sys.version_info[0] >= 3:
from configparser import Error
from configparser import MissingSectionHeaderE... |
import gcc
import gccutils
import sys
# Where our output goes.
output_file = None
# Cleanup functions require special treatment, because they take a
# function argument, but in theory the function must be nothrow.
cleanup_functions = {
'make_cleanup': 1,
'make_cleanup_dtor': 1,
'make_final_cleanup': 1,
... |
import sys
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
... |
"""Singleton file-related data structures utilized by the Seqparse module."""
# Standard Libraries
import os
from functools import total_ordering
__all__ = ("File", )
###############################################################################
# Class: File
@total_ordering
class File(object):
"""
Simple... |
from datetime import datetime
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.addons.product.tests import common
class TestCreatePicking(common.TestProductCommon):
def setUp(self):
super(TestCreatePicking, self).setUp()
self.partner_id = self.env.ref('base.res_partner_1')
... |
"""
===================================================================
Support Vector Regression (SVR) using linear and non-linear kernels
===================================================================
Toy example of 1D regression using linear, polynomial and RBF kernels.
"""
print(__doc__)
import numpy as np
... |
# tk common message boxes
#
# this module provides an interface to the native message boxes
# available in Tk 4.2 and newer.
#
# written by Fredrik Lundh, May 1997
#
#
# options (all have default values):
#
# - default: which button to make default (one of the reply codes)
#
# - icon: which icon to display (see below)... |
import argparse
from os.path import basename
from tools.arm_pack_manager import Cache
from os.path import basename, join, dirname, exists
from os import makedirs
from itertools import takewhile
from fuzzywuzzy import process
from tools.arm_pack_manager import Cache
parser = argparse.ArgumentParser(description='A Handy... |
#!/usr/bin/env python
import argparse
import sys
import time
import traceback
from utils import os1_utils, setup_utils, config_utils
# Setup the CLI
description = 'Deploy a Pulp environment; this can be used in conjunction with the run-integrations-tests.py script'
parser = argparse.ArgumentParser(description=descr... |
"""
tests for the models
"""
from datetime import datetime, timedelta
from django.utils.timezone import UTC
from mock import patch
from nose.plugins.attrib import attr
from student.roles import CourseCcxCoachRole
from student.tests.factories import (
AdminFactory,
)
from util.tests.test_date_utils import fake_ugett... |
# -*- coding: utf-8 -*-
"""Defines fixtures available to all tests."""
import pytest
from webtest import TestApp
from flaskiwsapp.app import create_app
from flaskiwsapp.database import db as _db
from .factories import UserFactory
from flaskiwsapp.settings.testConfig import TestConfig
from flaskiwsapp.snippets.helper... |
from __future__ import unicode_literals, division, absolute_import
import os
from tests import FlexGetBase
class TestMigrate(FlexGetBase):
__yaml__ = """
tasks:
test:
mock:
- {title: 'foobar'}
accept_all: yes
"""
def setup(self):
import log... |
from __future__ import unicode_literals
from sys import version_info
import flask_login
from flask_login import login_required, current_user, logout_user
from flask import flash
from wtforms import (
Form, PasswordField, StringField)
from wtforms.validators import InputRequired
from flask import url_for, redirec... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsSpatialiteProvider
.. 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.
... |
"""
Support for sending data to Logentries webhook endpoint.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/logentries/
"""
import json
import logging
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from h... |
import threading
from django.template import RequestContext
from util.request import safe_get_host
REQUEST_CONTEXT = threading.local()
class MakoMiddleware(object):
def process_request(self, request):
REQUEST_CONTEXT.context = RequestContext(request)
REQUEST_CONTEXT.context['is_secure'] = reques... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'jakob'
import ConfigParser
from StringIO import StringIO
import os
from zope.interface import implements
from IMailOption import IMailOption
class ConfPaser(object):
implements(IMailOption)
__pathToConfig = None
__config = None
__subj... |
#!/usr/bin/env python
__author__ = "stefan"
import configparser
import os
def initParser(config_path):
parser = configparser.ConfigParser()
parser.read(config_path)
return parser
def parseGlobal(parser, base):
if 'GLOBAL' not in parser:
raise KeyError('Invalid config ... No GLOBAL section.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
# pylint: disable=no-self-use
"""
csv2ofx.ofx
~~~~~~~~~~~
Provides methods for generating OFX content
Examples:
literal blocks::
python example_google.py
Attributes:
ENCODING (str): Default file encoding.
"""
from __future__ i... |
"""
DataSource is a wrapper for the OGR Data Source object, which provides
an interface for reading vector geometry data from many different file
formats (including ESRI shapefiles).
When instantiating a DataSource object, use the filename of a
GDAL-supported data source. For example, a SHP file or a
TIGER/Line... |
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ImportError:
HAS_AVI = False
def main():
argument_... |
"""
Handlers for user-related pages: login, logout, signup, verify
"""
from google.appengine.api import users
from webapp2_extras.auth import *
from requestmodel import *
from webapp2_extras.appengine.auth.models import UserToken
from webapp2_extras.appengine.auth.models import User
from google.appengine.ext import nd... |
"""
===============================
Using geometric transformations
===============================
In this example, we will see how to use geometric transformations in the context
of image processing.
"""
from __future__ import print_function
import math
import numpy as np
import matplotlib.pyplot as plt
from skim... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
class ProductBundle(Document):
def autoname(self):
self.name = self.new_item_code
def validate(self):
self.validate_main_item()
self.validate_child_items()
from erpnext.utilities.transacti... |
# -*- coding: utf-8 -*-
"""Parallel workflow execution via SGE
"""
from __future__ import print_function, division, unicode_literals, absolute_import
from builtins import object
import os
import pwd
import re
import subprocess
import time
import xml.dom.minidom
import random
from ...interfaces.base import CommandL... |
"Database cache backend."
import base64
import time
from datetime import datetime
try:
from django.utils.six.moves import cPickle as pickle
except ImportError:
import pickle
from django.conf import settings
from django.core.cache.backends.base import BaseCache
from django.db import connections, router, transa... |
#!/usr/bin/python
import os, re, glob, sys
if len(sys.argv) < 5:
print 'Merge partitioned matrix data Si.txt generated by the Petuum Sparse Coding application'
print ''
print 'Usage: python %s <data-dirname> <data-format> <dictionary-size> <n> [<output-dirname>]' % sys.argv[0]
print ''
print 'Outpu... |
from novaclient.v1_1 import services
from novaclient.tests.v1_1 import fakes
from novaclient.tests import utils
cs = fakes.FakeClient()
class ServicesTest(utils.TestCase):
def test_list_services(self):
svs = cs.services.list()
cs.assert_called('GET', '/os-services')
[self.assertTrue(isi... |
import numpy as np
import theano
import theano.tensor as T
class LogisticRegression(object):
def __init__(self, input_, n_in, n_out):
self.W = theano.shared(
value=np.zeros(
(n_in, n_out),
dtype=theano.config.floatX
),
name='W',
... |
"""
Tests for stuff in django.utils.datastructures.
"""
import copy
import pickle
import warnings
from django.test import SimpleTestCase
from django.utils.datastructures import (DictWrapper, ImmutableList,
MultiValueDict, MultiValueDictKeyError, MergeDict, SortedDict)
from django.utils import six
class SortedDi... |
"""
This file contains celery tasks for ccxcon
"""
from celery.task import task # pylint: disable=no-name-in-module, import-error
from celery.utils.log import get_task_logger # pylint: disable=no-name-in-module, import-error
from requests.exceptions import (
ConnectionError,
HTTPError,
RequestException,
... |
from gi.repository import Gio
from gi.repository import GObject
from gi.repository import SugarExt
from sugar3 import dispatch
_PLAYBACK = 0
_CAPTURE = 1
_SAVE_TIMEOUT = 500
class PlaybackSound(object):
_volume = SugarExt.VolumeAlsa.new(_PLAYBACK)
muted_changed = dispatch.Signal()
volume_changed = d... |
from sympy import atan2, factor, Float, I, Matrix, N, oo, pi, sqrt, symbols
from sympy.physics.optics import (BeamParameter, CurvedMirror,
CurvedRefraction, FlatMirror, FlatRefraction, FreeSpace, GeometricRay,
RayTransferMatrix, ThinLens, conjugate_gauss_beams,
gaussian_conj, geometric_conj_ab, geometric_conj_af... |
import openerp
from openerp.osv import osv, fields
from openerp.tools.translate import _
class base_module_upgrade(osv.osv_memory):
""" Module Upgrade """
_name = "base.module.upgrade"
_description = "Module Upgrade"
_columns = {
'module_info': fields.text('Modules to Update',readonly=True),
... |
import page_sets
from profile_creators import fast_navigation_profile_extender
class SmallProfileExtender(
fast_navigation_profile_extender.FastNavigationProfileExtender):
"""Creates a small profile by performing 25 navigations."""
def __init__(self, finder_options):
# Use exactly 5 tabs to generate the... |
from os.path import join
def configuration(parent_package='',top_path=None):
from scipy._build_utils.system_info import get_info
from numpy.distutils.misc_util import Configuration
from scipy._build_utils import (get_g77_abi_wrappers, uses_blas64,
blas_ilp64_pre_build_h... |
"""
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import os
import re
import time # Needed for Windows
import... |
from functools import wraps
from typing import Any, Callable, Coroutine, Generator, TypeVar
from typing_extensions import AsyncContextManager
from .cursor import Cursor
_T = TypeVar("_T")
class Result(AsyncContextManager[_T], Coroutine[Any, Any, _T]):
__slots__ = ("_coro", "_obj")
def __init__(self, coro:... |
from django.template.defaulttags import token_kwargs
from django import template
from allauth.socialaccount import providers
from allauth.utils import get_request_param
register = template.Library()
class ProviderLoginURLNode(template.Node):
def __init__(self, provider_id, params):
self.provider_id_var ... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'core'}
import re
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network_common import ComplexList
from ansible.module_utils.eos import load_config, get_config... |
"""The Gumbel distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import op... |
import string
import warnings
import collections
import numpy as np
__all__ = [
'InputVariable',
]
_SPECIAL_DATASET_INDICES = (':', '+', '?')
_DATASET_INDICES = ''.join(list(string.digits) + list(_SPECIAL_DATASET_INDICES))
_INTERNAL_DATASET_INDICES = ('__s', '__i', '__a')
_SPECIAL_CONVERSION = zip(_INTERNAL_D... |
from modules.base_module import BaseModule
class FcqCardModule(BaseModule):
fcq_ids = []
def render(self, fcq_ids, color):
self.fcq_ids = fcq_ids
self.fcq_ids.reverse()
chunks = [self.fcq_ids[x:x + 6]
for x in range(0, len(self.fcq_ids), 6)]
return self.rende... |
from gnuradio import gr
import fec_swig as fec
from bitflip import read_bitlist
import weakref
class extended_async_encoder(gr.hier_block2):
def __init__(self, encoder_obj_list, puncpat=None):
gr.hier_block2.__init__(self, "extended_async_encoder",
gr.io_signature(0, 0, 0),
... |
"""Defines a multi-dimensional array and useful procedures for Numerical computation.
Functions
- array - NumPy Array construction
- zeros - Return an array of all zeros
- empty - Return an unitialized array
- shape - Return s... |
import re
from mock import patch
from mock import sentinel
from django.contrib.auth.models import User
from django.contrib.sessions.middleware import SessionMiddleware
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from eventtracking imp... |
# test memoryview
# test reading from bytes
b = b'1234'
m = memoryview(b)
print(len(m))
print(m[0], m[1], m[-1])
print(list(m))
# test writing to bytes
try:
m[0] = 1
except TypeError:
print("TypeError")
# test writing to bytearray
b = bytearray(b)
m = memoryview(b)
m[0] = 1
print(b)
print(list(m))
# test sl... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsServer plugins and filters.
From build dir, run: ctest -R PyQgsServerPlugins -V
.. 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 ve... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# CSS Minification Script
# http://www.siafoo.net/snippet/16
# released in public domain
#
from __future__ import division
import sys
import getopt
import re
import string
def compress(input):
output = ''
while True:
open_c = input.find('/*')
... |
"""Services for exploration-related statistics."""
from core.domain import exp_domain
from core.domain import exp_services
from core.domain import stats_domain
from core.domain import stats_jobs_continuous
from core.platform import models
(stats_models,) = models.Registry.import_models([models.NAMES.statistics])
IMP... |
import unittest
import IECore
import IECoreScene
class LightTest( unittest.TestCase ) :
def test( self ) :
s = IECoreScene.Light()
self.assertEqual( s.name, "distantlight" )
self.assert_( len(s.handle) > 0 )
self.assertEqual( len( s.parameters ), 0 )
self.assertEqual( s.parameters.typeName(), "CompoundDa... |
# -*- coding: utf-8 -*-
'''Public section, including homepage and signup.'''
from flask import (Blueprint, request, render_template, flash, url_for,
redirect, session)
from flask.ext.login import login_user, login_required, logout_user
from sqlalchemy import desc
from blogaggregator.extensions impo... |
import os
import subprocess
import sys
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, lik... |
"""
Test courseware search
"""
import os
import json
from nose.plugins.attrib import attr
from ..helpers import UniqueCourseTest, remove_file
from ...pages.common.logout import LogoutPage
from ...pages.studio.utils import add_html_component, click_css, type_in_codemirror
from ...pages.studio.auto_auth import AutoAuth... |
"""
pkgdata is a simple, extensible way for a package to acquire data file
resources.
The getResource function is equivalent to the standard idioms, such as
the following minimal implementation:
import sys, os
def getResource(identifier, pkgname=__name__):
pkgpath = os.path.dirname(sys.modules[p... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.vyos.vyos import get_config, load_config
from ansible.module_utils.network.vyos.vyos import vy... |
"""Generic (shallow and deep) copying operations.
Interface summary:
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
For module specific errors, copy.Error is raised.
The difference between shallow and deep copying is only relev... |
# -*- coding: utf-8 -*-
import random
import re
import time
import urlparse, urllib,urllib2,cookielib
from base64 import b64encode
import xbmc
import xbmcgui,xbmcaddon,os
__scriptID__ = 'script.module.liveresolver'
__addon__ = xbmcaddon.Addon(__scriptID__)
class cInputWindow(xbmcgui.WindowDialog):
def __init__(s... |
import os
from django import forms, http
from django.conf import settings
from django.contrib.formtools import preview, wizard, utils
from django.test import TestCase
from django.utils import unittest
success_string = "Done was called!"
class TestFormPreview(preview.FormPreview):
def get_context(self, request, ... |
from pymc3 import Model, Normal, Metropolis, MvNormal
import numpy as np
import pymc3 as pm
from itertools import product
from theano.tensor import log
def simple_model():
mu = -2.1
tau = 1.3
with Model() as model:
x = Normal('x', mu, tau, shape=2, testval=[.1]*2)
return model.test_point, mode... |
"""
Path operations common to more than one OS
Do not use directly. The OS specific modules import the appropriate
functions from this module themselves.
"""
import os
import stat
__all__ = ['commonprefix', 'exists', 'getatime', 'getctime', 'getmtime',
'getsize', 'isdir', 'isfile']
# Does a path exist?
#... |
"""
Support for inter-process calls.
"""
import httplib
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from avro import io
from avro import protocol
from avro import schema
#
# Constants
#
# Handshake schema is pulled in during build
HANDSHAKE_REQUEST_SCHEMA = schema.parse("... |
import os
from decimal import Decimal
from django.db import connection
from django.db.models import Q
from django.contrib.gis.geos import GEOSGeometry, Point, LineString
from django.contrib.gis.measure import D # alias for Distance
from django.contrib.gis.tests.utils import oracle, postgis, spatialite, no_oracle, no_s... |
"""
Rounder Data Transfer Objects
Various objects used to safely transmit game state or activity to clients.
In cases where an engine object is considered safe to transmit to a client,
a DTO should still be created as child class of the engine object. Even if
initially empty it provides a hook for us to change the DTO... |
"""Support for the MySQL database via the oursql adapter.
OurSQL is available at:
http://packages.python.org/oursql/
Connecting
-----------
Connect string format::
mysql+oursql://<user>:<password>@<host>[:<port>]/<dbname>
Character Sets
--------------
oursql defaults to using ``utf8`` as the connecti... |
from smtplib import SMTP_SSL as SMTP
from email.mime.text import MIMEText
import logging
import datetime
from utils.mongo_handler import mongodb_client
from utils.decorator import retry
from config import DEBUG as _DEBUG, EMAIL, INSTANCE_NAME as _INSTANCE_NAME
logger_server = logging.getLogger("DeployServer.MailManag... |
from __future__ import print_function
import re
import ast
import sys
from copy import deepcopy
from collections import namedtuple
from mdtraj.utils.six import PY2
from mdtraj.utils.external.pyparsing import (Word, ParserElement, MatchFirst,
Keyword, opAssoc, quotedString, alphas, alphanums, infixNotation, Group,
... |
"""Zookeeper Partitioner Implementation
:Maintainer: None
:Status: Unknown
:class:`SetPartitioner` implements a partitioning scheme using
Zookeeper for dividing up resources amongst members of a party.
This is useful when there is a set of resources that should only be
accessed by a single process at a time that mul... |
import argparse
import faulthandler
import itertools
import json
import logging
import logging.handlers
import sys
import traceback
from core import attrs
from core.config import *
_app = None
log = None
def excepthook(type_, value, tb):
# There is much to do in this department.
# For now, we can just preve... |
from . import IDLEenvironment
import string
import win32ui
import win32api
import win32con
from . import keycodes
import sys
import traceback
HANDLER_ARGS_GUESS=0
HANDLER_ARGS_NATIVE=1
HANDLER_ARGS_IDLE=2
HANDLER_ARGS_EXTENSION=3
next_id = 5000
event_to_commands = {}# dict of integer IDs to event names.
command_to_e... |
data = (
'You ', # 0x00
'Yan ', # 0x01
'Gu ', # 0x02
'Gu ', # 0x03
'Bai ', # 0x04
'Han ', # 0x05
'Suo ', # 0x06
'Chun ', # 0x07
'Yi ', # 0x08
'Ai ', # 0x09
'Jia ', # 0x0a
'Tu ', # 0x0b
'Xian ', # 0x0c
'Huan ', # 0x0d
'Li ', # 0x0e
'Xi ', # 0x0f
'Tang ', # 0x10
'Zuo ', ... |
# 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 field 'UserProfileDetail.ftp'
db.add_column('profiles_userprofiledetail', 'ftp', self.gf('django.... |
from bs4 import BeautifulSoup as bs
import requests
import sys
import json
def main():
if len(sys.argv)<2:
print "Usage : python zauba.py item_to_import"
sys.exit()
headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5", "content-... |
import mock
import sys
sys.modules["midonetclient"] = mock.Mock()
import testtools
import webob.exc as w_exc
from neutron.openstack.common import uuidutils
from neutron.plugins.midonet import midonet_lib
import neutron.tests.unit.midonet.mock_lib as mock_lib
def _create_test_chain(id, name, tenant_id):
return {'... |
"""
Implementation of an in-memory worker that defers execution.
"""
from __future__ import absolute_import, division, print_function
from zope.interface import implementer
from . import IWorker
from ._convenience import Quit
NoMoreWork = object()
@implementer(IWorker)
class MemoryWorker(object):
"""
An L{... |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.lexnparse
~~~~~~~~~~~~~~~~~~~~~~~~~~
All the unittests regarding lexing, parsing and syntax.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import time
import tempfile
import unittest
from ... |
"""Protocol message implementation hooks for C++ implementation.
Contains helper functions used to create protocol message classes from
Descriptor objects at runtime backed by the protocol buffer C++ API.
"""
__author__ = '<EMAIL> (Johan Tibell)'
from google.protobuf.pyext import _message
class GeneratedProtocolMe... |
import os
import re
from string import Template
from java_class_component import Enum, Field
from java_method import Method
class JavaClassLoader(object):
"""Manager class maintains all loaded java classes."""
def __init__(self, src_path, class_list):
self._src_path = src_path
self._class_list = class_li... |
"""
set_fake_emails.py
Give all users a new email account. Useful for testing in a
development environment. As such, this command is only available when
setting.DEBUG is True.
"""
from optparse import make_option
from django.conf import settings
from django.core.management.base import CommandError, NoArg... |
import pytest
@pytest.mark.xfail
def test_should_fail_if_first_line_not_EXTM3U():
assert 0
@pytest.mark.xfail
def test_should_fail_if_expected_ts_segment_line_is_not_valid():
assert 0
@pytest.mark.xfail
def test_should_fail_if_EXT_X_MEDIA_SEQUENCE_is_diffent_from_sequence_number_of_first_uri():
assert 0
... |
"""Code for more fancy file handles.
Classes:
UndoHandle File object decorator with support for undo-like operations.
StringHandle Wraps a file object around a string.
SGMLStripper Object that strips SGML. This is now considered OBSOLETE, and
is likely to be deprecated in a future release o... |
#pylint: disable=C0111
from lettuce import world, step
from lettuce.django import django_url
from common import i_am_registered_for_the_course, section_location
from django.utils.translation import ugettext as _
############### ACTIONS ####################
HTML5_SOURCES = [
'https://s3.amazonaws.com/edx-course-v... |
import os
import re
from ctypes import c_char_p
from django.core.validators import ipv4_re
from django.contrib.gis.geoip.libgeoip import GEOIP_SETTINGS
from django.contrib.gis.geoip.prototypes import (
GeoIPRecord, GeoIPTag, GeoIP_open, GeoIP_delete, GeoIP_database_info,
GeoIP_lib_version, GeoIP_record_by_addr... |
import MalmoPython
import os
import random
import sys
import time
import datetime
import json
import random
def GetMissionXML():
''' Build an XML mission string that uses the DefaultWorldGenerator.'''
return '''<?xml version="1.0" encoding="UTF-8" ?>
<Mission xmlns="http://ProjectMalmo.mi... |
from __future__ import absolute_import, division, unicode_literals
import sys
import os
if __name__ == '__main__':
# Allow us to import from the src directory
os.chdir(os.path.split(os.path.abspath(__file__))[0])
sys.path.insert(0, os.path.abspath(os.path.join(os.pardir, "src")))
from html5lib.tokenizer ... |
""" View for configuration. """
from os.path import join as path
from flask import render_template, g, redirect, session, flash, url_for, request
from Anemone import app, schedule
from Anemone.models import Project
import Anemone.abcfile
@app.route("/<project>/configuration", methods=["GET", "POST"])
def configuratio... |
import sickbeard
import generic
from sickbeard import helpers, logger, exceptions, tvcache
from lib.tvdb_api import tvdb_api, tvdb_exceptions
from sickbeard.name_parser.parser import NameParser, InvalidNameException
class EthorProvider(generic.TorrentProvider):
def __init__(self):
generic.TorrentProvide... |
"""
Support for Xiaomi Mi Flora BLE plant sensor.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.miflora/
"""
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from... |
"""
Tests to verify that string representations are accurate
"""
from . import TestCase
import bitmath
import os
class TestFileSize(TestCase):
# expected sizes are given in bytes
def setUp(self):
self.byte_file = './tests/file_sizes/bytes.test'
self.kibibyte_file = './tests/file_sizes/kbytes.... |
from m5.params import *
from m5.proxy import *
from Device import BasicPioDevice
class PcSpeaker(BasicPioDevice):
type = 'PcSpeaker'
cxx_class = 'X86ISA::Speaker'
cxx_header = "dev/x86/speaker.hh"
i8254 = Param.I8254('Timer that drives the speaker') |
"""Support for Lutron Caseta switches."""
import logging
from homeassistant.components.switch import DOMAIN, SwitchEntity
from . import DOMAIN as CASETA_DOMAIN, LutronCasetaDevice
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Lutron Cas... |
import sale_order_dates
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from __future__ import print_function
import sys
from kinds import SYNTAX_BASE_KINDS, kind_to_type, lowercase_first_word
def error(msg):
print('error: ' + msg, file=sys.stderr)
sys.exit(-1)
class Node(object):
"""
A Syntax node, possibly with children.
If the kind is "SyntaxCollection", then t... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import traceback
from ansible.errors.yaml_strings import (
YAML_COMMON_DICT_ERROR,
YAML_COMMON_LEADING_TAB_ERROR,
YAML_COMMON_PARTIALLY_QUOTED_LINE_ERROR,
YAML_COMMON_UNBALANCED_QUOTES_ERROR,
YAML_COM... |
import uuid
from datetime import datetime
from kombu.mixins import ConsumerMixin
from qpaca.backend.base import BaseSubscriber, BasePublisher
from qpaca.helpers import get_config, logger
from qpaca.backend.handlers import RabbitMQHandler
from qpaca.monitoring.influx import InfluxDB
class RabbitMQPublisher(BasePubli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.