content string |
|---|
from copy import deepcopy
from org.o3project.odenos.core.component.network.packet.in_packet import InPacket
from org.o3project.odenos.core.component.network.flow.ofpflow.ofp_flow_match\
import OFPFlowMatch
class OFPInPacket(InPacket):
def __init__(self, id_, type_, attributes,
node, port, h... |
"""Utilities for creating input_fns.
Contents of this file are moved to tensorflow/python/estimator/export.py.
InputFnOps is renamed to ServingInputReceiver.
build_parsing_serving_input_fn is renamed to
build_parsing_serving_input_receiver_fn.
build_default_serving_input_fn is renamed to
build_raw_serving_input_re... |
from __future__ import division
import itertools
import numpy as np
from six.moves import zip
from collections import OrderedDict
from bokeh.plotting import ColumnDataSource, figure, show, output_file
from bokeh.models import HoverTool
output_file("hover.html")
TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework import status
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.decorators import api_view
from reactor.models ... |
# converted to java and then to python by p.j.leonard
# based on C++ code found at
# http://www.codeproject.com/KB/recipes/BP.aspx?msg=2809798#xx2809798xx
import math
import random
import copy
import pickle
"""
multilayer neural network
"""
def sigmoid(x):
if x < -100.0: # avoid... |
BitStr DEFINITIONS ::=
BEGIN
-- F.2.5.1
-- Use a bit string type to model binary data whose format and
-- length are unspecified,
-- or specified elsewhere, and whose length in bits is not necessarily
-- a multiple of eight.
-- EXAMPLE
G3FacsimilePage ::= BIT STRING
-- a sequence of bits conforming to... |
from nose.tools import assert_equals
from trashcli.trash import TrashDir
from trashcli.trash import TrashDirectory
class TestTrashDir:
def test_path(self):
trash_dir = TrashDirectory('/Trash-501', '/')
assert_equals('/Trash-501', trash_dir.path)
class TestTrashDir_finding_orphans:
def test(sel... |
import numpy as np
import taichi as ti
@ti.all_archs
def test_1d():
x = ti.field(ti.f32, shape=(16))
@ti.kernel
def func():
for i in ti.ndrange((4, 10)):
x[i] = i
func()
for i in range(16):
if 4 <= i < 10:
assert x[i] == i
else:
asser... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_display_units06.x... |
from PyQt4.QtGui import *
from PyQt4.QtCore import *
# KDE imports
from PyKDE4.kdecore import *
from PyKDE4.kdeui import KIconLoader
import locale
class UCAbstractItemModel(QAbstractItemModel):
""" Item model for tree views in userconfig. Common elements for
users and groups.
"""
column_data = [... |
# -*- coding: utf-8 -*-
"""
shodan.client
~~~~~~~~~~~~~
This module implements the Shodan API.
:copyright: (c) 2014-2015 by John Matherly
"""
import requests
import simplejson
import time
import shodan.exception as exception
import shodan.helpers as helpers
import shodan.stream as stream
# Tr... |
"""
smartcard_setup.py - Used as a setup test for smartcard tests.
Before doing a remote viewer connection there is some setup required
for smartcard tests:
On the client, certs that will be put into the smartcard will need
to be generated.
"""
import logging
from autotest.client.shared import error
from virttest ... |
import stat_tree
tree = stat_tree.StatsTree('/tmp/thetree')
tree.write(0, ['foobar'], {'a': 0.1, 'c': 1, 'b': 1})
tree.write(1, ['foobar'], {'a': 0.1, 'c': 1, 'b': 2})
tree.write(2, ['foobar'], {'a': 0.1, 'c': 100, 'b': 3})
tree.write(3, ['foobar'], {'a': 0.1, 'c': 1, 'b': 4})
tree.write(0.0, ['tag1'], {'m1':500, 'm2... |
"""Functions to parse datetime objects."""
# We're using regular expressions rather than time.strptime because:
# - They provide both validation and parsing.
# - They're more flexible for datetimes.
# - The date/datetime/time constructors produce friendlier error messages.
import datetime
import re
from django.utils ... |
import msilib,os;dirname=os.path.dirname(__file__)
ActionText = [
(u'InstallValidate', u'Validating install', None),
(u'InstallFiles', u'Copying new files', u'File: [1], Directory: [9], Size: [6]'),
(u'InstallAdminPackage', u'Copying network install files', u'File: [1], Directory: [9], Size: [6]'),
(u'FileCost', u'C... |
import os
from couchpotato.core.event import addEvent
from couchpotato.core.helpers.variable import tryInt
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from couchpotato.environment import Env
log = CPLog(__name__)
autoload = 'ClientScript'
class ClientScript(Plugin):
... |
import numpy as np
from PyQt4 import QtCore, QtGui
import h5py
from utils import *
class DataStream():
def __init__(self, path, dataPath):
"""Initializes a HDF5 DataStream. PATH is the path to the
.hdf5 file, and DATAPATH is the path within the file to the
specific dataset.
"""
... |
""" Tests for commerce views. """
import json
from uuid import uuid4
from nose.plugins.attrib import attr
import ddt
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
import mock
from student.tests.factories import UserFactory
class UserMixin(object):
... |
from django.contrib import admin
from django.contrib.admin.options import ModelAdmin
from django.contrib.auth.models import User
from django.test import RequestFactory, TestCase
from .models import (
Band, DynOrderingBandAdmin, Song, SongInlineDefaultOrdering,
SongInlineNewOrdering,
)
class MockRequest:
... |
from scrapy import log, signals
from scrapy.exceptions import CloseSpider
from scrapy.http import Request
from scrapy.xlib.pydispatch import dispatcher
from dynamic_scraper.spiders.django_base_spider import DjangoBaseSpider
from dynamic_scraper.models import Scraper
class CheckerTest(DjangoBaseSpider):
name ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'zappyk'
import os, sys
from lib_zappyk import _setup
from QueryExecWebZI.xlsX2splits_sheets import _project, _description, _version
#CZ#project = 'QueryExecWebZI'
#CZ#name = __import__(project).get_project()
#CZ#description = __import__(project)... |
import inspect
import os
import types
def getmembers(_object, _predicate):
"""This is an implementation of inspect.getmembers, as in some versions
of python it may be buggy.
See issue at http://bugs.python.org/issue1785"""
# This should be:
#return inspect.getmembers(_object, _predicate)
# ...... |
# Boris Borcic 2006
# Quick and concise Python 2.5 sudoku solver
#
# Adapted for Brython by Pierre Quentel
# load pre-computed tables
import json
data = json.loads(open('sudoku.json').read())
w2q = data['w2q']
q2w = data['q2w']
w2q2w = data['w2q2w']
class Completed(Exception) : pass
def sudoku99(problem) :
given... |
try:
from cs import CloudStack, CloudStackException, read_config
has_lib_cs = True
except ImportError:
has_lib_cs = False
# import cloudstack common
from ansible.module_utils.cloudstack import *
class AnsibleCloudStackNetwork(AnsibleCloudStack):
def __init__(self, module):
super(AnsibleCloud... |
from __future__ import absolute_import
import fluent.syntax.ast as FTL
from fluent.migrate.helpers import transforms_from
from fluent.migrate.helpers import VARIABLE_REFERENCE, TERM_REFERENCE
from fluent.migrate import REPLACE, COPY
trailhead = "firefox/new/trailhead.lang"
def migrate(ctx):
"""Migrate bedrock/fir... |
"""Support for AquaLogic sensors."""
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
PERCENTAGE,
POWER_WATT,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.core import callback
import homeassista... |
import unittest
import config
import node
LEADER = 1
ROUTER = 2
class TestCoaps(unittest.TestCase):
def setUp(self):
self.simulator = config.create_default_simulator()
self.nodes = {}
for i in range(1, 3):
self.nodes[i] = node.Node(i, simulator=self.simulator)
self.... |
import tensorflow as tf
import numpy as np
from ionotomo.settings import TFSettings
from ionotomo import *
from ionotomo.ionosphere.iri import a_priori_model
import astropy.coordinates as ac
import astropy.units as au
import astropy.time as at
def calc_rays_and_initial_model(antennas,directions,times,zmax=1000.,res_n... |
"""
File: SCPIBase.py
Author: Wouter Vlothuizen, TNO/QuTech
Purpose: self contained base class for SCPI ('Standard Commands for Programmable Instruments') commands, with
selectable transport
Usage: don't use directly, use a derived class (e.g. Qutech_CC)
Notes:
... |
"""Contains an abstract base class for protocol messages."""
__author__ = '<EMAIL> (Will Robinson)'
class Error(Exception): pass
class DecodeError(Error): pass
class EncodeError(Error): pass
class Message(object):
"""Abstract base class for protocol messages.
Protocol message classes are almost always genera... |
#!/usr/bin/env python3
import re
import sys
import shutil
import os.path
import subprocess
import sysconfig
import reindent
import untabify
SRCDIR = sysconfig.get_config_var('srcdir')
def n_files_str(count):
"""Return 'N file(s)' with the proper plurality on 'file'."""
return "{} file{}".format(count, "s" ... |
#!/usr/bin/python
from math import *
from pymavlink.rotmat import Vector3, Matrix3
from numpy import linspace
from visual import *
class Quat:
def __init__(self,w=1.0,x=0.0,y=0.0,z=0.0):
self.w = w
self.x = x
self.y = y
self.z = z
def to_euler(self):
roll = (atan2(2.0*... |
from __future__ import print_function
import sys
import re
import itk
import os
from optparse import OptionParser
parser = OptionParser(usage='wrappingCoverage.py paths')
parser.add_option(
"-b",
"--base",
dest="base",
default="Filter",
help="Base string used to search for the classes (default: F... |
from __future__ import absolute_import, division, print_function
import sys
__all__ = ['PY3', 'b', 'basestring_', 'bytes', 'next', 'is_unicode',
'iteritems']
PY3 = True if sys.version_info[0] == 3 else False
if sys.version_info[0] < 3:
def next(obj):
return obj.next()
def iteritems(d, *... |
"""Common NHNet/Bert2Bert configuration."""
from typing import List, Text
import dataclasses
from official.modeling.hyperparams import base_config
@dataclasses.dataclass
class BERT2BERTConfig(base_config.Config):
"""High-level configurations for BERT2BERT model.
These include parameters that are not directly ... |
import unittest
from scrapy.spiders import Spider
from scrapy.utils.url import url_is_from_any_domain, url_is_from_spider, canonicalize_url
__doctests__ = ['scrapy.utils.url']
class UrlUtilsTest(unittest.TestCase):
def test_url_is_from_any_domain(self):
url = 'http://www.wheele-bin-art.co.uk/get/produc... |
"""Scheduling learning rate."""
import logging
from math import cos, pi
class LRScheduler(object):
"""Base class of a learning rate scheduler.
A scheduler returns a new learning rate based on the number of updates that have
been performed.
Parameters
----------
base_lr : float, optional
... |
#!/usr/bin/env python
#
# by Saviour Emmanuel
from xml.dom import minidom
class NMAP_XMLParser(object):
def __init__(self,file_path):
self._xml_object = object()
self._xml_path = file_path
self._output_path = str()
self._csv_string = str()
self._open_xml()
def _open_xm... |
# -*- coding: utf-8 -*-
import xbmc,xbmcgui
try:
from YDStreamExtractor import getVideoInfo
from YDStreamExtractor import handleDownload
except Exception:
print 'importing Error. You need youtubedl module which is in official xbmc.org'
xbmc.executebuiltin("XBMC.Notification(LiveStreamsPro,Please [C... |
"""
Django admin commands related to verify_student
"""
import logging
import os
from pprint import pformat
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from lms.djangoapps.verify_student.models import ManualVerification
from lms.djangoapps.verify_stude... |
import csv
from urllib.request import Request, urlopen
import dateutil.parser
import re
from os import system
from sys import argv
from bs4 import BeautifulSoup
from datetime import date
import scrape_util
default_sale, base_url, prefix = scrape_util.get_market(argv)
default_sale = default_sale[0]
report_path = 'mar... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.forms import ModelForm
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True)... |
"""
Scheduler Service
"""
import sys
from nova.compute import rpcapi as compute_rpcapi
from nova.compute import utils as compute_utils
from nova.compute import vm_states
import nova.context
from nova import db
from nova import exception
from nova import manager
from nova import notifications
from nova.openstack.commo... |
"""Analyzes text using the Google Cloud Natural Language API."""
import argparse
import json
import sys
import googleapiclient.discovery
def get_native_encoding_type():
"""Returns the encoding type that matches Python's native strings."""
if sys.maxunicode == 65535:
return 'UTF16'
else:
... |
# -*- coding: utf-8 -*-
"""
pygments.formatters.svg
~~~~~~~~~~~~~~~~~~~~~~~
Formatter for SVG output.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.formatter import Formatter
from pygments.util import get_bool_opt, get... |
from __future__ import absolute_import
from __future__ import print_function
import os
import tarfile
import tempfile
from twisted.internet import defer
from twisted.python import log
from buildbot_worker.commands.base import Command
class TransferCommand(Command):
def finished(self, res):
if self.deb... |
#!/usr/bin/python
import h5py
import sys
import numpy as np
import os
import re
import random
# find the path to my own python function:
cur_dir=os.getcwd()
sep='test_cases'
test_DIR=cur_dir.split(sep,1)[0]
scriptDIR=test_DIR+'compare_function'
sys.path.append(scriptDIR)
# import my own function for color and comparat... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
HAVE_SEOBJECT = False
try:
import seobject
HAVE_SEOBJECT = True
except ImportError:
pass
from ansible.module_utils.basic import *
from ansible.module_utils.pycompat24 import get... |
"""Utilities for training the dependency parser.
You do not need to read/understand this code
"""
import time
import os
import logging
from collections import Counter
from general_utils import logged_loop, get_minibatches
from q2_parser_transitions import PartialParse, minibatch_parse
import numpy as np
P_PREFIX = ... |
#!/usr/bin/env python2
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <EMAIL>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import (
QDialog, Qt, QPixmap, QIcon, QSize, QVBoxLayout, QHBoxLayout, QLabel,
QCheckBox, QDialogButtonBox)
from calibre import confirm_config_name
from calibre.gui2... |
import time
import unittest
import config
import node
LEADER = 1
ROUTER1 = 2
ROUTER2 = 3
ROUTER3 = 4
ED = 5
class Cert_6_1_3_RouterAttachConnectivity(unittest.TestCase):
def setUp(self):
self.simulator = config.create_default_simulator()
self.nodes = {}
for i in range(1,6):
s... |
import unittest
from trac.core import TracError
from trac.test import EnvironmentStub, MockRequest
from trac.versioncontrol.web_ui.changeset import ChangesetModule
class ChangesetModuleTestCase(unittest.TestCase):
def setUp(self):
self.env = EnvironmentStub()
self.cm = ChangesetModule(self.env)
... |
"""
Unit tests for the course_mode signals
"""
from datetime import datetime, timedelta
from mock import patch
import ddt
from pytz import UTC
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from course_modes.models import CourseMod... |
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
LOG = logging.getLogger(__name__)
class CreateNetwork(forms.SelfHandlingFor... |
from unittest import skipUnless
from django.contrib.gis import forms
from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geos import GEOSGeometry
from django.forms import ValidationError
from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature
from django.utils.html import escape... |
"""Graph-only versions of a few op functions, for internal use only."""
# Must be separate from array_ops to avoid a cyclic dependency.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.framework import attr_value_pb2
from tensorflow.pyt... |
import functools
import os.path
import re
import tornado.escape
import tornado.web
import tornado.wsgi
import unicodedata
from google.appengine.api import users
from google.appengine.ext import db
class Entry(db.Model):
"""A single blog entry."""
author = db.UserProperty()
title = db.StringProperty(requi... |
from test_framework.test_framework import BitcoinTestFramework
class TestShell:
"""Wrapper Class for BitcoinTestFramework.
The TestShell class extends the BitcoinTestFramework
rpc & daemon process management functionality to external
python environments.
It is a singleton class, which ensures tha... |
import codecs
import os.path
import re
from setuptools import setup
from setuptools import find_packages
def find_version(*file_paths):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, *file_paths), 'r') as f:
version_file = f.read()
version_match = re.search(r... |
from webkitpy.tool.steps.abstractstep import AbstractStep
from webkitpy.tool.steps.options import Options
class SuggestReviewers(AbstractStep):
@classmethod
def options(cls):
return AbstractStep.options() + [
Options.git_commit,
Options.suggest_reviewers,
]
def run... |
"""
Django settings for informationLayer8 project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
... |
import pyautogui, time
from color import color_from_mouse
def keypress(key):
pyautogui.keyDown(key)
time.sleep(.5)
pyautogui.keyUp(key)
def save():
keypress('enter')
keypress('up')
keypress('up')
keypress('up')
keypress('x')
keypress('x')
keypress('x')
keypress('x')#spams x to assure that the saving proces... |
# import cloudstack common
from ansible.module_utils.cloudstack import *
class AnsibleCloudStackLBRuleMember(AnsibleCloudStack):
def __init__(self, module):
super(AnsibleCloudStackLBRuleMember, self).__init__(module)
self.returns = {
'publicip': 'public_ip',
'algorithm': 'a... |
from django.core.management.base import BaseCommand
from django.contrib.comments.models import Comment, FreeComment
from threadedcomments.models import ThreadedComment, FreeThreadedComment
class Command(BaseCommand):
help = "Migrates Django's built-in django.contrib.comments data to threadedcomments data"
... |
"""Self-test suite for Cryptodome.Hash.SHAKE128 and SHAKE256"""
import unittest
from binascii import hexlify, unhexlify
from Cryptodome.SelfTest.loader import load_tests
from Cryptodome.SelfTest.st_common import list_test_cases
from StringIO import StringIO
from Cryptodome.Hash import SHAKE128, SHAKE256
fr... |
import random
import unittest
from p2pool import data
from p2pool.bitcoin import data as bitcoin_data
from p2pool.test.util import test_forest
from p2pool.util import forest
def random_bytes(length):
return ''.join(chr(random.randrange(2**8)) for i in xrange(length))
class Test(unittest.TestCase):
def test_h... |
"""Tests for learn.dataframe.transforms.sparsify and densify."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.learn.python.learn.dataframe.transforms import densify
from tensorflow.contrib.learn.python.learn.da... |
"""
XX. Model inheritance
Model inheritance exists in two varieties:
- abstract base classes which are a way of specifying common
information inherited by the subclasses. They don't exist as a separate
model.
- non-abstract base classes (the default), which are models in their own
right with ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: fetch
short_description: Fetch files from remote nodes
de... |
from __future__ import print_function
from __future__ import absolute_import
from Components.Converter.Converter import Converter
from Components.Element import cached
from Components.config import configfile
class ConfigEntryTest(Converter, object):
def __init__(self, argstr):
Converter.__init__(self, argstr)
a... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'DiffWindow.ui'
#
# by: PyQt4 UI code generator 4.7.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_DiffWindow(object):
def setupUi(self, DiffWindow):
DiffWindow.setObject... |
import fnmatch
import os
import shutil
import six
from django.core.management import call_command
from django.test import TestCase
from django_extensions.management.utils import get_project_root
class CleanPycTests(TestCase):
def setUp(self):
self._settings = os.environ.get('DJANGO_SETTINGS_MODULE')
... |
from six import integer_types
from cantrips.types.exception import factory
from .features import TornadoTimerFeature, TwistedTimerFeature, ThreadedTimerFeature
class Timeout(object):
"""
Lets a timeout be triggered and cancelled. If the timeout is reached,
an exception is triggered.
Notes: Processo... |
########################################################################
# File: FTSSiteTests.py
########################################################################
""" :mod: FTSSiteTests
==================
.. module: FTSSiteTests
:synopsis: unittest for FTSSite class
.. moduleauthor:: <EMAIL>
... |
"""
Package :mod:`openquake.hazardlib.calc` contains hazard calculator modules
and utilities for them, such as :mod:`~openquake.hazardlib.calc.filters`.
"""
from openquake.hazardlib.calc.hazard_curve import hazard_curves_poissonian
from openquake.hazardlib.calc.gmf import ground_motion_fields
from openquake.hazardlib.c... |
import os
from lxml import etree
from django.conf import settings
from ConfigParser import SafeConfigParser
from owslib.iso import MD_Metadata
from pycsw import server
from geonode.catalogue.backends.generic import CatalogueBackend as GenericCatalogueBackend
from geonode.catalogue.backends.generic import METADATA_FORMA... |
"""Admin settings for the CMS news app."""
from django.contrib import admin
from cms.admin import PageBaseAdmin
from cms.apps.news.models import Category, Article
class CategoryAdmin(PageBaseAdmin):
"""Admin settings for the Category model."""
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
... |
"""
Course Textbooks page.
"""
import requests
from path import Path as path
from ..common.utils import click_css
from .course_page import CoursePage
class TextbooksPage(CoursePage):
"""
Course Textbooks page.
"""
url_path = "textbooks"
def is_browser_on_page(self):
return self.q(css='b... |
import random
from Tkinter import *
root = Tk()
print("")
print("Welcome to Blob Rage Beta 2")
print("Instructions:")
print("To kill blobs you click them until they are dead. You do 2.5 damage to a blob on contact.")
print("")
print("Blobs:")
print("Green Blob: 10 to 50 health, and speed equals a range of -2 to 2.")
p... |
import logging
import threading
import time
import psycopg2
from datetime import datetime
from dateutil.relativedelta import relativedelta
import pytz
import openerp
from openerp import SUPERUSER_ID, netsvc, api
from openerp.osv import fields, osv
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from openerp.t... |
"""Extend OptionParser with commands.
Example:
>>> parser = OptionParser()
>>> parser.usage = '%prog COMMAND [options] <arg> ...'
>>> parser.add_command('build', 'mymod.build')
>>> parser.add_command('clean', run_clean, add_opt_clean)
>>> run, options, args = parser.parse_command(sys.argv[1:])
>>> return run(options,... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.onyx import onyx_l3_interface
from units.modules.utils import set_module_args
from .onyx_module import TestOnyxModule, load_fixture
class TestOnyxL3InterfaceModule(... |
"""
gateway tests - argument errors in gateway methods
"""
from omero.gateway import _BlitzGateway
import pytest
class TestArgumentErrors(object):
@classmethod
@pytest.fixture(autouse=True)
def setup_class(cls, tmpdir, monkeypatch):
ice_config = tmpdir / "ice.config"
ice_config.write... |
"""Frechet derivative of the matrix exponential."""
from __future__ import division, print_function, absolute_import
import numpy as np
import scipy.linalg
__all__ = ['expm_frechet', 'expm_cond']
def expm_frechet(A, E, method=None, compute_expm=True, check_finite=True):
"""
Frechet derivative of the matrix ... |
#! /usr/bin/env python2
from __future__ import print_function
from argparse import ArgumentParser
from pdb import pm
from future.utils import viewitems
from miasm.loader import pe_init
from miasm.loader.strpatchwork import StrPatchwork
from miasm.core import parse_asm, asmblock
from miasm.analysis.machine import Mach... |
from __future__ import print_function
import sys, os
import logging, logging.handlers
from ginga import AstroImage
from ginga.gtkw import FileSelection, GtkHelp
from ginga.gtkw.ImageViewCanvasGtk import ImageViewCanvas
from ginga import colors
import gtk
STD_FORMAT = '%(asctime)s | %(levelname)1.1s | %(filename)s:%(... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.six.moves.urllib.parse import urlencode
fr... |
from __future__ import division, absolute_import, print_function
import math
from .info import __doc__
from numpy.version import version as __version__
from .type_check import *
from .index_tricks import *
from .function_base import *
from .nanfunctions import *
from .shape_base import *
from .stride_tricks import *... |
from calaccess_raw.admin.base import BaseAdmin
from calaccess_raw.admin.campaign import (
CvrSoCdAdmin,
Cvr2SoCdAdmin,
CvrCampaignDisclosureCdAdmin,
Cvr2CampaignDisclosureCdAdmin,
RcptCdAdmin,
Cvr3VerificationInfoCdAdmin,
LoanCdAdmin,
S401CdAdmin,
ExpnCdAdmin,
F495P2CdAdmin,
... |
#!bin/python
import os
import re
import shutil
import subprocess
username="wehnerj"
sortstring="8PNPO12"
#sortstring=None
apename="APE_ISO"
workground="WORKGROUND"
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.core import checks
from django.core.exceptions import FieldDoesNotExist
from django.db import models
class CurrentSiteManager(models.Manager):
"Use this to limit objects to those associated with the curre... |
from collections import OrderedDict
from typing import Dict, Type
from .base import RegionInstancesTransport
from .rest import RegionInstancesRestTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[RegionInstancesTransport]]
_transport_registry["rest"] = RegionIn... |
"""Implementation of compose command for Google Cloud Storage."""
from __future__ import absolute_import
from gslib.bucket_listing_ref import BucketListingObject
from gslib.command import Command
from gslib.command_argument import CommandArgument
from gslib.cs_api_map import ApiSelector
from gslib.encryption_helper i... |
from .context import Context
from .events import Events
class SocketBase(object):
def __init__(self, zmq_socket_type, context=None):
self._context = context or Context.get_instance()
self._events = Events(zmq_socket_type, context)
def close(self):
self._events.close()
def connec... |
# -*- coding: utf-8 -*-
"""
MiniTwit Tests
~~~~~~~~~~~~~~
Tests the MiniTwit application.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import os
import minitwit
import tempfile
import pytest
@pytest.fixture
def client(request):
db_fd, minitwit.app.... |
###########################################
# Suppress matplotlib user warnings
# Necessary for newer version of matplotlib
import warnings
warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib")
#
# Display inline matplotlib plots with IPython
from IPython import get_ipython
get_ipython().run_... |
"""
=======================================
Visualizing the stock market structure
=======================================
This example employs several unsupervised learning techniques to extract
the stock market structure from variations in historical quotes.
The quantity that we use is the daily variation in quote ... |
from __future__ import absolute_import, print_function
__all__ = ['FilterManager', 'FilterNotRegistered']
import six
class FilterNotRegistered(Exception):
pass
# TODO(dcramer): a lot of these managers are very similar and should abstracted
# into some kind of base class
class FilterManager(object):
def __... |
""" Module defining the Django auth backend class for the Keystone API. """
import datetime
import logging
import pytz
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from keystoneclient import exceptions as keystone_exceptions
from openstack_auth import exceptions
from opens... |
# Django settings for photob project.
import os
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
path = lambda *a: os.path.join(ROOT, *a)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAGERS = ADMINS
from postgresify import postgresify
DATABASES = postgresify(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.