content
stringlengths
4
20k
## @package seq2seq_util # Module caffe2.python.examples.seq2seq_util """ A bunch of util functions to build Seq2Seq models with Caffe2.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import collections from futur...
from case import Case class Case1_2_4(Case): DESCRIPTION = """Send binary message message with payload of length 127.""" EXPECTATION = """Receive echo'ed binary message (with payload as sent). Clean close with normal code.""" def onOpen(self): payload = "\xfe" * 127 self.expected[Case...
from base64 import b64encode from collections import namedtuple from socket import error as SocketError try: from select import poll, POLLIN except ImportError: # `poll` doesn't exist on OSX and other platforms poll = False try: from select import select except ImportError: # `select` doesn't...
#!/usr/bin/env python # -*- coding: utf-8 -*- from api import FM_API from Queue import Queue, Full from pySmartDL import SmartDL as pydl import pyglet as pg class FM_Controller(object): def __init__(self): self.agent = FM_API() self.player = Player() qsize = 10 self.queue = Queue...
"""Test for preservation of unknown fields in the pure Python implementation.""" __author__ = '<EMAIL> (Bohdan Koval)' import unittest from google.protobuf import unittest_mset_pb2 from google.protobuf import unittest_pb2 from google.protobuf.internal import encoder from google.protobuf.internal import test_util from...
#!/usr/bin/env python3 """Class for normalizing the data read from YAML files.""" import os import yaml # Switchmap-NG imports from switchmap.utils import log class Translator(object): """Process configuration file for a host. The aim of this class is to process the YAML file consistently across multi...
""" Run the unit tests for Signal """ from __future__ import absolute_import import random from myhdl import instance, instances random.seed(1) # random, but deterministic def A(n): @instance def logic(): yield None return logic def B(n): @instance def logic(): yield None ...
import os import pty import re import select import subprocess import sys import threading try: from Queue import Empty from Queue import Queue except ImportError: # python 3.x from queue import Empty from queue import Queue class Executer(object): def __init__(self, component): self...
""" ================= Cluster centroids ================= An illustration of the cluster centroids method. """ print(__doc__) import matplotlib.pyplot as plt import seaborn as sns sns.set() # Define some color for the plotting almost_black = '#262626' palette = sns.color_palette() from sklearn.datasets import mak...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Album', fields=[ ('id', models.AutoField(verbos...
from __future__ import absolute_import from __future__ import with_statement import os import sys import tempfile from libcloud import _init_once from libcloud.test import LibcloudTestCase from libcloud.test import unittest from libcloud.compute.ssh import ParamikoSSHClient from libcloud.compute.ssh import ShellOutSS...
# TODO(okuta): Implement norm # TODO(okuta): Implement cond # TODO(okuta): Implement det # TODO(okuta): Implement matrix_rank # TODO(okuta): Implement slogdet def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): """Returns the sum along the diagonals of an array. It computes the sum along ...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class KaraoketvIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?karaoketv\.co\.il/[^/]+/(?P<id>\d+)' _TEST = { 'url': 'http://www.karaoketv.co.il/%D7%A9%D7%99%D7%A8%D7%99_%D7%A7%D7%A8%D7%99%D7%95%D7%A7%D7%99...
""" Created on November 25, 2011 @author: sbobovyc """ """ Copyright (C) 2011 Stanislav Bobovych 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, o...
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2009 (ita) """ Fixes for py3k go here """ import os all_modifs = {} def modif(dir, name, fun): if name == '*': lst = [] for y in '. Tools 3rdparty'.split(): for x in os.listdir(os.path.join(dir, y)): if x.endswith('.py'): lst.append(y + os.sep ...
"""A pure Python implementation of import.""" __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload'] # Bootstrap help ##################################################### # Until bootstrapping is complete, DO NOT import any modules that attempt # to import importlib._bootstrap (directly or indirect...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from beeradcn import Beerad def pth(f): return 'data/' + f # check for encoding errors in foreign beer names # brute force appears to be all that's working def enc(s): return ''.join([x for x in s if ord(x) < 128]) def insert(cur, ins, tup, err): succ...
import global_settings as this from random import shuffle import math import copy def solvable(): if len(this.list_a) == 0: return False summation = 0 for i in range(len(this.list_a)): for j in range(i, len(this.list_a)): if(this.list_a[j] != 0 and this.list_a[j]<this.list_a[i]): summation += 1 if summ...
"""madapp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
from __future__ import unicode_literals import time import unittest from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import resolve from django.http import HttpResponse from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import require_...
# -*- coding: utf-8 -*- """ *************************************************************************** merge.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *********************************...
import MySQLdb as mdb import sys import time import socket import recolector user = 'root' # usuario con el que se entrara a la base de datos host = '192.168.56.2' # ip server db = 'gestion_red' #base de datos que se modificara # esto obtiene la ip del cliente s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.c...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.forms.utils import flatatt, ErrorDict, ErrorList from django.test import TestCase from django.utils.safestring import mark_safe from django.utils import six from django.utils.translation impor...
try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False def _needs_update(module, identity_provider): """Check for differences in the updatable values. Note: Names cannot be updated. """ params_dict = dict(remote_ids='remote_ids', enabled='enabled',...
from __future__ import unicode_literals import frappe from frappe import _ default_lead_sources = ["Existing Customer", "Reference", "Advertisement", "Cold Calling", "Exhibition", "Supplier Reference", "Mass Mailing", "Customer's Vendor", "Campaign", "Walk In"] def install(country=None): records = [ # domains ...
from unittest import TestCase from mock import Mock, patch from logging import Logger from pybuilder.plugins.python.pylint_plugin import check_pylint_availability class CheckPyLintAvailabilityTests(TestCase): @patch('pybuilder.plugins.python.pylint_plugin.assert_can_execute') def test_should_check_that_pyli...
from spack import * class Libusbmuxd(AutotoolsPackage): """A client library to multiplex connections from and to iOS devices.""" homepage = "https://www.libimobiledevice.org/" url = "https://www.libimobiledevice.org/downloads/libusbmuxd-1.0.10.tar.bz2" git = "https://git.libimobiledevice.or...
from __future__ import print_function import sys import os import argparse import subprocess import tempfile import shutil def compile(tmp_dir, sketch, tools_dir, hardware_dir, ide_path, f, args): cmd = ide_path + '/arduino-builder ' cmd += '-compile -logger=human ' cmd += '-build-path "' + tmp_dir + '" ' ...
"""Utilities for converting ODL operators to pytorch layers. This requires the ``torch`` module from the ``pytorch`` package, see `the pytorch installation guide <https://github.com/pytorch/pytorch#installation>`_ for instructions. """ from __future__ import division import warnings import numpy as np import torch ...
""" Tests of the LMS XBlock Mixin """ import ddt from nose.plugins.attrib import attr from lms_xblock.mixin import INVALID_USER_PARTITION_VALIDATION, INVALID_USER_PARTITION_GROUP_VALIDATION from xblock.validation import ValidationMessage from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.fa...
from __future__ import absolute_import, division, print_function, unicode_literals import itertools import logging from concurrent.futures import as_completed import jmespath from c7n.actions import BaseAction from c7n.exceptions import ClientError from c7n.filters import ( AgeFilter, Filter, CrossAccountAccessF...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db.models import Q from django.core.exceptions import ValidationError from cms.apphook_pool import apphook_pool from cms.models import Page from menus.base import Menu class CMSAttachMenu(Menu): cms_enabled = True instance = None ...
import pytest import re import time from subprocess import check_call from tests.common.impala_cluster import ImpalaCluster from tests.common.impala_test_suite import ImpalaTestSuite from tests.common.skip import SkipIfS3, SkipIfIsilon, SkipIfLocal from tests.common.test_dimensions import create_single_exec_option_dim...
from __future__ import absolute_import, division, print_function, with_statement import contextlib import glob import logging import os import re import subprocess import sys import tempfile import warnings from tornado.escape import utf8 from tornado.log import LogFormatter, define_logging_options, enable_pretty_log...
from __future__ import print_function import os import sys import warnings from setuptools import setup, extension from setuptools.command.build_ext import build_ext from setuptools.command.test import test as TestCommand setup_kwargs = {} def error(*lines): for line in lines: print(line, file=sys.stder...
import channel_construction as cc from channel_construction_bec import bhattacharyya_bounds from helper_functions import is_power_of_two CHANNEL_TYPE_AWGN = 'AWGN' CHANNEL_TYPE_BEC = 'BEC' def get_z_params(is_prototype, channel, block_size, design_snr, mu): print('POLAR code channel construction called with para...
from cloudbot.util.formatting import munge, dict_format, pluralize, strip_colors, truncate, truncate_str, \ strip_html, multi_replace, multiword_replace, truncate_words, smart_split, get_text_list, ireplace, chunk_str test_munge_input = "The quick brown fox jumps over the lazy dog" test_munge_count = 3 test_munge_...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.netv...
"""Remove cisco_vlan_bindings table Revision ID: b7a8863760e Revises: 3cabb850f4a5 Create Date: 2013-07-03 19:15:19.143175 """ # revision identifiers, used by Alembic. revision = 'b7a8863760e' down_revision = '3cabb850f4a5' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'n...
import xpcom from xpcom import components, nsError, _xpcom, logger class Factory: _com_interfaces_ = components.interfaces.nsIFactory # This will only ever be constructed via other Python code, # so we can have ctor args. def __init__(self, klass): self.klass = klass def createInstance(sel...
#!/usr/bin/env python from tools.load import LoadMatrix lm=LoadMatrix() traindat = lm.load_dna('../data/fm_train_dna.dat') testdat = lm.load_dna('../data/fm_test_dna.dat') label_traindat = lm.load_labels('../data/label_train_dna.dat') parameter_list=[[traindat,testdat,label_traindat,1,1e1, 1e0],[traindat,testdat,label...
from sqlparse import sql, tokens as T from sqlparse.utils import offset, indent class AlignedIndentFilter: join_words = (r'((LEFT\s+|RIGHT\s+|FULL\s+)?' r'(INNER\s+|OUTER\s+|STRAIGHT\s+)?|' r'(CROSS\s+|NATURAL\s+)?)?JOIN\b') by_words = r'(GROUP|ORDER)\s+BY\b' split_word...
from google.protobuf import text_format from tensorflow.core.framework import graph_pb2 from tensorflow.python.client import session from tensorflow.python.framework import graph_util from tensorflow.python.framework import importer from tensorflow.python.platform import gfile import tensorflow as tf import time def...
def main(request, response): import simplejson as json f = file('config.json') source = f.read() s = json.JSONDecoder().decode(source) url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1]) url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0]) _CSP = "default-src " + url1 ...
import threading import Queue import new def WorkerPoolError( Exception ): pass class WorkerPool( object ): def __init__( self, threadnum ): self.threadnum = threadnum self.q = Queue.Queue() self.ts = [ threading.Thread( target=self.run ) ...
# -*- coding: utf-8 -*- __license__ = 'GPL 3' __copyright__ = '2009, John Schember <<EMAIL>>' __docformat__ = 'restructuredtext en' import os from calibre.customize.conversion import OutputFormatPlugin, \ OptionRecommendation class TCROutput(OutputFormatPlugin): name = 'TCR Output' author = 'John Schem...
"""Module containing Apache Solr installation and cleanup functions.""" import posixpath import time from perfkitbenchmarker import vm_util SOLR_HOME_DIR = posixpath.join(vm_util.VM_TMP_DIR, 'solr-5.2.1') SOLR_TAR_URL = ('archive.apache.org/dist/lucene/solr/5.2.1/solr-5.2.1.tgz') def _Install(vm): """Installs th...
import django.forms from django.template import RequestContext from django.template.loader import render_to_string from IssueTracker.utils import issueHook import models, forms @issueHook("create") def issueCreate(request): """ Given request, render what extra stuff is needed for Machines """ args = {...
from __future__ import unicode_literals import inspect from rest_framework.serializers import ListSerializer from rest_framework.exceptions import ValidationError class EmbeddedListSerializer(ListSerializer): update_lookup_field = 'id' def update(self, queryset, all_validated_data): id_attr = getatt...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os.path import sys import tempfile import types import unittest from contextlib import contextmanager from django.template import Context, TemplateDoesNotExist from django.template.engine import Engine from django.test import SimpleTestCase, ignor...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import pytest from units.compat.mock import patch, MagicMock, mock_open from ansible.plugins.action.win_updates import ActionModule from ansible.playbook.task import Task class TestWinUpdatesActionPlugin(object): INVALID_OP...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Ansible module to manage Citrix NetScaler entities (c) 2013, Nandor Sivok <<EMAIL>> This file is part of Ansible Ansible 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 Foundat...
class ModuleDocFragment(object): DOCUMENTATION = """ options: - See respective platform section for more details requirements: - See respective platform section for more details notes: - Ansible modules are available for the following NetApp Storage Platforms: E-Series, ONTAP, SolidFire """ # Documentat...
from __future__ import division, print_function, absolute_import import numpy as np from copy import deepcopy from numpy.linalg import norm from numpy.testing import (TestCase, assert_array_almost_equal, assert_array_equal, assert_array_less, assert_raises, assert_e...
from DocXMLRPCServer import DocXMLRPCServer import httplib import sys from test import test_support threading = test_support.import_module('threading') import time import socket import unittest PORT = None def make_request_and_skipIf(condition, reason): # If we skip the test, we have to make a request...
#!/usr/bin/env python """ Sentry ====== Sentry is a realtime event logging and aggregation platform. It specializes in monitoring errors and extracting all the information needed to do a proper post-mortem without any of the hassle of the standard user feedback loop. Sentry is a Server ------------------ The Sentry ...
# -*- coding: utf-8 -*- """ equip.visitors.bytecode ~~~~~~~~~~~~~~~~~~~~~~~ Callback the visitor method for each encountered opcode. :copyright: (c) 2014 by Romain Gaucher (@rgaucher) :license: Apache 2, see LICENSE for more details. """ import opcode from ..utils.log import logger class BytecodeVisitor...
import json import unittest from fs.memoryfs import MemoryFS from mock import Mock, patch from xblock.field_data import DictFieldData from xblock.fields import ScopeIds from xmodule.error_module import NonStaffErrorDescriptor from opaque_keys.edx.locations import SlashSeparatedCourseKey, Location from xmodule.modules...
import wx from wxPython.wx import * import random import time import thread import socket import struct import string import os import sys import xml.dom.minidom import traceback import wx.lib.newevent import wx.lib.mixins.listctrl as listmix iDefaultAuthServerPort = 25101 sMetaverseServe...
import unittest from autothreadharness.harness_case import HarnessCase class REED_5_2_7(HarnessCase): role = HarnessCase.ROLE_REED case = '5 2 7' golden_devices_required = 16 def on_dialog(self, dialog, title): pass if __name__ == '__main__': unittest.main()
import unittest from unittest import mock from airflow.providers.google.marketing_platform.hooks.analytics import GoogleAnalyticsHook from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id WEB_PROPERTY_AD_WORDS_LINK_ID = "AAIIRRFFLLOOWW" WEB_PROPERTY_ID = "web_property_id" ...
"""Tests for distutils.util.""" import sys import unittest from test.test_support import run_unittest from distutils.errors import DistutilsByteCompileError from distutils.util import byte_compile, grok_environment_error class UtilTestCase(unittest.TestCase): def test_dont_write_bytecode(self): # makes ...
from nova.api.openstack import api_version_request from nova import exception from nova import test class APIVersionRequestTests(test.NoDBTestCase): def test_valid_version_strings(self): def _test_string(version, exp_major, exp_minor): v = api_version_request.APIVersionRequest(version) ...
import nest import unittest import numpy as np @nest.check_stack class RateCopyModelTestCase(unittest.TestCase): ''' Test whether a rate connection created by copy model behaves identical to the original version ''' def test_rate_copy_model(self): # neuron parameters neuron_para...
import unittest import shutil import os from test_common import javautils_script, get_config_file_list, \ get_actual_config, get_expected_config, DIRPATH from xml_compare import compare_xml_files class TestMvnConfig(unittest.TestCase): maxDiff = 2048 def setUp(self): self.olddir = os.getcwd(...
# -*- coding: utf-8 -*- """ Adding __str__() or __unicode__() to models Although it's not a strict requirement, each model should have a ``_str__()`` or ``__unicode__()`` method to return a "human-readable" representation of the object. Do this not only for your own sanity when dealing with the interactive prompt, but...
""" Distance and Area objects to allow for sensible and convienient calculation and conversions. Here are some tests. """ from django.contrib.gis.measure import Distance, Area, D, A from django.utils import unittest class DistanceTest(unittest.TestCase): "Testing the Distance object" def testInit(self): ...
# -*- coding: utf-8 -*- ''' Created on Mar 31, 2014 @author: alex ''' from spearmint_salad import salad, base, experiments_folder from spearmint_salad.analyze.analyze_trace import get_collection_structure from pkl_trace import TraceDBFile, get_column_dict import numpy as np from os import path from spearmint_salad....
import couchdb, os, logging, sys, collections from pprint import pprint import time import requests import copy # run in heroku by a) commiting, b) pushing to heroku, and c) running # heroku run python extras/db_housekeeping/merge_collections.py logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, ...
import contextlib import pytest from weasyl import media @contextlib.contextmanager def build_multi_get(expected_length): called = [] def multi_get(*keys): assert len(keys) == expected_length called.append(True) return keys yield multi_get assert called def test_populator...
from . import test_move_explode # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
__author__ = "Luis de Sousa" __date__ = "10-03-2015" import os import tempfile import unittest import lxml.etree import sys from pywps import Service, Process, ComplexInput, ComplexOutput, Format, FORMATS, get_format from pywps.dependencies import ogr from pywps.exceptions import NoApplicableCode from pywps import get...
from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.contrib.sites.models import Site from django.contrib.syndication.views import Feed, add_domain from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404 from django.utils.feedgenerator i...
"""A wrapper for the GStreamer Python bindings that exposes a simple music player. """ from __future__ import (division, absolute_import, print_function, unicode_literals) import sys import time import gobject import thread import os import copy import urllib import pygst pygst.require('0.10'...
{ 'name': 'Dates on Sales Order', 'version': '1.1', 'category': 'Sales Management', 'description': """ Add additional date information to the sales order. =================================================== You can add the following additional dates to a sales order: -----------------------------------...
# -*- coding: utf-8 -*- import os, re, sys, json, urllib, hashlib, traceback import xbmcup.app, xbmcup.db, xbmcup.system, xbmcup.net, xbmcup.parser, xbmcup.gui import xbmc, cover, xbmcplugin, xbmcgui from http import HttpData from common import Render from defines import * try: from sqlite3 import dbapi2 as sqlit...
from requestbuilder import Arg from euca2ools.commands.ec2 import EC2Request class DeleteVpnGateway(EC2Request): DESCRIPTION = 'Delete a virtual private gateway' ARGS = [Arg('VpnGatewayId', metavar='VGATEWAY', help='ID of the virtual private gateway to delete (required)')]
from functools import wraps from django.utils.decorators import available_attrs def xframe_options_deny(view_func): """ Modifies a view function so its response has the X-Frame-Options HTTP header set to 'DENY' as long as the response doesn't already have that header set. e.g. @xframe_optio...
"""add is_default to subnetpool Revision ID: 13cfb89f881a Revises: 59cb5b6cf4d Create Date: 2015-09-30 15:58:31.170153 """ # revision identifiers, used by Alembic. revision = '13cfb89f881a' down_revision = '59cb5b6cf4d' from alembic import op import sqlalchemy as sa from sqlalchemy import sql def upgrade(): o...
import unittest import json import trytond.tests.test_tryton from trytond.tests.test_tryton import POOL, USER, DB_NAME, CONTEXT from trytond.transaction import Transaction from nereid.testing import NereidTestCase class TestWebsite(NereidTestCase): 'Test Website' def setUp(self): trytond.tests.test_...
from __future__ import unicode_literals import frappe from frappe.utils import cint from frappe.model.naming import make_autoname from frappe import throw, _ from frappe.model.document import Document class HolidayList(Document): def validate(self): self.update_default_holiday_list() def get_weekly_off_dates(se...
# This script generates a Python interface for an Apple Macintosh Manager. # It uses the "bgen" package to generate C code. # The function specifications are generated by scanning the mamager's header file, # using the "scantools" package (customized for this particular manager). import string # Declarations that cha...
import functools from keystone.common import json_home from keystone.common import wsgi from keystone.federation import controllers build_resource_relation = functools.partial( json_home.build_v3_extension_resource_relation, extension_name='OS-FEDERATION', extension_version='1.0') build_parameter_relation =...
from keras.layers import Conv3D, Conv3DTranspose, UpSampling3D, Dense, Reshape, Flatten, Activation, Input from keras.models import Sequential from keras.layers.advanced_activations import LeakyReLU from keras_adversarial.legacy import l1l2 def em_generator(latent_dim, input_shape, leaky_alpha = 6*[0.2],reg = lambda: ...
import collections import re from nova import test from nova.virt.vmwareapi import vm_util ResultSet = collections.namedtuple('ResultSet', ['objects']) ResultSetToken = collections.namedtuple('ResultSet', ['objects', 'token']) ObjectContent = collections.namedtuple('ObjectContent', ['obj', 'propSet']) DynamicProperty...
# # Python script to generate BOM in multiple formats from a KiCad generic netlist. # import kicad_netlist_reader import os import csv class KicadBom: def __init__(self,netlist_path=None): self._netlist_ext = '.xml' self._netlist_path = None self._netlist = None self._grouped_compo...
import os from nose.tools import eq_ import mapnik from .utilities import execution_path, get_unique_colors, run_all def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() os.chdir(execution_path('.')) def test_dataraster_coloring(): srs...
from __future__ import unicode_literals import json from .common import InfoExtractor from ..compat import compat_urllib_request from ..utils import ( float_or_none, int_or_none, ) class CollegeRamaIE(InfoExtractor): _VALID_URL = r'https?://collegerama\.tudelft\.nl/Mediasite/Play/(?P<id>[\da-f]+)' _...
import mock import zvmsdk.utils as zvmutils from zvmsdk.tests.unit import base class ZVMUtilsTestCases(base.SDKTestCase): def test_convert_to_mb(self): self.assertEqual(2355.2, zvmutils.convert_to_mb('2.3G')) self.assertEqual(20, zvmutils.convert_to_mb('20M')) self.assertEqual(1153433.6, ...
"""Core event interfaces.""" from sqlalchemy import event, exc, util engine = util.importlater('sqlalchemy', 'engine') pool = util.importlater('sqlalchemy', 'pool') class DDLEvents(event.Events): """ Define event listeners for schema objects, that is, :class:`.SchemaItem` and :class:`.SchemaEvent` su...
import argparse from distutils.version import LooseVersion import json import os import sys from ipalib import api, errors, __version__ as IPA_VERSION from six import u def initialize(): ''' This function initializes the FreeIPA/IPA API. This function requires no arguments. A kerberos key must be present ...
#!/usr/bin/env python """ A library for computing local indicators of network-constrained clusters Author: Myunghwa Hwang <EMAIL> """ import unittest import numpy as np import scipy.stats as stats import geodanet.network as pynet import pysal, copy import time def unconditional_sim(event, base, s): """ Pa...
r""" ****************************** espressopp.esutil.GammaVariate ****************************** .. function:: espressopp.esutil.GammaVariate(alpha, beta) :param alpha: :param beta: :type alpha: :type beta: """ from espressopp import pmi from _espressopp import esutil_GammaVariate class GammaVariateLo...
import jsonschema from rally.plugins.common.sla import iteraion_time from tests.unit import test class IterationTimeTestCase(test.TestCase): def test_config_schema(self): properties = { "max_seconds_per_iteration": 0 } self.assertRaises(jsonschema.ValidationError, ...
#!/usr/bin/python # -*- coding: utf-8 -*- import os import re class State( object ): def __init__( self ,args=None ): if not args: pass #添加默认参数信息 else: self.args = list(args) self.rel = '/etc/redhat-release' self.verRe = re.compile("^(\d+(\.\d+)?)") ...
import argparse import sys import matplotlib import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec import numpy as np import json parser = argparse.ArgumentParser(description="Does some awesome things.") parser.add_argument('message', type=str, help="pass a message into the script") args = parser....
#!/usr/bin/env python # USB Serial support for CRI Spatial Light Modulator # import serial import os class SLM: """ Spatial Light Modulator """ def __init__(self, serialport=None): """ Create motor controller serial interface Input: serialport : name of the serial port (eg. '...
from openerp.osv import orm from openerp.tools.translate import _ class purchase_order(orm.Model): _inherit = "purchase.order" def fiscal_position_change( self, cr, uid, ids, fiscal_position, order_line, context=None): '''Function executed by the on_change on the fiscal_positi...
"""Basic test of all registered models.""" import tensorflow as tf # pylint: disable=unused-import import all_models # pylint: enable=unused-import from entropy_coder.model import model_factory class AllModelsTest(tf.test.TestCase): def testBuildModelForTraining(self): factory = model_factory.GetModelRegistr...
""" For the ``future`` package. Adds this import line:: from builtins import XYZ for each of the functions XYZ that is used in the module. Adds these imports after any other imports (in an initial block of them). """ from __future__ import unicode_literals from lib2to3 import fixer_base from lib2to3.pygram im...