content stringlengths 4 20k |
|---|
from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen
from Components.config import config, ConfigSubsection, ConfigInteger, ConfigSelection, ConfigSlider, getConfigListEntry
modelist = {"off": _("Off"), "auto": _("Auto"), "sidebyside": _("Side by Side"), "topandbottom": _("Top and Botto... |
from .package import EggPackage, SourcePackage, WheelPackage
class Sorter(object):
DEFAULT_PACKAGE_PRECEDENCE = (
WheelPackage,
EggPackage,
SourcePackage,
)
@classmethod
def package_type_precedence(cls, package, precedence=DEFAULT_PACKAGE_PRECEDENCE):
for rank, package_type in enumerate... |
# test the functions imported from cmath
try:
from cmath import *
except ImportError:
print("SKIP")
raise SystemExit
# make sure these constants exist in cmath
print("%.5g" % e)
print("%.5g" % pi)
test_values_non_zero = []
base_values = (0.0, 0.5, 1.2345, 10.)
for r in base_values:
for i in base_valu... |
from translate.storage import factory
from translate.storage.xml_extract import unit_tree
# _split_xpath_component
def test__split_xpath_component():
assert (u'some-tag', 0) == unit_tree._split_xpath_component(u'some-tag[0]')
# _split_xpath
def test__split_xpath():
assert [(u'p', 4), (u'text', 3), (u'bod... |
import unittest
from datetime import datetime
from airflow.models import BaseOperator, TaskInstance
from airflow.utils.trigger_rule import TriggerRule
from airflow.ti_deps.deps.trigger_rule_dep import TriggerRuleDep
from airflow.utils.state import State
class TriggerRuleDepTest(unittest.TestCase):
def _get_task... |
"""
Desktop logging configuration and library package that is independent from Django.
This module contains basic setup functions for logging.
"""
import logging
import logging.config
import os
import os.path
import re
import sys
from cStringIO import StringIO
from desktop.lib.paths import get_desktop_root
DEFAULT_... |
# -*- coding: utf-8 -*-
"""
jinja2.utils
~~~~~~~~~~~~
Utility functions.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import sys
import errno
try:
from thread import allocate_lock
except ImportError:
from dummy_thread import allocate_lo... |
"""
CrowdKernel algorithm of the Online Learning Library for Next.Discovery
author: Lalit Jain, <EMAIL>
last updated: 4/22/2015
"""
import numpy
import numpy.random
from apps.PoolBasedTripletMDS.algs.CrowdKernel import utilsCrowdKernel
import time
class CrowdKernel:
def initExp(self,butler,n,d,failure_probability)... |
"""
Classes to represent the default SQL aggregate functions
"""
import copy
import warnings
from django.db.models.fields import FloatField, IntegerField
from django.db.models.lookups import RegisterLookupMixin
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.functional import cached_pro... |
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from neutron.common import constants
from neutron.common import rpc as n_rpc
from neutron.common import topics
from neutron.common import utils
from neutron.i18n import _LE, _LW
from neutron import manager
LOG = logging.getLogger(_... |
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
class hr_timesheet_current_open(osv.osv_memory):
_name = 'hr.timesheet.current.open'
_description = 'hr.timesheet.current.open'
def open_timesheet(self, cr, uid, ids, context=None):
ts = self.pool.get('hr_timesh... |
import os
import gi
gi.require_version("BlockDev", "2.0")
from gi.repository import BlockDev as blockdev
import logging
log = logging.getLogger("blivet")
class MpathMembers(object):
"""A cache for querying multipath member devices"""
def __init__(self):
self._members = None
def is_mpath_member... |
#!/usr/bin/env python
# Check to validate rabbitmq connectivity
# This is an alternative to the management plugin and rabbitmqadmin
# Note rabbitmqadmin is available from http://<rabbitmq>:15672/cli/
# and should be saved in /usr/local/bin
#
# Usage: check_rabbit.py --host myhost --port 5672 --user myuser --password my... |
"""Implementation of magic functions for the extension machinery.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distrib... |
MAGIC = "@@@"
# Colors for log levels
LEVEL_COLORS = {
'DEBUG': 'CYAN',
'INFO': 'GREEN',
'WARNING': 'YELLOW',
'ERROR': 'RED',
'CRITICAL': 'blink@@@RED',
}
# Will get set to True if module is initialized
enabled = False
# Gets set to True if we should strip special sequences but
# not actually try to colori... |
import heapq
import psycopg2 # Trigger import error if not installed.
import threading
import time
from peewee import *
from peewee import savepoint
from peewee import transaction
from playhouse.pool import *
from playhouse.tests.base import database_initializer
from playhouse.tests.base import PeeweeTestCase
class... |
"""Generates the appropriate build.json data for all the naming tests."""
import yaml
import collections
import hashlib
import json
_LOCAL_DNS_SERVER_ADDRESS = '127.0.0.1:15353'
def _append_zone_name(name, zone_name):
return '%s.%s' % (name, zone_name)
def _build_expected_addrs_cmd_arg(expected_addrs):
ou... |
"""
simo_011-single_interface-dispersive.py is a simulation example for EMUstack.
Copyright (C) 2015 Bjorn Sturmberg
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 versi... |
import logging
import re
import unicodedata
from openerp.osv import fields, osv
from openerp.tools import ustr
from openerp.modules.registry import RegistryManager
from openerp import SUPERUSER_ID
_logger = logging.getLogger(__name__)
# Inspired by http://stackoverflow.com/questions/517923
def remove_accents(input_s... |
import sys
import imp
import os
import unittest
from test import test_support
test_src = """\
def get_name():
return __name__
def get_file():
return __file__
"""
absimp = "import sub\n"
relimp = "from . import sub\n"
deeprelimp = "from .... import sub\n"
futimp = "from __future__ import absolute_import\n"
r... |
import numpy as np
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.models.rbm import RBM
from pylearn2.models.s3c import S3C, E_Step, Grad_M_Step
from pylearn2.training_algorithms.default import DefaultTrainingAlgorithm
from pylearn2.training_algorithms.training_algorithm import NoBat... |
from django.conf import settings
from bloom.sms.lib.upside.Authentication_client import *
from bloom.sms.lib.upside.SMS_client import *
class UpsideConnector:
def __init__(self, username, password):
self.username = username
self.password = password
self.token = (str(settings.BLOOM_S... |
import keras
import tensorflow as tf
import keras.backend as K
K_VAL = 7
def bin_crossentropy_true_only(y_true, y_pred):
return (1 + K.sum(y_pred, axis=-1)) * K.mean(K.binary_crossentropy(y_true * y_pred, y_true), axis=-1)
# def tf_sparse_precision_at_k(y_true, y_pred):
# y_true_labels = tf.transpose(tf.wh... |
"""Tests for the routing function op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.tensor_forest.hybrid.ops import gen_training_ops
from tensorflow.contrib.tensor_forest.hybrid.python.ops import training_ops
from tensorflow.pyt... |
import base64
import datetime
from django.core import validators
from django import oldforms
from django.core.mail import mail_admins, mail_managers
from django.http import Http404
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render_to_response
from django.template import RequestC... |
#!/usr/bin/env python
"Makes working with XML feel like you are working with JSON"
from xml.parsers import expat
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import AttributesImpl
try: # pragma no cover
from cStringIO import StringIO
except ImportError: # pragma no cover
try:
from... |
from UserDict import DictMixin
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clear()
self.u... |
# Figures 8.3 and 8.4, pages 412 and 416.
# Ellipsoidal approximations.
from math import log, pi
from cvxopt import blas, lapack, solvers, matrix, sqrt, mul, cos, sin
#solvers.options['show_progress'] = False
try: import pylab
except ImportError: pylab_installed = False
else: pylab_installed = True
# Extreme points ... |
from Registry import Registry
from DPAPI.Core import crypto
from DPAPI.Core import eater
class Regedit(object):
"""This class provides several functions to handle registry extraction
stuff.
"""
def __init__(self):
self.syskey = None
self.lsakeys = None
self.policy = {"major":... |
"""
Monkey-patch the edX platform
Here be dragons (and simians!)
* USE WITH CAUTION *
No, but seriously, you probably never really want to make changes here.
This module contains methods to monkey-patch [0] the edx-platform.
Patches are to be applied as early as possible in the callstack
(currently lms/startup.py and... |
# coding=utf-8
from Tkinter import *
from game_logic.model.player import *
from game_logic.model.match import *
from game_logic.match_builder import *
import math
fenster = Tk()
height = 400
width = 600
flaeche = Canvas(fenster, width=width, height=height)
def zeichnen():
player1 = Player('A',None)
player2 ... |
from django.conf import settings
from django.views.generic.list import MultipleObjectMixin
from oscar.core.loading import get_class, get_model
BrowseCategoryForm = get_class('search.forms', 'BrowseCategoryForm')
SearchHandler = get_class('search.search_handlers', 'SearchHandler')
is_solr_supported = get_class('search... |
import os
import sys
import getopt
try:
import wx # NOQA
if wx.VERSION < (4,):
raise ImportError()
except:
print("wxPython >= 4 is not installed. This program requires wxPython >=4 to run.")
raise
from printrun.pronterface import PronterApp
if __name__ == '__main__':
from printrun.print... |
from stacktask_tempest_plugin.tests import base
from tempest.common import utils
from tempest.lib import decorators
from tempest.lib.common.utils import data_utils
class StacktaskSignup(base.BaseStacktaskTest):
credential_roles = ['admin']
@classmethod
def resource_setup(cls):
super(StacktaskSign... |
from django.conf import settings
from django import http
class XViewMiddleware(object):
"""
Adds an X-View header to internal HEAD requests -- used by the documentation system.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
"""
If the request method is HEAD and ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=bad-whitespace,redefined-builtin
"""
nwid setup
"""
from codecs import open
from setuptools import setup, find_packages
from os import path
from nwid import __version__ as version
with open('README.rst', 'r', 'utf-8') as f:
README = f.read()
url... |
from kivy.app import App
from kivy.factory import Factory
from kivy.lang import Builder
Factory.register('QRScanner', module='electrum_ltc.gui.kivy.qr_scanner')
class QrScannerDialog(Factory.AnimatedPopup):
__events__ = ('on_complete', )
def on_symbols(self, instance, value):
instance.stop()
... |
"""Base classes for cryptographic signers and verifiers."""
import abc
import io
import json
import six
_JSON_FILE_PRIVATE_KEY = 'private_key'
_JSON_FILE_PRIVATE_KEY_ID = 'private_key_id'
@six.add_metaclass(abc.ABCMeta)
class Verifier(object):
"""Abstract base class for crytographic signature verifiers."""
... |
from math import sqrt
from random import uniform
from pokemongo_bot.cell_workers.utils import distance
from pokemongo_bot.human_behaviour import random_lat_long_delta, sleep, random_alt_delta
class StepWalker(object):
def __init__(self, bot, dest_lat, dest_lng, dest_alt = None):
self.bot = bot
se... |
import six
from openstack import resource
from openstack.telemetry import telemetry_service
class Capability(resource.Resource):
resource_key = 'capability'
resources_key = 'capabilities'
base_path = '/capabilities'
service = telemetry_service.TelemetryService()
# Supported Operations
allow_... |
from boto.compat import six
class Batch(object):
"""
Used to construct a BatchGet request.
:ivar table: The Table object from which the item is retrieved.
:ivar keys: A list of scalar or tuple values. Each element in the
list represents one Item to retrieve. If the schema for the
t... |
import os
import pipes
def query_package(module, package, action):
if package.startswith('@'):
return query_set(module, package, action)
return query_atom(module, package, action)
def query_atom(module, atom, action):
cmd = '%s list %s' % (module.equery_path, atom)
rc, out, err = module.run... |
"""
WSGI config for zulip project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... |
from contextlib import contextmanager
from django.conf import settings
from django.db import connection
try:
from django.apps import apps
get_model = apps.get_model
except ImportError:
from django.db.models.loading import get_model
from django.core import mail
@contextmanager
def schema_context(schema_nam... |
import logging
import time
from zcp.common.db import impl_mongo
from zcp.task.polling import INSTANCE_METRICS, NETWORK_METRICS
from zcp.task.polling.base_handler import Handler
from zcp import utils
LOG = logging.getLogger(__name__)
METRIC_CACEHES = {}
def get_handler(*args):
return MongoHandler(*args)
class ... |
from __future__ import absolute_import, division, print_function, with_statement
from wsgiref.validate import validator
from tornado.escape import json_decode
from tornado.test.httpserver_test import TypeCheckHandler
from tornado.testing import AsyncHTTPTestCase
from tornado.util import u
from tornado.web import Reque... |
#!/usr/bin/env python
'''
parse a MAVLink protocol XML file and generate a python implementation
Copyright Andrew Tridgell 2011
Released under GNU GPL version 3 or later
'''
import sys, textwrap, os
from . import mavparse
# XSD schema file
schemaFile = os.path.join(os.path.dirname(os.path.realpath(__file__)), "mavs... |
""" THIS TEST REQUIRES NO THIRD PARTY APPLICATIONS OTHER THAN THE SPARKTK
THIS TEST IS TO BE MAINTAINED AS A SMOKE TEST FOR THE ML SYSTEM
"""
import unittest
from sparktk import TkContext
class CumSumTest(unittest.TestCase):
def test_frame_basic(self):
"""Documentation test for classifiers"""
... |
"""Fetch android artifacts and update pom properties."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import json
import string
import sys
import urllib2
def get_args():
"""Parse command line args."""
parser = argparse.ArgumentParse... |
# toolmenu.py
import win32ui
import win32con
import win32api
import app
import sys
import string
tools = {}
idPos = 100
# The default items should no tools menu exist in the INI file.
defaultToolMenuItems = [
('Browser', 'win32ui.GetApp().OnViewBrowse(0,0)'),
('Browse PythonPath', 'from pywin.tools import br... |
"""
Class representing the list of files in a distribution.
Equivalent to distutils.filelist, but fixes some problems.
"""
import fnmatch
import logging
import os
import re
from . import DistlibException
from .compat import fsdecode
from .util import convert_path
__all__ = ['Manifest']
logger = logging.getLogger(_... |
"""Bio.SearchIO parser for Exonerate vulgar output format."""
import sys
# Add path to Bio
sys.path.append('../../..')
import re
from Bio._py3k import _as_bytes, _bytes_to_string
from Bio._py3k import zip
from Bio.SearchIO.ExonerateIO._base import _BaseExonerateParser, _BaseExonerateIndexer, _STRAND_MAP
__all__ =... |
# You can edit these settings and save them, they
# will be applied immediately and remembered for next time.
# This will reset the interpreter.
# ******************************************************************************* #
# If changing these settings makes the interpreter unrecoverable, you #
# can... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
from ansible.module_utils.facts.collector import BaseFactCollector
try:
# Check if we have SSLContext support
from ssl import create_default_context, SSLContext
del create_default_context
del SSLContext... |
import controllers
import models
import wizard |
# _*_ coding:utf-8 _*_
__author__ = 'Sheldon'
__date__ = '2019/2/21 20:29'
import socket
from datetime import datetime
from concurrent import futures
from multiprocessing import Pool
import os
def blocking_way():
sock = socket.socket()
# blocking
sock.connect(('example.com', 80))
request = 'GET / HTTP... |
"""Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.counter import (
DOMAIN,
SERVICE_DECREMENT,
SERVICE_INCREMENT,
SERVICE_RESET,
)
from homeassistant.const import ATTR... |
'''
This program will update all those packages consider by pip to outdated.
It makes the assumption that those package that are wheels do not cause
breakage of other packages already installed.
'''
from distutils.version import LooseVersion
from subprocess import check_output, check_call
import re
test_pip_output = '... |
"""This module contains logic for carrying out create/modify/delete tasks.
"""
from collections import defaultdict
import datetime
import logging
import numpy
import pprint
import re
import time
import urllib
from google.appengine.api import runtime
from google.appengine.api import taskqueue
from google.appengine.ext... |
from __future__ import print_function
import textwrap
import sys, re
wrapper = textwrap.TextWrapper()
# take an array of lines and wrap them to 78 columns and let each line start
# with @p startwith
def wrap_block(lines, startwith):
longline = " ".join(lines)
wrapper.initial_indent = startwith
wrapper.subs... |
# -*- coding: utf-8 -*-
"""
pygments.style
~~~~~~~~~~~~~~
Basic style object.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.token import Token, STANDARD_TYPES
class StyleMeta(type):
def __new__(mcs, name, bases,... |
from __future__ import absolute_import, unicode_literals
import datetime
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField, Select
from django.utils.translation import ugettext_lazy as _
from django.contrib.localflavor.mk.mk_choices im... |
import bpy
from bpy.types import Panel
from rna_prop_ui import PropertyPanel
class DataButtonsPanel:
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "data"
@classmethod
def poll(cls, context):
return context.meta_ball
class DATA_PT_context_metaball(DataButtonsPanel, ... |
import cxm.core, cxm.vm
import unittest, os
class VMTests(unittest.TestCase):
def setUp(self):
cxm.core.cfg['VMCONF_DIR'] = "tests/stubs/cfg/"
def test_vm_ok1(self):
self.assertTrue(isinstance(cxm.vm.VM("test1.home.net"), cxm.vm.VM))
def test_vm_ok2(self):
self.assertTrue(isinstance(cxm.vm.VM("testcfg.home... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleAction, AnsibleActionFail
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
TRANSFERS_FILES = False
UNUSED_PARAMS = {
'systemd': ['pattern', 'runlev... |
"""
Support for Tomato routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.tomato/
"""
import json
import logging
import re
import threading
from datetime import timedelta
import requests
from homeassistant.components.device_tracker ... |
#!/usr/bin/env python3
import time
import os, sys
from .utils import *
from .downloader import *
from .extractor import *
class MGetDL(FileDownloader):
def __init__(self, opts, info):
super(MGetDL, self).__init__(info)
if opts.verbose: common.debug_info(info)
self.info = info
self.params = opts
self.defur... |
#!/usr/bin/env python
'''
owtf is an OWASP+PTES-focused try to unite great tools & facilitate pentesting
Copyright (c) 2013, Abraham Aranguren <<EMAIL>> http://7-a.org
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following condit... |
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class TestNode(NodeConnCB):
def __init__(self):
NodeConnCB.__init__(self)
self.connection = None
self.ping_counter = 1
self.last_pong = msg_pong()
... |
"""A plugin that lists installed packages that are obsolted by any available package"""
from dnf.i18n import _
import dnf
import dnf.cli
# If you only plan to create a new dnf subcommand in a plugin
# you can use @dnf.plugin.register_command decorator instead of creating
# a Plugin class which only registers the com... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.f5_utils import (
AnsibleF5Client,
AnsibleF5Parameters,
HAS_F5SDK,
F5ModuleError,
iControlUnexpectedHTTPError
)
class Parameters(Ans... |
import argparse
import logging
import rfactortools
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='GTR2 to GSC2013 converter')
parser.add_argument('DIRECTORY', action='store', type=str, nargs=1,
help='directory containing the mod')
parser.add_argument('-o'... |
# -*- coding: utf-8 -*-
'''
PDF Generator
-------
The pdf plugin generates PDF files from reStructuredText and Markdown sources.
'''
from __future__ import unicode_literals, print_function
from io import open
from pelican import signals
from pelican.generators import Generator
from pelican.readers import MarkdownRea... |
"""See README for more information"""
import multiprocessing
from optparse import OptionParser
import os
import re
import sys
import unittest
# Bring in the patman libraries
our_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(our_path, '../patman'))
# Our modules
import board
import b... |
#!/usr/bin/env python
import argparse
import bz2file
import sys
from dark.diamond.conversion import DiamondTabularFormatReader
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Convert DIAMOND tabular output to JSON.',
epilog=('Give a DIAMOND tabular file and convert it ... |
from __future__ import unicode_literals
from django.contrib.auth.handlers.modwsgi import check_password, groups_for_user
from django.contrib.auth.models import User, Group
from django.contrib.auth.tests.custom_user import CustomUser
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.test import T... |
# -*- coding: utf-8 -*-
from .vendor.Qt import QtCore, QtGui, QtWidgets
from . import lib
from . import button
import sys
# from __future__ import absolute_import, division, print_function
SORT_ROLE = QtCore.Qt.UserRole + 1
class Column(object):
u"""カラム情報"""
def __init__(self, index, value):
self.va... |
"""
Helpers for comparing version strings.
"""
import functools
import pkg_resources
from ironic.openstack.common.gettextutils import _
from ironic.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class deprecated(object):
"""A decorator to mark callables as deprecated.
This deco... |
"""Generic Node base class for all workers that run on hosts."""
import os
import random
import sys
from oslo.config import cfg
from oslo import messaging
from nova import baserpc
from nova import conductor
from nova import context
from nova import debugger
from nova import exception
from nova.i18n import _
from nov... |
import sys
import time
import zmq
def main(argv):
use_poll = '-p' in argv
use_copy = '-c' in argv
if use_copy:
argv.remove('-c')
if use_poll:
argv.remove('-p')
if len (argv) != 4:
print ('usage: local_lat [-c use-copy] [-p use-poll] <bind-to> <message-size> <roundtrip-coun... |
#!/usr/lib/env python
# -*- code:utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import csv
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelBinarizer
from tensorflow.contrib import learn... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from subprocess import Popen, PIPE
from ansible.errors import AnsibleParserError
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.common._collections_compat import MutableMap... |
import uuid
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest import exceptions
from tempest import test
class HypervisorAdminNegativeV3Test(base.BaseV3ComputeAdminTest):
"""
Tests Hypervisors API that require admin privileges
"""
@classmethod
def set... |
from .base import ischema_names
from ... import types as sqltypes
__all__ = ('INT4RANGE', 'INT8RANGE', 'NUMRANGE')
class RangeOperators(object):
"""
This mixin provides functionality for the Range Operators
listed in Table 9-44 of the `postgres documentation`__ for Range
Functions and Operators. It is... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
def GetRGBColor(colorName):
'''
Return the red, green and blue components for a
color as doubles.
'''
rgb = [0.0, 0.0, 0.0] # black
vtk.vtkNamedColors... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from nmadb_academics.models import Academic, Section
from nmadb_contacts.models import Human
class Session(models.Model):
""" Information about session.
"""
SESSION_TYPE = (
(u'Wi', _(u'winter'),),
... |
# -*- coding: utf-8 -*-
"""This module contains classes representing syntactical elements of SQL."""
import re
from debug_toolbar.utils.sqlparse import tokens as T
class Token(object):
"""Base class for all other classes in this module.
It represents a single token and has two instance attributes:
``v... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def add_categories(apps, schema_editor):
Category = apps.get_model('niqati', 'Category')
# We are going to add categories only if none already exists.
if not Category.objects.exists():
Category... |
from datetime import datetime, timedelta
import pendulum
import unittest
from airflow.utils import dates
from airflow.utils import timezone
class Dates(unittest.TestCase):
def test_days_ago(self):
today = pendulum.today()
today_midnight = pendulum.instance(datetime.fromordinal(today.date().toord... |
#!/usr/bin/env python
from nose.tools import *
import networkx as nx
from networkx import NetworkXNotImplemented
class TestAttractingComponents(object):
def setUp(self):
self.G1 = nx.DiGraph()
self.G1.add_edges_from([(5, 11), (11, 2), (11, 9), (11, 10),
(7, 11), (7,... |
from collections import MutableMapping
class OrderedDict(dict, MutableMapping):
# Methods with direct access to underlying attributes
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at 1 argument, got %d', len(args))
if not hasattr(self, '_keys'):
... |
"""
Key generators for data store objects
"""
import hashlib
import pickle
import sys
import os.path
def full_type(component):
"""Returns a string representing the full type of the component."""
if component.__class__.__name__ == 'module': # component is a module
if component.__name__ == "__main__":
... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Base MongoDB classes
"""
from handlers.settings import LOGGER, DB
from pymongo import MongoReplicaSetClient, MongoClient
from pymongo.errors import OperationFailure, ConnectionFailure
from pymongo.read_preferences import ReadPreference
from pymongo.ssl_support import s... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The dtk module provides basic functions for interfacing with
Diffusion Toolkit tools.
Currently these tools are supported:
* TODO
Examples
--------
See the docstrings for the individual classes fo... |
{
"name": "Stock obsolete",
"summary": "Add product depreciation",
"version": "1.0",
"author": "Camptocamp,Odoo Community Association (OCA)",
"category": "Generic Modules/Stock",
"description":
"""
Add a special view and wizard on product to check the validity of each
stock p... |
from ._slackrequest import SlackRequest
from ._channel import Channel
from ._user import User
from ._util import SearchList
from websocket import create_connection
import json
class Server(object):
def __init__(self, token, connect=True):
self.token = token
self.username = None
self.domai... |
# -*- coding: utf-8 -*-
"""
test all other .agg behavior
"""
from __future__ import print_function
import pytest
from datetime import datetime, timedelta
from functools import partial
import numpy as np
import pandas as pd
from pandas import date_range, DataFrame, Index, MultiIndex, Series
from pandas.core.groupb... |
# -*- coding: utf-8 -*-
from puzzle.models.sql import Comment
def test_add_comment_case(test_db):
text = 'test-comment'
case_obj = test_db.cases().first()
comment_obj = test_db.add_comment(case_obj, text)
assert isinstance(comment_obj, Comment)
assert comment_obj.text == text
def test_add_comment_... |
from __future__ import unicode_literals
import unittest
import frappe
from frappe.utils import global_search
from frappe.test_runner import make_test_objects
import frappe.utils
class TestGlobalSearch(unittest.TestCase):
def setUp(self):
global_search.setup_global_search_table()
self.assertTrue('__global_search'... |
'''
test for cloned vm changing password
@author: SyZhao
'''
import apibinding.inventory as inventory
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.operations.vm_operations as vm_ops
import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.