content stringlengths 4 20k |
|---|
import inspect
import sys
from collections import namedtuple
###############
# Structs #
###############
# https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-MetadataAPI
MetadataRequest = namedtuple("MetadataRequest",
["topics"])
MetadataResponse = namedt... |
{
'name': 'Membership Management',
'version': '0.1',
'category': 'Association',
'description': """
This module allows you to manage all operations for managing memberships.
=========================================================================
It supports different kind of members:
-----------------... |
#!/usr/bin/env python
# encoding: utf-8
"""
time task handy funcs
"""
import random
import operator
import datetime
import sys
from logmanager import LogManager
from threading import Thread, Event, Lock
custom_logger = LogManager(logFile='scheduler.log', logLevel=5).logger
class Task(object):
def __init__(self... |
import pytest
# Global objects under tests
@pytest.fixture
def Workbook():
"""Workbook Class"""
from openpyxl import Workbook
return Workbook
@pytest.fixture
def Worksheet():
"""Worksheet Class"""
from openpyxl.worksheet import Worksheet
return Worksheet
# Global fixtures
@pytest.fixture
... |
from PrismaCloudComputeParseComplianceAlert import parse_compliance
import pytest
import json
def test_parse_compliance():
valid_raw_json = json.dumps({
"_id": "testID",
"compliance": [
{
"description": "testDescription",
"id": "testID",
... |
import _base
class Filter(_base.Filter):
def __init__(self, source, encoding):
_base.Filter.__init__(self, source)
self.encoding = encoding
def __iter__(self):
state = "pre_head"
meta_found = (self.encoding is None)
pending = []
for token in _base.Filter.__iter... |
# -*- coding: utf-8 -*-
import datetime
from dateutil.relativedelta import relativedelta
from openerp import fields, tools
from openerp.addons.event.tests.common import TestEventCommon
from openerp.tools import mute_logger
class TestMailSchedule(TestEventCommon):
@mute_logger('openerp.addons.base.ir.ir_model',... |
import os
import mock
from nova.tests.unit.virt.hyperv import test_base
from nova.virt.hyperv import constants
from nova.virt.hyperv import pathutils
from nova.virt.hyperv import vmutils
class PathUtilsTestCase(test_base.HyperVBaseTestCase):
"""Unit tests for the Hyper-V PathUtils class."""
def setUp(self)... |
#!/usr/bin/python
import dbus
import os
import sys
def printusage():
print 'bthmonoheadset.py <options>'
print ' create - create a mono headset'
print ' start - connect and play '
print ' stop - stop and disconnect'
return
headsetAddress = os.getenv("BTMONO_HEADSET")
print 'BT Mono Headset Is : =>... |
import logging
import re
import time
from openerp.osv import osv, fields
from openerp import tools
from openerp.tools.translate import _
_logger = logging.getLogger(__name__)
try:
from mygengo import MyGengo
except ImportError:
_logger.warning('Gengo library not found, Gengo features disabled. If you plan to... |
from .. import util
importlib = util.import_importlib('importlib')
machinery = util.import_importlib('importlib.machinery')
import errno
import os
import sys
import tempfile
from types import ModuleType
import unittest
import warnings
import zipimport
class FinderTests:
"""Tests for PathFinder."""
def tes... |
"""
NTLM authenticating pool, contributed by erikcederstran
Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10
"""
from __future__ import absolute_import
from logging import getLogger
from ntlm import ntlm
from .. import HTTPSConnectionPool
from ..packages.six.moves.http_client import HTTPSConnecti... |
import numpy
import six
from chainer import backend
from chainer import function_node
import chainer.functions
import chainer.utils
from chainer.utils import type_check
import chainerx
class SelectorBase(function_node.FunctionNode):
"""Select an array element from a given axis or set of axes."""
def __init_... |
# -*- coding: utf-8 -*-
"""
plugin.ipython
~~~~~~~~~~~~~~~~~~~~~~~~
This module provides a Python library for Windows Azure Virtual Machines.
:copyright: TBD
:license: TBD
"""
import paramiko
import os
class IPython:
def __init__(self):
self.profile_name = "ssh"
#self.init_ssh()
def ini... |
import unittest
from ctypes import *
class MyInt(c_int):
def __cmp__(self, other):
if type(other) != MyInt:
return -1
return cmp(self.value, other.value)
def __hash__(self): # Silence Py3k warning
return hash(self.value)
class Test(unittest.TestCase):
def test_compare(... |
import sys
import os
from pymavlink import mavutil
from construct import ULInt16, Struct, Byte, Bytes, Const
from construct.core import FieldError
from optparse import OptionParser
MAVLINK_MAGIC = 0xfe
write_junk = True
# copied from ardupilotmega.h (git changeset 694536afb882068f50da1fc296944087aa207f9f, Dec 02 ... |
from connection import H2OConnection
from frame import H2OFrame
from job import H2OJob
from model.model_future import H2OModelFuture
from model.dim_reduction import H2ODimReductionModel
from model.autoencoder import H2OAutoEncoderModel
from model.multinomial import H2OMultinomialModel
from model.regression ... |
class ChainFinder(object):
def __init__(self):
self.parent_lookup = {}
self.descendents_by_top = {}
self.trees_from_bottom = {}
def __repr__(self):
return "<ChainFinder: trees_fb:%s d_b_tops:%s>" % (self.trees_from_bottom, self.descendents_by_top)
def load_nodes(self, nodes... |
"""Etcd client."""
import threading
import random
from contextlib import contextmanager
import etcd3
from fedlearner.common import mock_kvstore
class EtcdClient(object):
ETCD_CLIENT_POOL_LOCK = threading.Lock()
ETCD_CLIENT_POOL = {}
ETCD_CLIENT_POOL_DESTORY = False
class Event(object):
def __... |
"""
Provide utilities for printing endnotes in text reports.
"""
from ..docgen import FontStyle, ParagraphStyle, FONT_SANS_SERIF
from ...lib import NoteType, Citation
from ...ggettext import gettext as _
from ...utils.string import confidence
from ...datehandler import displayer
def add_endnote_styles(style_sheet):
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import json
from ansible.module_utils.basic import AnsibleModule
from copy import deepcopy... |
from django.db import models
from django.utils.safestring import mark_safe
from base.models.enums import organization_type
from osis_common.models.serializable_model import SerializableModel, SerializableModelAdmin
class OrganizationAdmin(SerializableModelAdmin):
list_display = ('name', 'acronym', 'type', 'chang... |
from openerp.report import report_sxw
from openerp.tools import amount_to_text_en
class payslip_details_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(payslip_details_report, self).__init__(cr, uid, name, context)
self.localcontext.update({
'get_details... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
from ast import literal_eval
HAS_PYTHON26 = True
except ImportError:
HAS_PYTHON26 = False
try:
from google.cloud import spanner
from google.gax.errors imp... |
import re
import time
import operator
import supybot.dbi as dbi
import supybot.log as log
import supybot.conf as conf
import supybot.utils as utils
import supybot.ircdb as ircdb
from supybot.commands import *
import supybot.ircmsgs as ircmsgs
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import... |
"""
I am a virtual hosts implementation.
"""
# Twisted Imports
from twisted.python import roots
from twisted.web import resource
class VirtualHostCollection(roots.Homogenous):
"""Wrapper for virtual hosts collection.
This exists for configuration purposes.
"""
entityType = resource.Resource
def... |
from __future__ import absolute_import, division, unicode_literals
import re
from xml.sax.saxutils import escape, unescape
from .tokenizer import HTMLTokenizer
from .constants import tokenTypes
class HTMLSanitizerMixin(object):
""" sanitization of XHTML+MathML+SVG and of inline style attributes."""
accepta... |
# -*- coding: utf-8 -*-
import os
import sys
import re
import subprocess
import tarfile
from .utils import Color as c, run_and_print
from .server import get_total_ram
from six import print_
class Benchmark(object):
def __init__(self, specs, stdout):
self.specs = specs
self.stdout = stdout
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
import ansible.errors
from ansible.executor import module_common as amc
from ansible.executor.interpreter_discovery import InterpreterDiscoveryRequiredError
from ansible.module_utils.six import PY2
class TestStrip... |
"""California housing dataset.
The original database is available from StatLib
http://lib.stat.cmu.edu/
The data contains 20,640 observations on 9 variables.
This dataset contains the average house value as target variable
and the following input variables (features): average income,
housing average age, averag... |
"""Keystone Caching Layer Implementation."""
import dogpile.cache
from dogpile.cache import proxy
from dogpile.cache import util
from oslo_config import cfg
from oslo_log import log
from oslo_utils import importutils
from keystone import exception
from keystone.i18n import _, _LE
CONF = cfg.CONF
LOG = log.getLogger... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import urllib.parse
class NodeHandlingTest (BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 4
self.setup_clean_chain = False
def run_test(self):
###... |
"""
Polish-language mappings for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
labels = {
# fixed: language-dependent
'author': u'Autor',
'authors': u'Autorzy',
'organization': u'Organizacja',
'address': u'Adres',
'contact': u'Kontakt',
'vers... |
#!/usr/bin/env python
"""
This example calculates the Ricci tensor from the metric and does this
on the example of Schwarzschild solution.
If you want to derive this by hand, follow the wiki page here:
http://en.wikipedia.org/wiki/Deriving_the_Schwarzschild_solution
Also read the above wiki and follow the reference... |
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
class VMwareMigrateVmk(object):
def __init__(self, module):
self.module = module
self.host_system = None
self.migrate_switch_name = self.module.params['migrate_switch_name']
s... |
from fofix.core.View import BackgroundLayer
from fofix.core.Input import KeyListener
from fofix.core.Camera import Camera
from OpenGL.GL import *
from OpenGL.GLU import *
class Scene(BackgroundLayer, KeyListener):
def __init__(self, engine):
self.engine = engine
self.actors = []
self.cam... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import unittest
from unittest import skipUnless
from django.conf import settings
from django.contrib.gis.geoip2 import HAS_GEOIP2
from django.contrib.gis.geos import HAS_GEOS, GEOSGeometry
from django.test import mock
from django.utils import s... |
import warnings
from django.contrib.auth.models import User
from django.test import TestCase
class SpecialHeadersTest(TestCase):
fixtures = ['data.xml']
urls = 'regressiontests.special_headers.urls'
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=De... |
#pylint: disable=no-init
from __future__ import (absolute_import, division, print_function)
from mantid.simpleapi import *
from mantid.kernel import *
from mantid.api import *
class AddSampleLogMultiple(PythonAlgorithm):
def category(self):
return 'DataHandling\\Logs'
def summary(self):
ret... |
from __future__ import absolute_import, division, print_function, \
with_statement
from ctypes import c_char_p, c_int, c_long, byref,\
create_string_buffer, c_void_p
from shadowsocks import common
from shadowsocks.crypto import util
__all__ = ['ciphers']
libcrypto = None
loaded = False
buf_size = 2048
de... |
#!/usr/bin/env python
"""
An example of the MultiDiGraph clas
The function chess_pgn_graph reads a collection of chess
matches stored in the specified PGN file
(PGN ="Portable Game Notation")
Here the (compressed) default file ---
chess_masters_WCC.pgn.bz2 ---
contains all 685 World Chess Championship matches
from... |
"""IPv4 helper functions."""
import struct
import dns.exception
def inet_ntoa(address):
if len(address) != 4:
raise dns.exception.SyntaxError
return '%u.%u.%u.%u' % (ord(address[0]), ord(address[1]),
ord(address[2]), ord(address[3]))
def inet_aton(text):
parts = text.... |
# pylint: skip-file
# flake8: noqa
# pylint: disable=too-many-instance-attributes
class OCScale(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
resource_name,
namespace,
... |
"""Generate minimal requirements from `setup.py` + `requirements-devel.txt`."""
from __future__ import print_function
import argparse
import re
import sys
import mock
import pkg_resources
import setuptools
def parse_set(string):
"""Parse set from comma separated string."""
string = string.strip()
if ... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... |
"""
Represents a Vpn Gateway
"""
from boto.ec2.ec2object import TaggedEC2Object
class Attachment(object):
def __init__(self, connection=None):
self.vpc_id = None
self.state = None
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection)... |
import re
from StringIO import StringIO
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.db.models import Q
# from django.core import serializers
from django.core.serializers.json import Serializer
from opac.models import Book, BookCopy
class JSONSerializer(S... |
from mongoengine import *
from datetime import datetime
from mongoengine.base import BaseField
connect('infoneige')
class StreetProperties(EmbeddedDocument):
A = StringField()
SENS_CIR = IntField()
DE = StringField()
SUR = StringField()
TRC_ID = IntField()
class Street(Document):
trcId = IntField()
geometry ... |
# Example code for multicore example with python interface
# import python interface
import pysimulavr
if __name__ == "__main__":
# get systemclock instance
print "multicore example:"
sc = pysimulavr.SystemClock.Instance()
# create core A: clock generator 250Hz with device clock 4MHz
print " create cor... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import glob
import os
import re
import time
from threading import Thread
from cor... |
import random
def print_table():
lookup = ['-', 'X', 'O']
for row in T:
print ' '.join([lookup[cell] for cell in row])
print
def move(player, row, column):
global next_player
assert player == next_player, 'player not valid'
assert row in range(table_size), 'row out of range'
ass... |
'''
Create GCE resources for use in integration tests.
Takes a prefix as a command-line argument and creates two persistent disks named
${prefix}-base and ${prefix}-extra and a snapshot of the base disk named
${prefix}-snapshot. prefix will be forced to lowercase, to ensure the names are
legal GCE resource names.
'''
... |
class Rect:
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
class Pos:
def __init__(self, x, y):
self.x = x
self.y = y
class Dim:
def __init__(self, w, h):
self.w = w
self.h = h
def rect_center(r):
return Pos... |
"""Unit tests for filter.py."""
import webkitpy.thirdparty.unittest2 as unittest
from filter import _CategoryFilter as CategoryFilter
from filter import validate_filter_rules
from filter import FilterConfiguration
# On Testing __eq__() and __ne__():
#
# In the tests below, we deliberately do not use assertEqual() or... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from six import iteritems
from ansible.errors import AnsibleError
from ansible.plugins.action import ActionBase
from ansible.utils.boolean import boolean
from ansible.utils.vars import isidentifier
class ActionModule(ActionBase)... |
"""Routines to handle adaption of legacy call signatures,
generation of deprecation notes and docstrings.
"""
from .. import util
def _legacy_signature(since, argnames, converter=None):
def leg(fn):
if not hasattr(fn, '_legacy_signatures'):
fn._legacy_signatures = []
fn._legacy_signa... |
import unittest
from test import support
import __future__
GOOD_SERIALS = ("alpha", "beta", "candidate", "final")
features = __future__.all_feature_names
class FutureTest(unittest.TestCase):
def test_names(self):
# Verify that all_feature_names appears correct.
given_feature_names = features[:]
... |
"""
Utilities to convert integers and binary strings to binary (number), binary
string, number, hexadecimal, etc.
"""
from hachoir_core.endian import BIG_ENDIAN, LITTLE_ENDIAN, MIDDLE_ENDIAN
from hachoir_core.compatibility import reversed
from itertools import chain, repeat
from struct import calcsize, unpack, error a... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'SocialToken.token'
db.alter_column('socialaccount_socialtoken', 'token', self.gf('django.... |
from __future__ import unicode_literals
import logging
import sys
import warnings
from functools import wraps
from django.conf import settings
from django.core import signals
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.http import Http404
from django.http.multipartparser impor... |
"""
Stratified Plume Model: Lake simulation
========================================
Use the ``TAMOC`` `stratified_plume_model` to simulate a lake aeration plume.
This script demonstrates the typical steps involved in running the single
bubble model with reactive (dissolving) particles.
This simulation uses the am... |
#! /usr/bin/env python
# linktree
#
# Make a copy of a directory tree with symbolic links to all files in the
# original tree.
# All symbolic links go to a special symbolic link at the top, so you
# can easily fix things if the original source tree moves.
# See also "mkreal".
#
# usage: mklinks oldtree newtr... |
'''
High-level editor interface that communicates with underlying editor (like
Espresso, Coda, etc.) or browser. Basically, you should call set_context(obj)
method to set up undelying editor context before using any other method.
This interface is used by zen_actions.py for performing different
actions like Expand ab... |
"""utilities for Pylint configuration :
* pylintrc
* pylint.d (PYLINTHOME)
"""
from __future__ import with_statement
from __future__ import print_function
import pickle
import os
import sys
from os.path import exists, isfile, join, expanduser, abspath, dirname
# pylint home is used to save old runs results #########... |
#!/usr/bin/env python
import os
import tarfile
from contextlib import closing
from gppylib.commands.base import ExecutionError
from gppylib.operations.test.regress.test_package import GppkgTestCase, unittest, RPMSpec, GppkgSpec, run_command, OS, GPDB_VERSION
class QueryTestCase(GppkgTestCase):
"""Test the query ... |
"""Functions for establishing a test stream that sends out continuous artificial stimulus data"""
import pylsl
import time
import random
import threading
def repopulate_list(template_list):
"""Creates a shuffled deep copy of a template list."""
new_list = []
for item in template_list:
new_list.app... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from feedjack import models
class SiteAdmin(admin.ModelAdmin):
list_display = 'url', 'name'
filter_vertical = 'links',
admin.site.register(models.Site, SiteAdmin)
class PostProcessorTagInline(admin.T... |
"""Module to host the ChangeGitBranch class and test_git_executable function.
"""
import os
import subprocess
import misc_utils
class ChangeGitBranch(object):
"""Class to manage git branches.
This class allows one to create a new branch in a repository based
off of a given commit, and restore the origi... |
######################################################################
#
# PduOutle7930tDevice modeler plugin
#
######################################################################
__doc__="""PduOutlet7930Device
PduOutlet7930Device maps Outlets and states to connected Devices
$Id: $"""
__version__ = '$Revision: $... |
"""
Collection of unit tests for 'infra.libs.memoize' library.
"""
import unittest
from infra_libs import memoize
class MemoTestCase(unittest.TestCase):
def setUp(self):
self.tagged = set()
def tag(self, tag=None):
self.assertNotIn(tag, self.tagged)
self.tagged.add(tag)
def assertTagged(self, *t... |
from os import listdir, makedirs
from os.path import join
from lxml.etree import (PythonElementClassLookup, XMLParser, tostring, fromstring, CommentBase, Comment,
Element, SubElement, parse, ParseError, ElementTree, CustomElementClassLookup)
from .exceptions import MissingFileError, ParserError,... |
import zipfile, os, subprocess
from .main import read, translate, writeToJar
from .jvm.optimization import options
def getStubs():
with zipfile.ZipFile('tests/stubs/stubs.zip', 'r') as stubs:
for name in stubs.namelist():
yield (name, stubs.read(name))
STUB_FILES = dict(getStubs())
def execut... |
import warnings
from django.template import Library, defaulttags
from django.utils.deprecation import RemovedInDjango20Warning
register = Library()
@register.tag
def cycle(parser, token):
"""
This is the future version of `cycle` with auto-escaping.
The deprecation is now complete and this version is no... |
import oemedical_pathology_category
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from constants import DUST_DENSITY_COEFF, ALPHA, N, K
from math import sqrt, exp, pi
class CircumstellarDustLane:
def __init__(self, inner_edge, outer_edge, dust_present, gas_present):
self.inner = inner_edge
self.outer = outer_edge
self.dust_present = dust_present
self.gas_present... |
"""Tests for google.protobuf.descriptor_pool."""
__author__ = '<EMAIL> (Matt Toia)'
import unittest
from google.protobuf import descriptor_pb2
from google.protobuf.internal import factory_test1_pb2
from google.protobuf.internal import factory_test2_pb2
from google.protobuf import descriptor
from google.protobuf impor... |
# pylint: skip-file
# flake8: noqa
def main():
''' ansible oc module for labels '''
module = AnsibleModule(
argument_spec=dict(
kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
state=dict(default='present', type='str',
choices=[... |
import shutil
from collections import defaultdict
from io import BytesIO
from flask import flash, jsonify, request, session
from PIL import Image
from werkzeug.exceptions import Forbidden
from indico.core import signals
from indico.core.db import db
from indico.core.errors import UserValueError
from indico.modules.ca... |
''' TraceEventImporter imports TraceEvent-formatted data
into the provided model.
This is a port of the trace event importer from
https://code.google.com/p/trace-viewer/
'''
import copy
import json
import re
import telemetry.timeline.async_slice as tracing_async_slice
import telemetry.timeline.flow_event as tracing_f... |
"""Utilities for use with the base interface of RPC Framework."""
import collections
from grpc.framework.interfaces.base import base
class _Completion(
base.Completion,
collections.namedtuple(
'_Completion', ('terminal_metadata', 'code', 'message',))):
"""A trivial implementation of base.Completio... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ReliefColorsWidget.py
---------------------
Date : December 2016
Copyright : (C) 2016 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*****... |
# -*- coding: utf-8 -*-
import os
from ..test_managercli import TestCliProxyCommand
from subscription_manager import managercli
from subscription_manager.cli_command.abstract_syspurpose import AbstractSyspurposeCommand
from ..stubs import StubUEP
from ..fixture import Capture
from mock import patch, Mock, MagicMock... |
#! /usr/bin/env python
"""Minimum distance calculator node.
__author__ Denise Ratasich
__date__ 2017-09-25
"""
import roslib
import rospy
from sensor_msgs.msg import LaserScan
from additional_msgs.msg import Float32Stamped
_node_name = 'dmin_calculator'
"""Name of this node in the ROS system."""
_pub = None
"""Pu... |
# docstrings not neede here (the type handler floaterfaces are fully
# documented in base.py) pylint: disable-msg=C0111
from .base import ReturnValue, Parameter, \
ReverseWrapperBase, ForwardWrapperBase
from .ctypeparser import parse_type
class FloatParam(Parameter):
DIRECTIONS = [Parameter.DIRECTION_IN]
... |
import numpy as np
def featureNormalize(X):
"""
returns a normalized version of X where
the mean value of each feature is 0 and the standard deviation
is 1. This is often a good preprocessing step to do when
working with learning algorithms.
"""
X_norm, mu, sigma = 0,0,0
# ... |
#!/usr/bin/env python
# Built-in packages
import argparse
import logging
# Add-on packages
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import SingleLetterAlphabet
# McLab Packages
import mclib_Python as mclib
def getOptions():
"""Function to pull in comman... |
"""Vault secrets engines endpoints"""
from hvac.api.secrets_engines.aws import Aws
from hvac.api.secrets_engines.azure import Azure
from hvac.api.secrets_engines.identity import Identity
from hvac.api.secrets_engines.kv import Kv
from hvac.api.secrets_engines.kv_v1 import KvV1
from hvac.api.secrets_engines.kv_v2 import... |
#@PydevCodeAnalysisIgnore
import sys, os
import ctypes
# find_library(name) returns the pathname of a library, or None.
if os.name == "nt":
def find_library(name):
# See MSDN for the REAL search order.
for directory in os.environ['PATH'].split(os.pathsep):
fname = os.path.join(directory... |
"""
==============================================
Plot randomly generated classification dataset
==============================================
Plot several randomly generated 2D classification datasets.
This example illustrates the :func:`datasets.make_classification`
:func:`datasets.make_blobs` and :func:`datasets.... |
import unittest
import numpy
import chainer
from chainer import cuda
import chainer.functions as F
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
from chainer.testing import parameterize
from chainer.utils import conv
def _pair(x... |
"""TLS Lite + Twisted."""
from twisted.protocols.policies import ProtocolWrapper, WrappingFactory
from twisted.python.failure import Failure
from AsyncStateMachine import AsyncStateMachine
from tlslite.TLSConnection import TLSConnection
from tlslite.errors import *
import socket
import errno
#The TLSConnection is ... |
from DDEXUI.ddex.ddex import DDEX
from DDEXUI.ddex.resource import Resource
from DDEXUI.ddex.release import ReleaseIdType
class DDEXBuilder:
def __init__(self):
self._resources = []
self._releases = []
self._sender = None
self._recipient = None
self._is_update = None
de... |
import pytest
from ...tests.helper import assert_quantity_allclose, quantity_allclose
from ... import units as u
from .. import Longitude, Latitude, EarthLocation
from ..sites import get_builtin_sites, get_downloaded_sites, SiteRegistry
def test_builtin_sites():
reg = get_builtin_sites()
greenwich = reg['gr... |
import unittest
from planout.assignment import Assignment
from planout.ops.random import UniformChoice
class AssignmentTest(unittest.TestCase):
tester_unit = 4
tester_salt = 'test_salt'
def test_set_get_constant(self):
a = Assignment(self.tester_salt)
a.foo = 12
self.assertEqual(... |
""" Abstract base class for all window actions. """
# Enthought library imports.
from pyface.window import Window
from traits.api import Instance
# Local imports.
from pyface.action.action import Action
class WindowAction(Action):
""" Abstract base class for all window actions. """
#### 'WindowAction' int... |
'''
ListView tests
==============
'''
import unittest
from kivy.uix.label import Label
from kivy.adapters.listadapter import ListAdapter
from kivy.adapters.simplelistadapter import SimpleListAdapter
from kivy.uix.listview import ListItemButton, ListView
class ListViewTestCase(unittest.TestCase):
def setUp(self... |
from __future__ import absolute_import
import logging
from django.http import HttpResponseBadRequest, Http404
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_GET
from django.core.exceptions import PermissionDenied
from django.conf import settings
from opaque_... |
import logging
from django.contrib.admin.views.decorators import staff_member_required
from glue import Epoxy, API_EXCEPTION_AUTH, API_EXCEPTION_FORMERRORS, API_EXCEPTION_DOESNOTEXIST, API_EXCEPTION_HTTPERROR
from observer.models import DocumentProfile, Device, Property, DocumentProfile_Properties
from observer.form... |
#!/usr/bin/env python3
import sys
import re
def entry_is_device(entry):
first_arg_type = entry[1][1:].split(' ')[0]
device_types = ['VkDevice', 'VkCommandBuffer', 'VkQueue']
return (first_arg_type in device_types) and (entry[0] != 'vkGetDeviceProcAddr')
def main():
pure_entrypoints = []
entrypoin... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.encoding import smart_str
import mimetypes
import os
class ServerBase(object):
"""
Server classes define a way to serve a Django File object.
Warning: this API is EXPERIMENTAL and may change at any time.
"""
def g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.