content stringlengths 4 20k |
|---|
from oslo.config import cfg
import testtools
from testtools import matchers
from neutron.common import exceptions as q_exc
from neutron.db import api as db
from neutron.plugins.linuxbridge.db import l2network_db_v2 as lb_db
from neutron.tests import base
from neutron.tests.unit import test_db_plugin as test_plugin
PH... |
from tests.support import RpgTestCase
from rpg import Base
from rpg.command import Command
import os
class BuildTest(RpgTestCase):
def test_rpg_project(self):
self.base = Base()
self.base.sack = self.base.load_dnf_sack()
self.base.load_plugins()
self.base.load_project_from_url(
... |
from muntjac.demo.sampler.ExampleUtil import ExampleUtil
from muntjac.event.dd.acceptcriteria.server_side_criterion import \
ServerSideCriterion
from muntjac.terminal.gwt.client.ui.dd.vertical_drop_location import \
VerticalDropLocation
from muntjac.api import HorizontalLayout, Table
from muntjac.ui.table im... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_system_firmware_upgrade
except ImportErr... |
# Common stuff for process trackers.
from cli import *
def str2cpu(str):
try:
cpu = SIM_get_object(str)
except:
print "There is no object named '%s'." % str
return None
if SIM_object_is_processor(cpu):
return cpu
print "%d is not a processor." % str
return None
def... |
# -*- 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):
# Adding field 'GeneratedCertificate.mode'
db.add_column('certificates_generatedcertificate', 'mode',
... |
import os
import shlex
from subprocess import Popen, PIPE
import time
import unittest
import utils
class TestCase(unittest.TestCase):
@classmethod
def setenv(cls, env):
cls.env = env
def assertContains(self, b, a):
self.assertIn(a, b)
class MultiDict(dict):
def __getattr__(self, name):
v = s... |
"""Utilities for making samples.
Consolidates a lot of code commonly repeated in sample applications.
"""
__author__ = '<EMAIL> (Joe Gregorio)'
__all__ = ['init']
import argparse
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import file
from oauth2clien... |
import time
from six.moves.http_cookiejar import (
CookieJar as _CookieJar, DefaultCookiePolicy, IPV4_RE
)
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.python import to_native_str
class CookieJar(object):
def __init__(self, policy=None, check_expired_frequency=10000):
self.policy... |
"""
Module for setting and validating the presto-admin config
"""
from functools import wraps
import pprint
import re
import socket
import fabric
from fabric.api import task, env, runs_once
from fabric.context_managers import settings
from prestoadmin import config
from prestoadmin.util import constants
from prestoad... |
"""
PostgreSQL database backend for Django.
Requires psycopg 1: http://initd.org/projects/psycopg1
"""
import sys
from django.db import utils
from django.db.backends import *
from django.db.backends.signals import connection_created
from django.db.backends.postgresql.client import DatabaseClient
from django.db.backe... |
# Python's term for passing arguments to functions is "call by object".
# What does that mean?
# It's easy to overcomplicate, so don't. When an argument is passed to
# a function, the function's namespace binds its parameter name to the
# passed argument in the same way that any other assignment is handled.
# This mea... |
"""
This module provides an interface to the Elastic Compute Cloud (EC2)
CloudWatch service from AWS.
The 5 Minute How-To Guide
-------------------------
First, make sure you have something to monitor. You can either create a
LoadBalancer or enable monitoring on an existing EC2 instance. To enable
monitoring, you ca... |
"""
Twisted Factory, BGP implementation.
"""
import time
import os
import logging
import socket
import platform
import struct
import sys
import netaddr
from twisted.internet import protocol
from twisted.internet import reactor
from oslo.config import cfg
from yabgp.core.protocol import BGP
from yabgp.core.fsm import... |
import netrc, os, unittest, sys
from test import test_support
TEST_NETRC = """
machine foo login log1 password pass1 account acct1
macdef macro1
line1
line2
macdef macro2
line3
line4
default login log2 password pass2
"""
temp_filename = test_support.TESTFN
class NetrcTestCase(unittest.TestCase):
def setUp (... |
"""Tests for compute service with multiple compute nodes."""
from oslo.config import cfg
from nova import context
from nova.openstack.common import importutils
from nova import test
from nova.virt import fake
CONF = cfg.CONF
CONF.import_opt('compute_manager', 'nova.service')
CONF.import_opt('compute_driver', 'nova.... |
"""Driver for starting up Google Mock class generator."""
__author__ = '<EMAIL> (Neal Norwitz)'
import os
import sys
if __name__ == '__main__':
# Add the directory of this script to the path so we can import gmock_class.
sys.path.append(os.path.dirname(__file__))
from cpp import gmock_class
# Fix the docstr... |
from __future__ import print_function
import atexit
import contextlib
import errno
import os
import shutil
import stat
import sys
import tempfile
import threading
import zipfile
from collections import defaultdict
from uuid import uuid4
def die(msg, exit_code=1):
print(msg, file=sys.stderr)
sys.exit(exit_code)
... |
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Event(models.Model):
# Oracle can have problems with a column named "date"
date = models.DateField(db_column="event_date")
class Parent(models.Model):
name = models.CharField(max_length=128)
class Child(mo... |
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = """
options:
provider:
description:
- A dict object containing connection details.
default: null
suboptions:
host:
description:
- Specifies the DNS host name or address for conne... |
"""Test some code in the test base module to make sure it really works."""
import io
import tempfile
import typing
from django.test import TestCase
from .. import ca_settings
from ..extensions import AuthorityInformationAccess
from ..extensions import AuthorityKeyIdentifier
from ..extensions import BasicConstraints
... |
#! /bin/usr/python
from random import shuffle
import consul
from KVwrapper import retrieve_remote_snapshot_metadata, update_remote_metadata, get_server_list, get_node_meta
from Utils import dataset_name, get_latest_snapshot
from plugin.SanoidBackupPlugin import SanoidBackupPlugin
"""
Generic backup plugin
- Allow t... |
import os, sys, inspect, thread, time
# src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# arch_dir = '../lib/x64' if sys.maxsize > 2**32 else '../lib/x86'
# sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
import Leap
from Leap import CircleGesture, KeyTapGesture, ScreenTapGestur... |
import argparse
import os
import re
import subprocess
import sys
from xml.dom import minidom
from common import InputError
from common import write_files
# Global variables
args = None # Parsed command-line arguments.
def _parse_trans_unit(trans_unit):
"""Converts a trans-unit XML node into a more convenient di... |
import os
import sys
import ctypes
import logging
import msvc_details
from ctypes import *
from ctypes.wintypes import ULONG
from ctypes.wintypes import DWORD
from ctypes.wintypes import BOOL
from ctypes.wintypes import BYTE
from ctypes.wintypes import WORD
from ctypes.wintypes import UINT
sys.path.append( r'../..' )
... |
#!/usr/bin/env python
__all__ = ['tumblr_download']
from ..common import *
from .universal import *
from .dailymotion import dailymotion_download
from .vimeo import vimeo_download
from .vine import vine_download
def tumblr_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
if re.match(r'https?... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import json
import traceback
from functools import partial
try:
import boto3
impor... |
"""
Support for Rflink lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.rflink/
"""
import asyncio
import logging
from homeassistant.components import group
from homeassistant.components.light import (
ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS... |
from lxml import etree
import webob
import webob.dec
import webob.exc
from nova.api import ec2
from nova import context
from nova import exception
from nova.openstack.common import cfg
from nova.openstack.common import timeutils
from nova import test
CONF = cfg.CONF
@webob.dec.wsgify
def conditional_forbid(req):
... |
from cache_manager import CacheManager
from externmodules.semantic.virtuoso_webservice import SemanticService
class SEMANTIC(CacheManager):
def _init_strategy(self):
eq = [
"0 0 0 0 0 0 0 0 0 0 0", "0 1 1 1 0 0 1 0 0 0 0", "0 0 1 1 0 0 1 0 0 0 0",
"0 0 1 0 0 0 1 0 0 0 0", "0... |
#! /usr/bin/env python
# Set default parameters for GeoNet
# Reporting, plotting and file handling
doFileOutput = 1
doReport = 1
doPlot = 0
doResetFiguresOnStart = 1
# **** Default parameters for Perona-Malik nonlinear diffusion
# ... could be: PeronaMalik1, PeronaMalik2, Tukey, rampPreserving
diffusionMethod = 'Per... |
import bisect
PAGE_SIZE = 4096
class Map(object):
"""Models the memory map of a given |backends.Process|.
This is typically obtained by calling backends.Process.DumpMemoryMaps()."""
def __init__(self):
self.entries = [] # List of |MapEntry|, sorted by start address.
def Add(self, entry):
assert(... |
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
"""
Used for gis.specific migration tests.
"""
operations = [
migrations.CreateModel(
name='Neighborhood',
fields=[
('id', models.A... |
#Chien Kai Wang, Brian Wan, William Chen
#TCP CHAT CLIENT
import pyaudio
import sys
import socket
import select
import time
from array import array
from struct import pack
msgType = 0
check = 0
receive = 0
ALPHA_LOWER = ['a', 'b', 'c', 'd', 'e', 'f', 'g', ' ', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', ... |
from __future__ import division
version = '0.9.5' |
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 exist on AppEngine.
select = False
def is_connection_dr... |
#
#
from __future__ import division, print_function, absolute_import
__all__ = ['expm','expm2','expm3','cosm','sinm','tanm','coshm','sinhm',
'tanhm','logm','funm','signm','sqrtm',
'expm_frechet', 'expm_cond', 'fractional_matrix_power']
from numpy import (Inf, dot, diag, exp, product, logical_no... |
DATE_FORMAT = r'j-E, Y-\y\i\l'
TIME_FORMAT = 'G:i'
DATETIME_FORMAT = r'j-E, Y-\y\i\l G:i'
YEAR_MONTH_FORMAT = r'F Y-\y\i\l'
MONTH_DAY_FORMAT = 'j-E'
SHORT_DATE_FORMAT = 'd.m.Y'
SHORT_DATETIME_FORMAT = 'd.m.Y H:i'
FIRST_DAY_OF_WEEK = 1 # Monday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see... |
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.ruby as ruby
import logging
import re
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
v2_library = gapic.ruby_library(
'dlp', 'v2', config_p... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'supported_by': 'community',
'status': ['preview']
}
DOCUMENTATION = r'''
---
module: postgresql_query
short_description: Run PostgreSQL queries
description:
- Runs arbit... |
from django.test import TestCase
from .taggit_extras.models import Food
class NamespacedTaggableManagerTest(TestCase):
food_model = Food
def assert_tags_equal(self, qs, tags, sort=True, attr="name"):
got = map(lambda tag: getattr(tag, attr), qs)
if sort:
got.sort()
ta... |
"""
This software is an implementation of
Deep MRI brain extraction: A 3D convolutional neural network for skull stripping
You can download the paper at http://dx.doi.org/10.1016/j.neuroimage.2016.01.024
If you use this software for your projects please cite:
Kleesiek and Urban et al, Deep MRI brain extraction: A 3... |
from test.vim_test_case import VimTestCase as _VimTest
from test.constant import *
from test.util import running_on_windows
class _ExpandTabs(_VimTest):
def _extra_vim_config(self, vim_config):
vim_config.append("set sw=3")
vim_config.append("set expandtab")
class RecTabStopsWithExpandtab_Simple... |
#! /usr/bin/env python
# Released to the public domain, by Tim Peters, 03 October 2000.
"""reindent [-d][-r][-v] [ path ... ]
-d (--dryrun) Dry run. Analyze, but don't make any changes to, files.
-r (--recurse) Recurse. Search for all .py files in subdirectories too.
-n (--nobackup) No backup. Does not make a... |
"""Mailcap file handling. See RFC 1524."""
import os
__all__ = ["getcaps","findmatch"]
# Part 1: top-level interface.
def getcaps():
"""Return a dictionary containing the mailcap database.
The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain')
to a list of dictionaries corresponding to ... |
import ConfigParser
class Config:
def __init__(self, cfg):
"""@param cfg: configuration file."""
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read(cfg)
for section in config.sections():
for name, raw_value in config.items(section):
if n... |
"""arg_scope tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.framework.python.ops import add_arg_scope
from tensorflow.contrib.framework.python.ops import arg_scope
from tensorflow.contrib.framework.python.ops import arg_sco... |
from openerp import models, fields
class StockLocation(models.Model):
"""
Add the area dimension and the unit of measure of the warehouse locations.
By default, the unit of measure is the one of the user's company.
Add a boolean for the form view in order to display or not area
dimensions fields.
... |
from __future__ import division
import numpy
from chainer import backend
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
def _infer_lines(B, C, H, W, out_H, out_W, kH, kW):
target_size = 2 ** 17
line_size = B * C * (H * W // out_H + kH * kW * out_W)
... |
import unittest
import pmt
class test_gruel_pmt_to_python(unittest.TestCase):
def test01 (self):
b = pmt.pmt_from_double(123765)
self.assertEqual(pmt.to_python(b), 123765)
t = pmt.to_pmt(range(5))
if __name__ == '__main__':
unittest.main() |
"""Ops for pfor, for_loop, jacobian."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ops.parallel_for import * # pylint: disable=wildcard-import
from tensorflow.python.ops.parallel_for.control_flow_ops import for_loop
from tensorf... |
import logging
import os
import random
from teuthology.suite import matrix
log = logging.getLogger(__name__)
def build_matrix(path, subset=None, seed=None):
"""
Return a list of items descibed by path such that if the list of
items is chunked into mincyclicity pieces, each piece is still a
good subs... |
"""Verify perf_expectations.json can be loaded using simplejson.
perf_expectations.json is a JSON-formatted file. This script verifies
that simplejson can load it correctly. It should catch most common
formatting problems.
"""
import subprocess
import sys
import os
import unittest
import re
simplejson = None
def ... |
"""
Combiner for GRUB v1 and v2 configurations
==========================================
Combiner for Red Hat Grub v1 and Grub v2 information.
This combiner uses both the Grub1Config and the Grub2Config parsers.
It determines which parser was used by checking the class attribute in shared.
When the appropriate Grub p... |
from __future__ import division
import sys, random, math, datetime, time,re
sys.dont_write_bytecode = True
from base import *
def rank_simple(vector):
return sorted(range(len(vector)), key=vector.__getitem__)
def rankdata(a):
n = len(a)
ivec=rank_simple(a)
svec=[a[rank] for rank in ivec]
sumranks... |
"""Tests for base.api_fixer."""
import json
import pickle
import unittest2
import yaml
import api_fixer
class BadPickle(object):
"""Dummy object."""
def __reduce__(self):
return tuple([eval, tuple(['[1][2]'])])
class ApiFixerTest(unittest2.TestCase):
"""Test cases for base.api_fixer."""
def testJsonE... |
import sys, os, string
JSON_DIR = string.rstrip(__file__, (os.sep + os.path.basename(__file__)))
JSON_DIR += os.sep + '..' + os.sep + 'third-party' + os.sep + 'python'
# Include in sys path
if JSON_DIR not in sys.path:
sys.path.append(JSON_DIR)
# Import required libraries
import json, urllib
# Vtiger Webservice C... |
"""
These are the unittests for the pycbc.filter.matchedfilter module
"""
import sys
import pycbc
import unittest
from pycbc.types import *
from pycbc.scheme import *
from pycbc.filter import *
from math import sqrt
import pycbc.fft
import numpy
from utils import parse_args_all_schemes, simple_exit
_scheme, _context =... |
import base64
import cStringIO
import string
import struct
import dns.exception
import dns.rdata
import dns.rdatatype
b32_hex_to_normal = string.maketrans('0123456789ABCDEFGHIJKLMNOPQRSTUV',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567')
b32_normal_to_hex = string.maketrans('ABCDEFGHIJKLMNOP... |
from Bio.Sequencing.Applications import (
BwaAlignCommandline,
BwaSampeCommandline,
BwaSamseCommandline,
BwaBwaswCommandline,
)
import pipes
import logging
from biopipes.samtools import (
sam_to_ubam,
sort_bam,
index_bam,
)
def fastq_to_sai(index, read_file, args={}, debug=False, pipeli... |
""" Class to handle source code management repositories. """
import subprocess
try:
import git
HAS_GITPYTHON = True
except ImportError:
HAS_GITPYTHON = False
# GitPython is a bit too unstable currently
HAS_GITPYTHON = False
class InvalidSCMError(Exception):
""" Exception for when trying to access a r... |
from openerp.osv import fields, osv
class make_invoice(osv.osv_memory):
_name = 'mrp.repair.make_invoice'
_description = 'Make Invoice'
_columns = {
'group': fields.boolean('Group by partner invoice address'),
}
def make_invoices(self, cr, uid, ids, context=None):
""" Generates... |
"""Tests for distutils.dist."""
from distutils import sysconfig
import os
import unittest
from test.test_support import TESTFN
class SysconfigTestCase(unittest.TestCase):
def test_get_config_h_filename(self):
config_h = sysconfig.get_config_h_filename()
self.assert_(os.path.isfile(config_h), con... |
import os
import unittest
import sys
import PyFBA
test_file_loc = os.path.dirname(os.path.realpath(__file__))
class TestFBA(unittest.TestCase):
modeldata = PyFBA.parse.model_seed.parse_model_seed_data('gramnegative', verbose=True)
media = PyFBA.parse.pyfba_media(media_name="ArgonneLB", modeldata=modeldata, ... |
import dns.rdtypes.mxbase
class AFSDB(dns.rdtypes.mxbase.UncompressedDowncasingMX):
"""AFSDB record
@ivar subtype: the subtype value
@type subtype: int
@ivar hostname: the hostname name
@type hostname: dns.name.Name object"""
# Use the property mechanism to make "subtype" an alias for the
... |
from __future__ import absolute_import, division, print_function
from collections import Iterable
from datashape import DataShape
from odo.utils import copydoc
from .expressions import Expr, ndim, symbol
__all__ = 'Transpose', 'TensorDot', 'dot', 'transpose', 'tensordot'
class Transpose(Expr):
""" Transpose di... |
from osv import fields, osv
import decimal_precision as dp
class hr_contract_be(osv.osv):
_inherit = 'hr.contract'
_columns = {
'travel_reimbursement_amount': fields.float('Reimbursement of travel expenses', digits_compute=dp.get_precision('Payroll')),
'car_company_amount': fields.float('Compa... |
#!/usr/bin/env python
import json
import apsw
from playhouse.apsw_ext import *
from redis import Redis
class RedisModule(object):
def __init__(self, db):
self.db = db
def Create(self, db, modulename, dbname, tablename, *args):
schema = 'CREATE TABLE %s (rowid, key, value, type, parent);'
... |
from sqlalchemy import Boolean, Column, DateTime
from sqlalchemy import MetaData, Integer, String, Table, ForeignKey
from cinder.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
# New table
quota_class... |
from datetime import timedelta, date
from django.template import Template, Context, add_to_builtins
from django.utils import unittest
from django.utils.dateformat import DateFormat
from django.utils.translation import ugettext as _
from django.utils.html import escape
add_to_builtins('django.contrib.humanize.template... |
"""
Main command group for Rasterio's CLI.
Subcommands developed as a part of the Rasterio package have their own
modules under ``rasterio.rio`` (like ``rasterio/rio/info.py``) and are
registered in the 'rasterio.rio_commands' entry point group in
Rasterio's ``setup.py``:
entry_points='''
[console_scripts... |
""" Test functions for linalg module
"""
import numpy as np
from numpy.testing import *
from numpy import array, single, double, csingle, cdouble, dot, identity
from numpy import multiply, atleast_2d, inf, asarray, matrix
from numpy import linalg
from numpy.linalg import matrix_power, norm, matrix_rank
def ifthen(a, ... |
"""Common operations on Posix pathnames.
Instead of importing this module directly, import os and refer to
this module as os.path. The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, an... |
data = (
'Shu ', # 0x00
'Luo ', # 0x01
'Qi ', # 0x02
'Yi ', # 0x03
'Ji ', # 0x04
'Zhe ', # 0x05
'Yu ', # 0x06
'Zhan ', # 0x07
'Ye ', # 0x08
'Yang ', # 0x09
'Pi ', # 0x0a
'Ning ', # 0x0b
'Huo ', # 0x0c
'Mi ', # 0x0d
'Ying ', # 0x0e
'Meng ', # 0x0f
'Di ', ... |
from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.event import event
from flexget.manager import Session
from flexget.utils import imdb
from flexget.utils.log import log_once
try:
# TODO: Fix this after api_tmdb has module level functions
... |
"""
XFields for video module.
"""
import datetime
from xblock.fields import Scope, String, Float, Boolean, List, Dict, DateTime
from xmodule.fields import RelativeTime
# Make '_' a no-op so we can scrape strings
_ = lambda text: text
class VideoFields(object):
"""Fields for `VideoModule` and `VideoDescriptor`.... |
"""Various utilities common to nibabel release and maintenance tools.
"""
# Library imports
import os
import sys
from distutils.dir_util import remove_tree
# Useful shorthands
pjoin = os.path.join
cd = os.chdir
# Utility functions
def c(cmd):
"""Run system command, raise SystemExit if it returns an error."""
... |
import base64
from Crypto.Hash import HMAC
from Crypto import Random
from muranorepository.openstack.common.gettextutils import _ # noqa
from muranorepository.openstack.common import importutils
class CryptoutilsException(Exception):
"""Generic Exception for Crypto utilities."""
message = _("An unknown er... |
""" Solution to the second puzzle of Day 19 on adventofcode.com
"""
import os
def main():
""" Spacechem medicine is a hell of a drug
"""
basedir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(basedir, 'input')
transforms = []
molecule = ''
with open(file_path, 'r')... |
#!/usr/bin/env python
import os
import sys
import numpy as np
import tensorflow as tf
import dataIO as d
from tqdm import *
from utils import *
'''
Global Parameters
'''
n_epochs = 10000
batch_size = 32
g_lr = 0.0025
d_lr = 0.00001
beta = 0.5
d_thresh = 0.8
z_size = 200
leak_value = 0.2
cub... |
import math
import trep
from OpenGL.GL import *
import numpy as np
class PyPistonForce(trep.Force):
def __init__(self, system, crank_angle, offset, piston, curve):
trep.Force.__init__(self, system, name='%s-force' % piston)
# The combustion is modeled as a simple spline that is
# dependen... |
import os
import re
import json
import xml.etree.ElementTree as ET
from omsdk.typemgr.ClassType import *
from omdrivers.types.iDRAC.iDRAC import *
from omdrivers.types.iDRAC.BIOS import *
from omdrivers.types.iDRAC.RAID import *
from omdrivers.types.iDRAC.NIC import *
from omdrivers.types.iDRAC.FCHBA import *
from omdr... |
import os
import tempfile
import gtk
import mock
from stoqlib.database.settings import DatabaseSettings
from stoqlib.gui.test.uitestutils import GUITest
from stoq.gui.config import (DatabaseSettingsStep,
FirstTimeConfigWizard)
class MockDatabaseSettings(DatabaseSettings):
def has_da... |
import os
import json
from pyramid.response import Response
from pyramid.response import FileResponse
from pyramid.view import view_config
import pyramid.httpexceptions as httpexceptions
# database stuff
from sqlalchemy.exc import DBAPIError
from sqlalchemy import or_
from climasng.models import *
# json data stuff
... |
# Basically just a sanity check to make sure things don't change from underneath us.
from django.test import TestCase
from tastypie import http
class HttpTestCase(TestCase):
def test_201(self):
response = http.HttpCreated(location='http://example.com/thingy/1/')
self.assertEqual(response.status_c... |
import datetime
class ConditionalGetMiddleware(object):
"""
Handles conditional GET operations. If the response has a ETag or
Last-Modified header, and the request has If-None-Match or
If-Modified-Since, the response is replaced by an HttpNotModified.
Removes the content from any response to a HEA... |
from .base import Browser, ExecutorBrowser, require_arg
from ..webdriver_server import ChromeDriverServer
from ..executors import executor_kwargs as base_executor_kwargs
from ..executors.executorselenium import (SeleniumTestharnessExecutor, # noqa: F401
SeleniumRefTestExecutor... |
from multiprocessing import Process
from multiprocessing import Queue
import signal
import six
import threading
import time
import traceback
from neutron.agent import firewall
from oslo_log import log as logging
from oslo_vmware import exceptions as vmware_exceptions
from networking_vsphere._i18n import _LI
from netw... |
r"""This module implements IO and manipulation function for discrete trajectories
Discrete trajectories are generally ndarrays of type integer
We store them either as single column ascii files or as ndarrays of shape (n,) in binary .npy format.
.. moduleauthor:: B. Trendelkamp-Schroer <benjamin DOT trendelkamp-schroe... |
import re
import pytest
import responses
@pytest.fixture
def app(monkeypatch):
monkeypatch.setenv('MAILJET_API_KEY', 'apikey')
monkeypatch.setenv('MAILJET_API_SECRET', 'apisecret')
monkeypatch.setenv('MAILJET_SENDER', 'sender')
import main
main.app.testing = True
return main.app.test_client... |
#!/usr/bin/env python
import sys
from os import path,getcwd
def run(verbosity=1,doctest=False,numpy=True):
"""Run NetworkX tests.
Parameters
----------
verbosity: integer, optional
Level of detail in test reports. Higher numbers provide more detail.
doctest: bool, optional
True to... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import unified_strdate
class ATTTechChannelIE(InfoExtractor):
_VALID_URL = r'https?://techchannel\.att\.com/play-video\.cfm/([^/]+/)*(?P<id>.+)'
_TEST = {
'url': 'http://techchannel.att.com/play-video.cfm/2014/1/27... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from ansible.modules.network.eos import eos_eapi
from units.modules.utils import set_module_args
from .eos_module import TestEosModule, load_fixture
class TestEosEapiModule(TestEosModul... |
#!/usr/bin/python
# write an experiment that creates a new control program.
import os
import sys
import copy
BOREALISPATH = os.environ['BOREALISPATH']
sys.path.append(BOREALISPATH)
from experiment_prototype.experiment_prototype import ExperimentPrototype
import experiments.superdarn_common_fields as scf
class Twof... |
import io
import logging
import sys
from contextlib import contextmanager
from sqlalchemy import MetaData, Table, Column, String, literal_column
from sqlalchemy import create_engine
from sqlalchemy.engine import url as sqla_url
from .compat import callable, EncodedIO
from . import ddl, util
log = logging.getLogger(... |
"""Matches two images using their DELF features.
The matching is done using feature-based nearest-neighbor search, followed by
geometric verification using RANSAC.
The DELF features can be extracted using the extract_features.py script.
"""
from __future__ import absolute_import
from __future__ import division
from ... |
from msrest.serialization import Model
class PoolStopResizeOptions(Model):
"""Additional parameters for stop_resize operation.
:param timeout: The maximum time that the server can spend processing the
request, in seconds. The default is 30 seconds. Default value: 30 .
:type timeout: int
:param c... |
# -*- coding: utf-8 -*-
'''
importer libs
~~~~~~~~~~~~~
pre-installed libraries (for override).
:author: Sam Gammon <<EMAIL>>
:license: This software follows the MIT (OSI-approved)
license for open source software. A truncated
version is included here; for full licens... |
import webob
from wormhole import exception
from wormhole import wsgi
from wormhole.tasks import addtask
from wormhole.common import utils
from wormhole.common import units
from oslo.config import cfg
from wormhole.common import log
import functools
import uuid
import os
CONF = cfg.CONF
LOG = log.getLogger(__name__... |
from antlr4.tree.ParseTreePatternMatcher import ParseTreePatternMatcher
from antlr4.tree.Tree import ParseTree
from antlr4.xpath.XPath import XPath
class ParseTreePattern(object):
# Construct a new instance of the {@link ParseTreePattern} class.
#
# @param matcher The {@link ParseTreePatternMatcher} whic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.