repo_name stringlengths 5 100 | path stringlengths 4 294 | copies stringclasses 990
values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15
values |
|---|---|---|---|---|---|
40123151ChengYu/2015cd_midterm2 | static/Brython3.1.1-20150328-091302/Lib/multiprocessing/__init__.py | 693 | 6866 | #
# Package analogous to 'threading.py' but using processes
#
# multiprocessing/__init__.py
#
# This package is intended to duplicate the functionality (and much of
# the API) of threading.py but uses processes instead of threads. A
# subpackage 'multiprocessing.dummy' has the same API but is a simple
# wrapper for 'threading'.
#
# Try calling `multiprocessing.doc.main()` to read the html
# documentation in a webbrowser.
#
#
# Copyright (c) 2006-2008, R Oudkerk
# Licensed to PSF under a Contributor Agreement.
#
__version__ = '0.70a1'
__all__ = [
'Process', 'current_process', 'active_children', 'freeze_support',
'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger',
'allow_connection_pickling', 'BufferTooShort', 'TimeoutError',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
'Event', 'Barrier', 'Queue', 'SimpleQueue', 'JoinableQueue', 'Pool',
'Value', 'Array', 'RawValue', 'RawArray', 'SUBDEBUG', 'SUBWARNING',
]
__author__ = 'R. Oudkerk (r.m.oudkerk@gmail.com)'
#
# Imports
#
import os
import sys
from multiprocessing.process import Process, current_process, active_children
from multiprocessing.util import SUBDEBUG, SUBWARNING
#
# Exceptions
#
class ProcessError(Exception):
pass
class BufferTooShort(ProcessError):
pass
class TimeoutError(ProcessError):
pass
class AuthenticationError(ProcessError):
pass
import _multiprocessing
#
# Definitions not depending on native semaphores
#
def Manager():
'''
Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects.
'''
from multiprocessing.managers import SyncManager
m = SyncManager()
m.start()
return m
#brython fix me
#def Pipe(duplex=True):
# '''
# Returns two connection object connected by a pipe
# '''
# from multiprocessing.connection import Pipe
# return Pipe(duplex)
def cpu_count():
'''
Returns the number of CPUs in the system
'''
if sys.platform == 'win32':
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif 'bsd' in sys.platform or sys.platform == 'darwin':
comm = '/sbin/sysctl -n hw.ncpu'
if sys.platform == 'darwin':
comm = '/usr' + comm
try:
with os.popen(comm) as p:
num = int(p.read())
except ValueError:
num = 0
else:
try:
num = os.sysconf('SC_NPROCESSORS_ONLN')
except (ValueError, OSError, AttributeError):
num = 0
if num >= 1:
return num
else:
raise NotImplementedError('cannot determine number of cpus')
def freeze_support():
'''
Check whether this is a fake forked process in a frozen executable.
If so then run code specified by commandline and exit.
'''
if sys.platform == 'win32' and getattr(sys, 'frozen', False):
from multiprocessing.forking import freeze_support
freeze_support()
def get_logger():
'''
Return package logger -- if it does not already exist then it is created
'''
from multiprocessing.util import get_logger
return get_logger()
def log_to_stderr(level=None):
'''
Turn on logging and add a handler which prints to stderr
'''
from multiprocessing.util import log_to_stderr
return log_to_stderr(level)
#brython fix me
#def allow_connection_pickling():
# '''
# Install support for sending connections and sockets between processes
# '''
# # This is undocumented. In previous versions of multiprocessing
# # its only effect was to make socket objects inheritable on Windows.
# import multiprocessing.connection
#
# Definitions depending on native semaphores
#
def Lock():
'''
Returns a non-recursive lock object
'''
from multiprocessing.synchronize import Lock
return Lock()
def RLock():
'''
Returns a recursive lock object
'''
from multiprocessing.synchronize import RLock
return RLock()
def Condition(lock=None):
'''
Returns a condition object
'''
from multiprocessing.synchronize import Condition
return Condition(lock)
def Semaphore(value=1):
'''
Returns a semaphore object
'''
from multiprocessing.synchronize import Semaphore
return Semaphore(value)
def BoundedSemaphore(value=1):
'''
Returns a bounded semaphore object
'''
from multiprocessing.synchronize import BoundedSemaphore
return BoundedSemaphore(value)
def Event():
'''
Returns an event object
'''
from multiprocessing.synchronize import Event
return Event()
def Barrier(parties, action=None, timeout=None):
'''
Returns a barrier object
'''
from multiprocessing.synchronize import Barrier
return Barrier(parties, action, timeout)
def Queue(maxsize=0):
'''
Returns a queue object
'''
from multiprocessing.queues import Queue
return Queue(maxsize)
def JoinableQueue(maxsize=0):
'''
Returns a queue object
'''
from multiprocessing.queues import JoinableQueue
return JoinableQueue(maxsize)
def SimpleQueue():
'''
Returns a queue object
'''
from multiprocessing.queues import SimpleQueue
return SimpleQueue()
def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None):
'''
Returns a process pool object
'''
from multiprocessing.pool import Pool
return Pool(processes, initializer, initargs, maxtasksperchild)
def RawValue(typecode_or_type, *args):
'''
Returns a shared object
'''
from multiprocessing.sharedctypes import RawValue
return RawValue(typecode_or_type, *args)
def RawArray(typecode_or_type, size_or_initializer):
'''
Returns a shared array
'''
from multiprocessing.sharedctypes import RawArray
return RawArray(typecode_or_type, size_or_initializer)
def Value(typecode_or_type, *args, lock=True):
'''
Returns a synchronized shared object
'''
from multiprocessing.sharedctypes import Value
return Value(typecode_or_type, *args, lock=lock)
def Array(typecode_or_type, size_or_initializer, *, lock=True):
'''
Returns a synchronized shared array
'''
from multiprocessing.sharedctypes import Array
return Array(typecode_or_type, size_or_initializer, lock=lock)
#
#
#
if sys.platform == 'win32':
def set_executable(executable):
'''
Sets the path to a python.exe or pythonw.exe binary used to run
child processes on Windows instead of sys.executable.
Useful for people embedding Python.
'''
from multiprocessing.forking import set_executable
set_executable(executable)
__all__ += ['set_executable']
| gpl-2.0 |
gauravbose/digital-menu | digimenu2/django/core/management/commands/loaddata.py | 77 | 12783 | from __future__ import unicode_literals
import glob
import gzip
import os
import warnings
import zipfile
from itertools import product
from django.apps import apps
from django.conf import settings
from django.core import serializers
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError
from django.core.management.color import no_style
from django.db import (
DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connections, router,
transaction,
)
from django.utils import lru_cache
from django.utils._os import upath
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding import force_text
from django.utils.functional import cached_property
try:
import bz2
has_bz2 = True
except ImportError:
has_bz2 = False
class Command(BaseCommand):
help = 'Installs the named fixture(s) in the database.'
missing_args_message = ("No database fixture specified. Please provide the "
"path of at least one fixture in the command line.")
def add_arguments(self, parser):
parser.add_argument('args', metavar='fixture', nargs='+',
help='Fixture labels.')
parser.add_argument('--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load '
'fixtures into. Defaults to the "default" database.')
parser.add_argument('--app', action='store', dest='app_label',
default=None, help='Only look for fixtures in the specified app.')
parser.add_argument('--ignorenonexistent', '-i', action='store_true',
dest='ignore', default=False,
help='Ignores entries in the serialized data for fields that do not '
'currently exist on the model.')
def handle(self, *fixture_labels, **options):
self.ignore = options.get('ignore')
self.using = options.get('database')
self.app_label = options.get('app_label')
self.hide_empty = options.get('hide_empty', False)
self.verbosity = options.get('verbosity')
with transaction.atomic(using=self.using):
self.loaddata(fixture_labels)
# Close the DB connection -- unless we're still in a transaction. This
# is required as a workaround for an edge case in MySQL: if the same
# connection is used to create tables, load data, and query, the query
# can return incorrect results. See Django #7572, MySQL #37735.
if transaction.get_autocommit(self.using):
connections[self.using].close()
def loaddata(self, fixture_labels):
connection = connections[self.using]
# Keep a count of the installed objects and fixtures
self.fixture_count = 0
self.loaded_object_count = 0
self.fixture_object_count = 0
self.models = set()
self.serialization_formats = serializers.get_public_serializer_formats()
# Forcing binary mode may be revisited after dropping Python 2 support (see #22399)
self.compression_formats = {
None: (open, 'rb'),
'gz': (gzip.GzipFile, 'rb'),
'zip': (SingleZipReader, 'r'),
}
if has_bz2:
self.compression_formats['bz2'] = (bz2.BZ2File, 'r')
with connection.constraint_checks_disabled():
for fixture_label in fixture_labels:
self.load_label(fixture_label)
# Since we disabled constraint checks, we must manually check for
# any invalid keys that might have been added
table_names = [model._meta.db_table for model in self.models]
try:
connection.check_constraints(table_names=table_names)
except Exception as e:
e.args = ("Problem installing fixtures: %s" % e,)
raise
# If we found even one object in a fixture, we need to reset the
# database sequences.
if self.loaded_object_count > 0:
sequence_sql = connection.ops.sequence_reset_sql(no_style(), self.models)
if sequence_sql:
if self.verbosity >= 2:
self.stdout.write("Resetting sequences\n")
with connection.cursor() as cursor:
for line in sequence_sql:
cursor.execute(line)
if self.verbosity >= 1:
if self.fixture_count == 0 and self.hide_empty:
pass
elif self.fixture_object_count == self.loaded_object_count:
self.stdout.write("Installed %d object(s) from %d fixture(s)" %
(self.loaded_object_count, self.fixture_count))
else:
self.stdout.write("Installed %d object(s) (of %d) from %d fixture(s)" %
(self.loaded_object_count, self.fixture_object_count, self.fixture_count))
def load_label(self, fixture_label):
"""
Loads fixtures files for a given label.
"""
for fixture_file, fixture_dir, fixture_name in self.find_fixtures(fixture_label):
_, ser_fmt, cmp_fmt = self.parse_name(os.path.basename(fixture_file))
open_method, mode = self.compression_formats[cmp_fmt]
fixture = open_method(fixture_file, mode)
try:
self.fixture_count += 1
objects_in_fixture = 0
loaded_objects_in_fixture = 0
if self.verbosity >= 2:
self.stdout.write("Installing %s fixture '%s' from %s." %
(ser_fmt, fixture_name, humanize(fixture_dir)))
objects = serializers.deserialize(ser_fmt, fixture,
using=self.using, ignorenonexistent=self.ignore)
for obj in objects:
objects_in_fixture += 1
if router.allow_migrate_model(self.using, obj.object.__class__):
loaded_objects_in_fixture += 1
self.models.add(obj.object.__class__)
try:
obj.save(using=self.using)
except (DatabaseError, IntegrityError) as e:
e.args = ("Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
'app_label': obj.object._meta.app_label,
'object_name': obj.object._meta.object_name,
'pk': obj.object.pk,
'error_msg': force_text(e)
},)
raise
self.loaded_object_count += loaded_objects_in_fixture
self.fixture_object_count += objects_in_fixture
except Exception as e:
if not isinstance(e, CommandError):
e.args = ("Problem installing fixture '%s': %s" % (fixture_file, e),)
raise
finally:
fixture.close()
# Warn if the fixture we loaded contains 0 objects.
if objects_in_fixture == 0:
warnings.warn(
"No fixture data found for '%s'. (File format may be "
"invalid.)" % fixture_name,
RuntimeWarning
)
@lru_cache.lru_cache(maxsize=None)
def find_fixtures(self, fixture_label):
"""
Finds fixture files for a given label.
"""
fixture_name, ser_fmt, cmp_fmt = self.parse_name(fixture_label)
databases = [self.using, None]
cmp_fmts = list(self.compression_formats.keys()) if cmp_fmt is None else [cmp_fmt]
ser_fmts = serializers.get_public_serializer_formats() if ser_fmt is None else [ser_fmt]
if self.verbosity >= 2:
self.stdout.write("Loading '%s' fixtures..." % fixture_name)
if os.path.isabs(fixture_name):
fixture_dirs = [os.path.dirname(fixture_name)]
fixture_name = os.path.basename(fixture_name)
else:
fixture_dirs = self.fixture_dirs
if os.path.sep in os.path.normpath(fixture_name):
fixture_dirs = [os.path.join(dir_, os.path.dirname(fixture_name))
for dir_ in fixture_dirs]
fixture_name = os.path.basename(fixture_name)
suffixes = ('.'.join(ext for ext in combo if ext)
for combo in product(databases, ser_fmts, cmp_fmts))
targets = set('.'.join((fixture_name, suffix)) for suffix in suffixes)
fixture_files = []
for fixture_dir in fixture_dirs:
if self.verbosity >= 2:
self.stdout.write("Checking %s for fixtures..." % humanize(fixture_dir))
fixture_files_in_dir = []
for candidate in glob.iglob(os.path.join(fixture_dir, fixture_name + '*')):
if os.path.basename(candidate) in targets:
# Save the fixture_dir and fixture_name for future error messages.
fixture_files_in_dir.append((candidate, fixture_dir, fixture_name))
if self.verbosity >= 2 and not fixture_files_in_dir:
self.stdout.write("No fixture '%s' in %s." %
(fixture_name, humanize(fixture_dir)))
# Check kept for backwards-compatibility; it isn't clear why
# duplicates are only allowed in different directories.
if len(fixture_files_in_dir) > 1:
raise CommandError(
"Multiple fixtures named '%s' in %s. Aborting." %
(fixture_name, humanize(fixture_dir)))
fixture_files.extend(fixture_files_in_dir)
if fixture_name != 'initial_data' and not fixture_files:
# Warning kept for backwards-compatibility; why not an exception?
warnings.warn("No fixture named '%s' found." % fixture_name)
elif fixture_name == 'initial_data' and fixture_files:
warnings.warn(
'initial_data fixtures are deprecated. Use data migrations instead.',
RemovedInDjango19Warning
)
return fixture_files
@cached_property
def fixture_dirs(self):
"""
Return a list of fixture directories.
The list contains the 'fixtures' subdirectory of each installed
application, if it exists, the directories in FIXTURE_DIRS, and the
current directory.
"""
dirs = []
fixture_dirs = settings.FIXTURE_DIRS
if len(fixture_dirs) != len(set(fixture_dirs)):
raise ImproperlyConfigured("settings.FIXTURE_DIRS contains duplicates.")
for app_config in apps.get_app_configs():
app_label = app_config.label
app_dir = os.path.join(app_config.path, 'fixtures')
if app_dir in fixture_dirs:
raise ImproperlyConfigured(
"'%s' is a default fixture directory for the '%s' app "
"and cannot be listed in settings.FIXTURE_DIRS." % (app_dir, app_label)
)
if self.app_label and app_label != self.app_label:
continue
if os.path.isdir(app_dir):
dirs.append(app_dir)
dirs.extend(list(fixture_dirs))
dirs.append('')
dirs = [upath(os.path.abspath(os.path.realpath(d))) for d in dirs]
return dirs
def parse_name(self, fixture_name):
"""
Splits fixture name in name, serialization format, compression format.
"""
parts = fixture_name.rsplit('.', 2)
if len(parts) > 1 and parts[-1] in self.compression_formats:
cmp_fmt = parts[-1]
parts = parts[:-1]
else:
cmp_fmt = None
if len(parts) > 1:
if parts[-1] in self.serialization_formats:
ser_fmt = parts[-1]
parts = parts[:-1]
else:
raise CommandError(
"Problem installing fixture '%s': %s is not a known "
"serialization format." % (''.join(parts[:-1]), parts[-1]))
else:
ser_fmt = None
name = '.'.join(parts)
return name, ser_fmt, cmp_fmt
class SingleZipReader(zipfile.ZipFile):
def __init__(self, *args, **kwargs):
zipfile.ZipFile.__init__(self, *args, **kwargs)
if len(self.namelist()) != 1:
raise ValueError("Zip-compressed fixtures must contain one file.")
def read(self):
return zipfile.ZipFile.read(self, self.namelist()[0])
def humanize(dirname):
return "'%s'" % dirname if dirname else 'absolute path'
| bsd-3-clause |
Stuxnet-Kernel/kernel_shamu | tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Core.py | 11088 | 3246 | # Core.py - Python extension for perf script, core functions
#
# Copyright (C) 2010 by Tom Zanussi <tzanussi@gmail.com>
#
# This software may be distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
from collections import defaultdict
def autodict():
return defaultdict(autodict)
flag_fields = autodict()
symbolic_fields = autodict()
def define_flag_field(event_name, field_name, delim):
flag_fields[event_name][field_name]['delim'] = delim
def define_flag_value(event_name, field_name, value, field_str):
flag_fields[event_name][field_name]['values'][value] = field_str
def define_symbolic_field(event_name, field_name):
# nothing to do, really
pass
def define_symbolic_value(event_name, field_name, value, field_str):
symbolic_fields[event_name][field_name]['values'][value] = field_str
def flag_str(event_name, field_name, value):
string = ""
if flag_fields[event_name][field_name]:
print_delim = 0
keys = flag_fields[event_name][field_name]['values'].keys()
keys.sort()
for idx in keys:
if not value and not idx:
string += flag_fields[event_name][field_name]['values'][idx]
break
if idx and (value & idx) == idx:
if print_delim and flag_fields[event_name][field_name]['delim']:
string += " " + flag_fields[event_name][field_name]['delim'] + " "
string += flag_fields[event_name][field_name]['values'][idx]
print_delim = 1
value &= ~idx
return string
def symbol_str(event_name, field_name, value):
string = ""
if symbolic_fields[event_name][field_name]:
keys = symbolic_fields[event_name][field_name]['values'].keys()
keys.sort()
for idx in keys:
if not value and not idx:
string = symbolic_fields[event_name][field_name]['values'][idx]
break
if (value == idx):
string = symbolic_fields[event_name][field_name]['values'][idx]
break
return string
trace_flags = { 0x00: "NONE", \
0x01: "IRQS_OFF", \
0x02: "IRQS_NOSUPPORT", \
0x04: "NEED_RESCHED", \
0x08: "HARDIRQ", \
0x10: "SOFTIRQ" }
def trace_flag_str(value):
string = ""
print_delim = 0
keys = trace_flags.keys()
for idx in keys:
if not value and not idx:
string += "NONE"
break
if idx and (value & idx) == idx:
if print_delim:
string += " | ";
string += trace_flags[idx]
print_delim = 1
value &= ~idx
return string
def taskState(state):
states = {
0 : "R",
1 : "S",
2 : "D",
64: "DEAD"
}
if state not in states:
return "Unknown"
return states[state]
class EventHeaders:
def __init__(self, common_cpu, common_secs, common_nsecs,
common_pid, common_comm):
self.cpu = common_cpu
self.secs = common_secs
self.nsecs = common_nsecs
self.pid = common_pid
self.comm = common_comm
def ts(self):
return (self.secs * (10 ** 9)) + self.nsecs
def ts_format(self):
return "%d.%d" % (self.secs, int(self.nsecs / 1000))
| gpl-2.0 |
hustbeta/openstack-juno-api-adventure | examples/neutron/05_pools.py | 1 | 1335 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import keystoneclient.auth.identity.v3
import keystoneclient.session
import keystoneclient.v3.client
import neutronclient.neutron.client
import local_settings
def get_session():
keystone = keystoneclient.v3.client.Client(auth_url=local_settings.auth_url_v3,
username=local_settings.username,
password=local_settings.password,
unscoped=True)
keystone.management_url = keystone.auth_url
projects = keystone.projects.list(user=keystone.auth_ref.user_id)
projects.sort(key=lambda project: project.name.lower())
auth = keystoneclient.auth.identity.v3.Token(auth_url=local_settings.auth_url_v3,
token=keystone.auth_token,
project_id=projects[0].id)
session = keystoneclient.session.Session(auth=auth)
return session
def test_neutron(session):
neutron = neutronclient.neutron.client.Client('2.0', session=session)
q = neutron.list_pools(tenant_id='422b53b9339f427abca6a1eab3c1cdd1')
#q = neutron.list_pools()
print type(q)
print json.dumps(q)
session = get_session()
test_neutron(session)
| mit |
numpy/datetime | numpy/core/tests/test_ufunc.py | 8 | 16944 | import sys
import numpy as np
from numpy.testing import *
import numpy.core.umath_tests as umt
class TestUfunc(TestCase):
def test_reduceat_shifting_sum(self) :
L = 6
x = np.arange(L)
idx = np.array(zip(np.arange(L-2), np.arange(L-2)+2)).ravel()
assert_array_equal(np.add.reduceat(x,idx)[::2], [1,3,5,7])
def test_generic_loops(self) :
"""Test generic loops.
The loops to be tested are:
PyUFunc_ff_f_As_dd_d
PyUFunc_ff_f
PyUFunc_dd_d
PyUFunc_gg_g
PyUFunc_FF_F_As_DD_D
PyUFunc_DD_D
PyUFunc_FF_F
PyUFunc_GG_G
PyUFunc_OO_O
PyUFunc_OO_O_method
PyUFunc_f_f_As_d_d
PyUFunc_d_d
PyUFunc_f_f
PyUFunc_g_g
PyUFunc_F_F_As_D_D
PyUFunc_F_F
PyUFunc_D_D
PyUFunc_G_G
PyUFunc_O_O
PyUFunc_O_O_method
PyUFunc_On_Om
Where:
f -- float
d -- double
g -- long double
F -- complex float
D -- complex double
G -- complex long double
O -- python object
It is difficult to assure that each of these loops is entered from the
Python level as the special cased loops are a moving target and the
corresponding types are architecture dependent. We probably need to
define C level testing ufuncs to get at them. For the time being, I've
just looked at the signatures registered in the build directory to find
relevant functions.
Fixme, currently untested:
PyUFunc_ff_f_As_dd_d
PyUFunc_FF_F_As_DD_D
PyUFunc_f_f_As_d_d
PyUFunc_F_F_As_D_D
PyUFunc_On_Om
"""
fone = np.exp
ftwo = lambda x,y : x**y
fone_val = 1
ftwo_val = 1
# check unary PyUFunc_f_f.
msg = "PyUFunc_f_f"
x = np.zeros(10, dtype=np.single)[0::2]
assert_almost_equal(fone(x), fone_val, err_msg=msg)
# check unary PyUFunc_d_d.
msg = "PyUFunc_d_d"
x = np.zeros(10, dtype=np.double)[0::2]
assert_almost_equal(fone(x), fone_val, err_msg=msg)
# check unary PyUFunc_g_g.
msg = "PyUFunc_g_g"
x = np.zeros(10, dtype=np.longdouble)[0::2]
assert_almost_equal(fone(x), fone_val, err_msg=msg)
# check unary PyUFunc_F_F.
msg = "PyUFunc_F_F"
x = np.zeros(10, dtype=np.csingle)[0::2]
assert_almost_equal(fone(x), fone_val, err_msg=msg)
# check unary PyUFunc_D_D.
msg = "PyUFunc_D_D"
x = np.zeros(10, dtype=np.cdouble)[0::2]
assert_almost_equal(fone(x), fone_val, err_msg=msg)
# check unary PyUFunc_G_G.
msg = "PyUFunc_G_G"
x = np.zeros(10, dtype=np.clongdouble)[0::2]
assert_almost_equal(fone(x), fone_val, err_msg=msg)
# check binary PyUFunc_ff_f.
msg = "PyUFunc_ff_f"
x = np.ones(10, dtype=np.single)[0::2]
assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg)
# check binary PyUFunc_dd_d.
msg = "PyUFunc_dd_d"
x = np.ones(10, dtype=np.double)[0::2]
assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg)
# check binary PyUFunc_gg_g.
msg = "PyUFunc_gg_g"
x = np.ones(10, dtype=np.longdouble)[0::2]
assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg)
# check binary PyUFunc_FF_F.
msg = "PyUFunc_FF_F"
x = np.ones(10, dtype=np.csingle)[0::2]
assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg)
# check binary PyUFunc_DD_D.
msg = "PyUFunc_DD_D"
x = np.ones(10, dtype=np.cdouble)[0::2]
assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg)
# check binary PyUFunc_GG_G.
msg = "PyUFunc_GG_G"
x = np.ones(10, dtype=np.clongdouble)[0::2]
assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg)
# class to use in testing object method loops
class foo :
def logical_not(self) :
return np.bool_(1)
def logical_and(self, obj) :
return np.bool_(1)
# check unary PyUFunc_O_O
msg = "PyUFunc_O_O"
x = np.ones(10, dtype=np.object)[0::2]
assert np.all(np.abs(x) == 1), msg
# check unary PyUFunc_O_O_method
msg = "PyUFunc_O_O_method"
x = np.zeros(10, dtype=np.object)[0::2]
for i in range(len(x)) :
x[i] = foo()
assert np.all(np.logical_not(x) == True), msg
# check binary PyUFunc_OO_O
msg = "PyUFunc_OO_O"
x = np.ones(10, dtype=np.object)[0::2]
assert np.all(np.add(x,x) == 2), msg
# check binary PyUFunc_OO_O_method
msg = "PyUFunc_OO_O_method"
x = np.zeros(10, dtype=np.object)[0::2]
for i in range(len(x)) :
x[i] = foo()
assert np.all(np.logical_and(x,x) == 1), msg
# check PyUFunc_On_Om
# fixme -- I don't know how to do this yet
def test_all_ufunc(self) :
"""Try to check presence and results of all ufuncs.
The list of ufuncs comes from generate_umath.py and is as follows:
===== ==== ============= =============== ========================
done args function types notes
===== ==== ============= =============== ========================
n 1 conjugate nums + O
n 1 absolute nums + O complex -> real
n 1 negative nums + O
n 1 sign nums + O -> int
n 1 invert bool + ints + O flts raise an error
n 1 degrees real + M cmplx raise an error
n 1 radians real + M cmplx raise an error
n 1 arccos flts + M
n 1 arccosh flts + M
n 1 arcsin flts + M
n 1 arcsinh flts + M
n 1 arctan flts + M
n 1 arctanh flts + M
n 1 cos flts + M
n 1 sin flts + M
n 1 tan flts + M
n 1 cosh flts + M
n 1 sinh flts + M
n 1 tanh flts + M
n 1 exp flts + M
n 1 expm1 flts + M
n 1 log flts + M
n 1 log10 flts + M
n 1 log1p flts + M
n 1 sqrt flts + M real x < 0 raises error
n 1 ceil real + M
n 1 trunc real + M
n 1 floor real + M
n 1 fabs real + M
n 1 rint flts + M
n 1 isnan flts -> bool
n 1 isinf flts -> bool
n 1 isfinite flts -> bool
n 1 signbit real -> bool
n 1 modf real -> (frac, int)
n 1 logical_not bool + nums + M -> bool
n 2 left_shift ints + O flts raise an error
n 2 right_shift ints + O flts raise an error
n 2 add bool + nums + O boolean + is ||
n 2 subtract bool + nums + O boolean - is ^
n 2 multiply bool + nums + O boolean * is &
n 2 divide nums + O
n 2 floor_divide nums + O
n 2 true_divide nums + O bBhH -> f, iIlLqQ -> d
n 2 fmod nums + M
n 2 power nums + O
n 2 greater bool + nums + O -> bool
n 2 greater_equal bool + nums + O -> bool
n 2 less bool + nums + O -> bool
n 2 less_equal bool + nums + O -> bool
n 2 equal bool + nums + O -> bool
n 2 not_equal bool + nums + O -> bool
n 2 logical_and bool + nums + M -> bool
n 2 logical_or bool + nums + M -> bool
n 2 logical_xor bool + nums + M -> bool
n 2 maximum bool + nums + O
n 2 minimum bool + nums + O
n 2 bitwise_and bool + ints + O flts raise an error
n 2 bitwise_or bool + ints + O flts raise an error
n 2 bitwise_xor bool + ints + O flts raise an error
n 2 arctan2 real + M
n 2 remainder ints + real + O
n 2 hypot real + M
===== ==== ============= =============== ========================
Types other than those listed will be accepted, but they are cast to
the smallest compatible type for which the function is defined. The
casting rules are:
bool -> int8 -> float32
ints -> double
"""
pass
def test_signature(self):
# the arguments to test_signature are: nin, nout, core_signature
# pass
assert_equal(umt.test_signature(2,1,"(i),(i)->()"), 1)
# pass. empty core signature; treat as plain ufunc (with trivial core)
assert_equal(umt.test_signature(2,1,"(),()->()"), 0)
# in the following calls, a ValueError should be raised because
# of error in core signature
# error: extra parenthesis
msg = "core_sig: extra parenthesis"
try:
ret = umt.test_signature(2,1,"((i)),(i)->()")
assert_equal(ret, None, err_msg=msg)
except ValueError: None
# error: parenthesis matching
msg = "core_sig: parenthesis matching"
try:
ret = umt.test_signature(2,1,"(i),)i(->()")
assert_equal(ret, None, err_msg=msg)
except ValueError: None
# error: incomplete signature. letters outside of parenthesis are ignored
msg = "core_sig: incomplete signature"
try:
ret = umt.test_signature(2,1,"(i),->()")
assert_equal(ret, None, err_msg=msg)
except ValueError: None
# error: incomplete signature. 2 output arguments are specified
msg = "core_sig: incomplete signature"
try:
ret = umt.test_signature(2,2,"(i),(i)->()")
assert_equal(ret, None, err_msg=msg)
except ValueError: None
# more complicated names for variables
assert_equal(umt.test_signature(2,1,"(i1,i2),(J_1)->(_kAB)"),1)
def test_get_signature(self):
assert_equal(umt.inner1d.signature, "(i),(i)->()")
def test_inner1d(self):
a = np.arange(6).reshape((2,3))
assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1))
def test_broadcast(self):
msg = "broadcast"
a = np.arange(4).reshape((2,1,2))
b = np.arange(4).reshape((1,2,2))
assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg)
msg = "extend & broadcast loop dimensions"
b = np.arange(4).reshape((2,2))
assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg)
msg = "broadcast in core dimensions"
a = np.arange(8).reshape((4,2))
b = np.arange(4).reshape((4,1))
assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg)
msg = "extend & broadcast core and loop dimensions"
a = np.arange(8).reshape((4,2))
b = np.array(7)
assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg)
msg = "broadcast should fail"
a = np.arange(2).reshape((2,1,1))
b = np.arange(3).reshape((3,1,1))
try:
ret = umt.inner1d(a,b)
assert_equal(ret, None, err_msg=msg)
except ValueError: None
def test_type_cast(self):
msg = "type cast"
a = np.arange(6, dtype='short').reshape((2,3))
assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1), err_msg=msg)
msg = "type cast on one argument"
a = np.arange(6).reshape((2,3))
b = a+0.1
assert_array_almost_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1),
err_msg=msg)
def test_endian(self):
msg = "big endian"
a = np.arange(6, dtype='>i4').reshape((2,3))
assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1), err_msg=msg)
msg = "little endian"
a = np.arange(6, dtype='<i4').reshape((2,3))
assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1), err_msg=msg)
def test_incontiguous_array(self):
msg = "incontiguous memory layout of array"
x = np.arange(64).reshape((2,2,2,2,2,2))
a = x[:,0,:,0,:,0]
b = x[:,1,:,1,:,1]
a[0,0,0] = -1
msg2 = "make sure it references to the original array"
assert_equal(x[0,0,0,0,0,0], -1, err_msg=msg2)
assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg)
x = np.arange(24).reshape(2,3,4)
a = x.T
b = x.T
a[0,0,0] = -1
assert_equal(x[0,0,0], -1, err_msg=msg2)
assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg)
def test_output_argument(self):
msg = "output argument"
a = np.arange(12).reshape((2,3,2))
b = np.arange(4).reshape((2,1,2)) + 1
c = np.zeros((2,3),dtype='int')
umt.inner1d(a,b,c)
assert_array_equal(c, np.sum(a*b,axis=-1), err_msg=msg)
msg = "output argument with type cast"
c = np.zeros((2,3),dtype='int16')
umt.inner1d(a,b,c)
assert_array_equal(c, np.sum(a*b,axis=-1), err_msg=msg)
msg = "output argument with incontiguous layout"
c = np.zeros((2,3,4),dtype='int16')
umt.inner1d(a,b,c[...,0])
assert_array_equal(c[...,0], np.sum(a*b,axis=-1), err_msg=msg)
def test_innerwt(self):
a = np.arange(6).reshape((2,3))
b = np.arange(10,16).reshape((2,3))
w = np.arange(20,26).reshape((2,3))
assert_array_equal(umt.innerwt(a,b,w), np.sum(a*b*w,axis=-1))
a = np.arange(100,124).reshape((2,3,4))
b = np.arange(200,224).reshape((2,3,4))
w = np.arange(300,324).reshape((2,3,4))
assert_array_equal(umt.innerwt(a,b,w), np.sum(a*b*w,axis=-1))
def test_matrix_multiply(self):
self.compare_matrix_multiply_results(np.long)
self.compare_matrix_multiply_results(np.double)
def compare_matrix_multiply_results(self, tp):
d1 = np.array(rand(2,3,4), dtype=tp)
d2 = np.array(rand(2,3,4), dtype=tp)
msg = "matrix multiply on type %s" % d1.dtype.name
def permute_n(n):
if n == 1:
return ([0],)
ret = ()
base = permute_n(n-1)
for perm in base:
for i in xrange(n):
new = perm + [n-1]
new[n-1] = new[i]
new[i] = n-1
ret += (new,)
return ret
def slice_n(n):
if n == 0:
return ((),)
ret = ()
base = slice_n(n-1)
for sl in base:
ret += (sl+(slice(None),),)
ret += (sl+(slice(0,1),),)
return ret
def broadcastable(s1,s2):
return s1 == s2 or s1 == 1 or s2 == 1
permute_3 = permute_n(3)
slice_3 = slice_n(3) + ((slice(None,None,-1),)*3,)
ref = True
for p1 in permute_3:
for p2 in permute_3:
for s1 in slice_3:
for s2 in slice_3:
a1 = d1.transpose(p1)[s1]
a2 = d2.transpose(p2)[s2]
ref = ref and a1.base != None and a1.base.base != None
ref = ref and a2.base != None and a2.base.base != None
if broadcastable(a1.shape[-1], a2.shape[-2]) and \
broadcastable(a1.shape[0], a2.shape[0]):
assert_array_almost_equal(
umt.matrix_multiply(a1,a2),
np.sum(a2[...,np.newaxis].swapaxes(-3,-1) *
a1[...,np.newaxis,:], axis=-1),
err_msg = msg+' %s %s' % (str(a1.shape),
str(a2.shape)))
assert_equal(ref, True, err_msg="reference check")
if __name__ == "__main__":
run_module_suite()
| bsd-3-clause |
MaxMorais/frappe | frappe/tests/test_fmt_money.py | 54 | 4016 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, cstr
def fmt_money(amount, precision=None):
"""
Convert to string with commas for thousands, millions etc
"""
number_format = frappe.db.get_default("number_format") or "#,###.##"
decimal_str, comma_str, precision = get_number_format_info(number_format)
amount = '%.*f' % (precision, flt(amount))
if amount.find('.') == -1:
decimals = ''
else:
decimals = amount.split('.')[1]
parts = []
minus = ''
if flt(amount) < 0:
minus = '-'
amount = cstr(abs(flt(amount))).split('.')[0]
if len(amount) > 3:
parts.append(amount[-3:])
amount = amount[:-3]
val = number_format=="#,##,###.##" and 2 or 3
while len(amount) > val:
parts.append(amount[-val:])
amount = amount[:-val]
parts.append(amount)
parts.reverse()
amount = comma_str.join(parts) + (precision and (decimal_str + decimals) or "")
amount = minus + amount
return amount
def get_number_format_info(format):
if format=="#.###":
return "", ".", 0
elif format=="#,###":
return "", ",", 0
elif format=="#,###.##" or format=="#,##,###.##":
return ".", ",", 2
elif format=="#.###,##":
return ",", ".", 2
elif format=="# ###.##":
return ".", " ", 2
else:
return ".", ",", 2
import unittest
class TestFmtMoney(unittest.TestCase):
def test_standard(self):
frappe.db.set_default("number_format", "#,###.##")
self.assertEquals(fmt_money(100), "100.00")
self.assertEquals(fmt_money(1000), "1,000.00")
self.assertEquals(fmt_money(10000), "10,000.00")
self.assertEquals(fmt_money(100000), "100,000.00")
self.assertEquals(fmt_money(1000000), "1,000,000.00")
self.assertEquals(fmt_money(10000000), "10,000,000.00")
self.assertEquals(fmt_money(100000000), "100,000,000.00")
self.assertEquals(fmt_money(1000000000), "1,000,000,000.00")
def test_negative(self):
frappe.db.set_default("number_format", "#,###.##")
self.assertEquals(fmt_money(-100), "-100.00")
self.assertEquals(fmt_money(-1000), "-1,000.00")
self.assertEquals(fmt_money(-10000), "-10,000.00")
self.assertEquals(fmt_money(-100000), "-100,000.00")
self.assertEquals(fmt_money(-1000000), "-1,000,000.00")
self.assertEquals(fmt_money(-10000000), "-10,000,000.00")
self.assertEquals(fmt_money(-100000000), "-100,000,000.00")
self.assertEquals(fmt_money(-1000000000), "-1,000,000,000.00")
def test_decimal(self):
frappe.db.set_default("number_format", "#.###,##")
self.assertEquals(fmt_money(-100), "-100,00")
self.assertEquals(fmt_money(-1000), "-1.000,00")
self.assertEquals(fmt_money(-10000), "-10.000,00")
self.assertEquals(fmt_money(-100000), "-100.000,00")
self.assertEquals(fmt_money(-1000000), "-1.000.000,00")
self.assertEquals(fmt_money(-10000000), "-10.000.000,00")
self.assertEquals(fmt_money(-100000000), "-100.000.000,00")
self.assertEquals(fmt_money(-1000000000), "-1.000.000.000,00")
def test_lacs(self):
frappe.db.set_default("number_format", "#,##,###.##")
self.assertEquals(fmt_money(100), "100.00")
self.assertEquals(fmt_money(1000), "1,000.00")
self.assertEquals(fmt_money(10000), "10,000.00")
self.assertEquals(fmt_money(100000), "1,00,000.00")
self.assertEquals(fmt_money(1000000), "10,00,000.00")
self.assertEquals(fmt_money(10000000), "1,00,00,000.00")
self.assertEquals(fmt_money(100000000), "10,00,00,000.00")
self.assertEquals(fmt_money(1000000000), "1,00,00,00,000.00")
def test_no_precision(self):
frappe.db.set_default("number_format", "#,###")
self.assertEquals(fmt_money(0.3), "0")
self.assertEquals(fmt_money(100.3), "100")
self.assertEquals(fmt_money(1000.3), "1,000")
self.assertEquals(fmt_money(10000.3), "10,000")
self.assertEquals(fmt_money(-0.3), "0")
self.assertEquals(fmt_money(-100.3), "-100")
self.assertEquals(fmt_money(-1000.3), "-1,000")
if __name__=="__main__":
frappe.connect()
unittest.main() | mit |
Flimm/linkchecker | linkcheck/checker/fileurl.py | 9 | 10873 | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2000-2014 Bastian Kleineidam
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Handle local file: links.
"""
import re
import os
try:
import urlparse
except ImportError:
# Python 3
from urllib import parse as urlparse
import urllib
try:
from urllib2 import urlopen
except ImportError:
# Python 3
from urllib.request import urlopen
from datetime import datetime
from . import urlbase, get_index_html
from .. import log, LOG_CHECK, fileutil, mimeutil, LinkCheckerError, url as urlutil
from ..bookmarks import firefox
from .const import WARN_FILE_MISSING_SLASH, WARN_FILE_SYSTEM_PATH
def get_files (dirname):
"""Get iterator of entries in directory. Only allows regular files
and directories, no symlinks."""
for entry in os.listdir(dirname):
fullentry = os.path.join(dirname, entry)
if os.path.islink(fullentry):
continue
if os.path.isfile(fullentry):
yield entry
elif os.path.isdir(fullentry):
yield entry+"/"
def prepare_urlpath_for_nt (path):
"""
URLs like 'file://server/path/' result in a path named '/server/path'.
However urllib.url2pathname expects '////server/path'.
"""
if '|' not in path:
return "////"+path.lstrip("/")
return path
def get_nt_filename (path):
"""Return case sensitive filename for NT path."""
unc, rest = os.path.splitunc(path)
head, tail = os.path.split(rest)
if not tail:
return path
for fname in os.listdir(unc+head):
if fname.lower() == tail.lower():
return os.path.join(get_nt_filename(unc+head), fname)
log.error(LOG_CHECK, "could not find %r in %r", tail, head)
return path
def get_os_filename (path):
"""Return filesystem path for given URL path."""
if os.name == 'nt':
path = prepare_urlpath_for_nt(path)
res = urllib.url2pathname(fileutil.pathencode(path))
if os.name == 'nt' and res.endswith(':') and len(res) == 2:
# Work around http://bugs.python.org/issue11474
res += os.sep
return res
def is_absolute_path (path):
"""Check if given path is absolute. On Windows absolute paths start
with a drive letter. On all other systems absolute paths start with
a slash."""
if os.name == 'nt':
if re.search(r"^[a-zA-Z]:", path):
return True
path = path.replace("\\", "/")
return path.startswith("/")
class FileUrl (urlbase.UrlBase):
"""
Url link with file scheme.
"""
def init (self, base_ref, base_url, parent_url, recursion_level,
aggregate, line, column, page, name, url_encoding, extern):
"""Initialize the scheme."""
super(FileUrl, self).init(base_ref, base_url, parent_url,
recursion_level, aggregate, line, column, page, name, url_encoding, extern)
self.scheme = u'file'
def build_base_url(self):
"""The URL is normed according to the platform:
- the base URL is made an absolute file:// URL
- under Windows platform the drive specifier is normed
"""
if self.base_url is None:
return
base_url = self.base_url
if not (self.parent_url or self.base_ref or base_url.startswith("file:")):
base_url = os.path.expanduser(base_url)
if not is_absolute_path(base_url):
try:
base_url = os.getcwd()+"/"+base_url
except OSError as msg:
# occurs on stale remote filesystems (eg. NFS)
errmsg = _("Could not get current working directory: %(msg)s") % dict(msg=msg)
raise LinkCheckerError(errmsg)
if os.path.isdir(base_url):
base_url += "/"
base_url = "file://"+base_url
if os.name == "nt":
base_url = base_url.replace("\\", "/")
# transform c:/windows into /c|/windows
base_url = re.sub("^file://(/?)([a-zA-Z]):", r"file:///\2|", base_url)
# transform file://path into file:///path
base_url = re.sub("^file://([^/])", r"file:///\1", base_url)
self.base_url = unicode(base_url)
def build_url (self):
"""
Calls super.build_url() and adds a trailing slash to directories.
"""
self.build_base_url()
if self.parent_url is not None:
# URL joining with the parent URL only works if the query
# of the base URL are removed first.
# Otherwise the join function thinks the query is part of
# the file name.
from .urlbase import url_norm
# norm base url - can raise UnicodeError from url.idna_encode()
base_url, is_idn = url_norm(self.base_url, self.encoding)
urlparts = list(urlparse.urlsplit(base_url))
# ignore query part for filesystem urls
urlparts[3] = ''
self.base_url = urlutil.urlunsplit(urlparts)
super(FileUrl, self).build_url()
# ignore query and fragment url parts for filesystem urls
self.urlparts[3] = self.urlparts[4] = ''
if self.is_directory() and not self.urlparts[2].endswith('/'):
self.add_warning(_("Added trailing slash to directory."),
tag=WARN_FILE_MISSING_SLASH)
self.urlparts[2] += '/'
self.url = urlutil.urlunsplit(self.urlparts)
def add_size_info (self):
"""Get size of file content and modification time from filename path."""
if self.is_directory():
# Directory size always differs from the customer index.html
# that is generated. So return without calculating any size.
return
filename = self.get_os_filename()
self.size = fileutil.get_size(filename)
self.modified = datetime.utcfromtimestamp(fileutil.get_mtime(filename))
def check_connection (self):
"""
Try to open the local file. Under NT systems the case sensitivity
is checked.
"""
if (self.parent_url is not None and
not self.parent_url.startswith(u"file:")):
msg = _("local files are only checked without parent URL or when the parent URL is also a file")
raise LinkCheckerError(msg)
if self.is_directory():
self.set_result(_("directory"))
else:
url = fileutil.pathencode(self.url)
self.url_connection = urlopen(url)
self.check_case_sensitivity()
def check_case_sensitivity (self):
"""
Check if url and windows path name match cases
else there might be problems when copying such
files on web servers that are case sensitive.
"""
if os.name != 'nt':
return
path = self.get_os_filename()
realpath = get_nt_filename(path)
if path != realpath:
self.add_warning(_("The URL path %(path)r is not the same as the "
"system path %(realpath)r. You should always use "
"the system path in URLs.") % \
{"path": path, "realpath": realpath},
tag=WARN_FILE_SYSTEM_PATH)
def read_content (self):
"""Return file content, or in case of directories a dummy HTML file
with links to the files."""
if self.is_directory():
data = get_index_html(get_files(self.get_os_filename()))
if isinstance(data, unicode):
data = data.encode("iso8859-1", "ignore")
else:
data = super(FileUrl, self).read_content()
return data
def get_os_filename (self):
"""
Construct os specific file path out of the file:// URL.
@return: file name
@rtype: string
"""
return get_os_filename(self.urlparts[2])
def get_temp_filename (self):
"""Get filename for content to parse."""
return self.get_os_filename()
def is_directory (self):
"""
Check if file is a directory.
@return: True iff file is a directory
@rtype: bool
"""
filename = self.get_os_filename()
return os.path.isdir(filename) and not os.path.islink(filename)
def is_parseable (self):
"""Check if content is parseable for recursion.
@return: True if content is parseable
@rtype: bool
"""
if self.is_directory():
return True
if firefox.has_sqlite and firefox.extension.search(self.url):
return True
if self.content_type in self.ContentMimetypes:
return True
log.debug(LOG_CHECK, "File with content type %r is not parseable.", self.content_type)
return False
def set_content_type (self):
"""Return URL content type, or an empty string if content
type could not be found."""
if self.url:
self.content_type = mimeutil.guess_mimetype(self.url, read=self.get_content)
else:
self.content_type = u""
def get_intern_pattern (self, url=None):
"""Get pattern for intern URL matching.
@return non-empty regex pattern or None
@rtype String or None
"""
if url is None:
url = self.url
if not url:
return None
if url.startswith('file://'):
i = url.rindex('/')
if i > 6:
# remove last filename to make directory internal
url = url[:i+1]
return re.escape(url)
def add_url (self, url, line=0, column=0, page=0, name=u"", base=None):
"""If a local webroot directory is configured, replace absolute URLs
with it. After that queue the URL data for checking."""
webroot = self.aggregate.config["localwebroot"]
if webroot and url and url.startswith(u"/"):
url = webroot + url[1:]
log.debug(LOG_CHECK, "Applied local webroot `%s' to `%s'.", webroot, url)
super(FileUrl, self).add_url(url, line=line, column=column, page=page, name=name, base=base)
| gpl-2.0 |
scifiswapnil/Project-LoCatr | lib/python2.7/site-packages/django/urls/resolvers.py | 39 | 21589 | """
This module converts requested URLs to callback view functions.
RegexURLResolver is the main class here. Its resolve() method takes a URL (as
a string) and returns a ResolverMatch object which provides access to all
attributes of the resolved URL match.
"""
from __future__ import unicode_literals
import functools
import re
import threading
from importlib import import_module
from django.conf import settings
from django.core.checks import Warning
from django.core.checks.urls import check_resolver
from django.core.exceptions import ImproperlyConfigured
from django.utils import lru_cache, six
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
from django.utils.http import RFC3986_SUBDELIMS, urlquote
from django.utils.regex_helper import normalize
from django.utils.translation import get_language
from .exceptions import NoReverseMatch, Resolver404
from .utils import get_callable
class ResolverMatch(object):
def __init__(self, func, args, kwargs, url_name=None, app_names=None, namespaces=None):
self.func = func
self.args = args
self.kwargs = kwargs
self.url_name = url_name
# If a URLRegexResolver doesn't have a namespace or app_name, it passes
# in an empty value.
self.app_names = [x for x in app_names if x] if app_names else []
self.app_name = ':'.join(self.app_names)
self.namespaces = [x for x in namespaces if x] if namespaces else []
self.namespace = ':'.join(self.namespaces)
if not hasattr(func, '__name__'):
# A class-based view
self._func_path = '.'.join([func.__class__.__module__, func.__class__.__name__])
else:
# A function-based view
self._func_path = '.'.join([func.__module__, func.__name__])
view_path = url_name or self._func_path
self.view_name = ':'.join(self.namespaces + [view_path])
def __getitem__(self, index):
return (self.func, self.args, self.kwargs)[index]
def __repr__(self):
return "ResolverMatch(func=%s, args=%s, kwargs=%s, url_name=%s, app_names=%s, namespaces=%s)" % (
self._func_path, self.args, self.kwargs, self.url_name,
self.app_names, self.namespaces,
)
@lru_cache.lru_cache(maxsize=None)
def get_resolver(urlconf=None):
if urlconf is None:
from django.conf import settings
urlconf = settings.ROOT_URLCONF
return RegexURLResolver(r'^/', urlconf)
@lru_cache.lru_cache(maxsize=None)
def get_ns_resolver(ns_pattern, resolver):
# Build a namespaced resolver for the given parent URLconf pattern.
# This makes it possible to have captured parameters in the parent
# URLconf pattern.
ns_resolver = RegexURLResolver(ns_pattern, resolver.url_patterns)
return RegexURLResolver(r'^/', [ns_resolver])
class LocaleRegexDescriptor(object):
def __get__(self, instance, cls=None):
"""
Return a compiled regular expression based on the active language.
"""
if instance is None:
return self
# As a performance optimization, if the given regex string is a regular
# string (not a lazily-translated string proxy), compile it once and
# avoid per-language compilation.
if isinstance(instance._regex, six.string_types):
instance.__dict__['regex'] = self._compile(instance._regex)
return instance.__dict__['regex']
language_code = get_language()
if language_code not in instance._regex_dict:
instance._regex_dict[language_code] = self._compile(force_text(instance._regex))
return instance._regex_dict[language_code]
def _compile(self, regex):
"""
Compile and return the given regular expression.
"""
try:
return re.compile(regex, re.UNICODE)
except re.error as e:
raise ImproperlyConfigured(
'"%s" is not a valid regular expression: %s' %
(regex, six.text_type(e))
)
class LocaleRegexProvider(object):
"""
A mixin to provide a default regex property which can vary by active
language.
"""
def __init__(self, regex):
# regex is either a string representing a regular expression, or a
# translatable string (using ugettext_lazy) representing a regular
# expression.
self._regex = regex
self._regex_dict = {}
regex = LocaleRegexDescriptor()
def describe(self):
"""
Format the URL pattern for display in warning messages.
"""
description = "'{}'".format(self.regex.pattern)
if getattr(self, 'name', False):
description += " [name='{}']".format(self.name)
return description
def _check_pattern_startswith_slash(self):
"""
Check that the pattern does not begin with a forward slash.
"""
regex_pattern = self.regex.pattern
if not settings.APPEND_SLASH:
# Skip check as it can be useful to start a URL pattern with a slash
# when APPEND_SLASH=False.
return []
if (regex_pattern.startswith('/') or regex_pattern.startswith('^/')) and not regex_pattern.endswith('/'):
warning = Warning(
"Your URL pattern {} has a regex beginning with a '/'. Remove this "
"slash as it is unnecessary. If this pattern is targeted in an "
"include(), ensure the include() pattern has a trailing '/'.".format(
self.describe()
),
id="urls.W002",
)
return [warning]
else:
return []
class RegexURLPattern(LocaleRegexProvider):
def __init__(self, regex, callback, default_args=None, name=None):
LocaleRegexProvider.__init__(self, regex)
self.callback = callback # the view
self.default_args = default_args or {}
self.name = name
def __repr__(self):
return force_str('<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern))
def check(self):
warnings = self._check_pattern_name()
if not warnings:
warnings = self._check_pattern_startswith_slash()
return warnings
def _check_pattern_name(self):
"""
Check that the pattern name does not contain a colon.
"""
if self.name is not None and ":" in self.name:
warning = Warning(
"Your URL pattern {} has a name including a ':'. Remove the colon, to "
"avoid ambiguous namespace references.".format(self.describe()),
id="urls.W003",
)
return [warning]
else:
return []
def resolve(self, path):
match = self.regex.search(path)
if match:
# If there are any named groups, use those as kwargs, ignoring
# non-named groups. Otherwise, pass all non-named arguments as
# positional arguments.
kwargs = match.groupdict()
args = () if kwargs else match.groups()
# In both cases, pass any extra_kwargs as **kwargs.
kwargs.update(self.default_args)
return ResolverMatch(self.callback, args, kwargs, self.name)
@cached_property
def lookup_str(self):
"""
A string that identifies the view (e.g. 'path.to.view_function' or
'path.to.ClassBasedView').
"""
callback = self.callback
# Python 3.5 collapses nested partials, so can change "while" to "if"
# when it's the minimum supported version.
while isinstance(callback, functools.partial):
callback = callback.func
if not hasattr(callback, '__name__'):
return callback.__module__ + "." + callback.__class__.__name__
elif six.PY3:
return callback.__module__ + "." + callback.__qualname__
else:
# PY2 does not support __qualname__
return callback.__module__ + "." + callback.__name__
class RegexURLResolver(LocaleRegexProvider):
def __init__(self, regex, urlconf_name, default_kwargs=None, app_name=None, namespace=None):
LocaleRegexProvider.__init__(self, regex)
# urlconf_name is the dotted Python path to the module defining
# urlpatterns. It may also be an object with an urlpatterns attribute
# or urlpatterns itself.
self.urlconf_name = urlconf_name
self.callback = None
self.default_kwargs = default_kwargs or {}
self.namespace = namespace
self.app_name = app_name
self._reverse_dict = {}
self._namespace_dict = {}
self._app_dict = {}
# set of dotted paths to all functions and classes that are used in
# urlpatterns
self._callback_strs = set()
self._populated = False
self._local = threading.local()
def __repr__(self):
if isinstance(self.urlconf_name, list) and len(self.urlconf_name):
# Don't bother to output the whole list, it can be huge
urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
else:
urlconf_repr = repr(self.urlconf_name)
return str('<%s %s (%s:%s) %s>') % (
self.__class__.__name__, urlconf_repr, self.app_name,
self.namespace, self.regex.pattern,
)
def check(self):
warnings = self._check_include_trailing_dollar()
for pattern in self.url_patterns:
warnings.extend(check_resolver(pattern))
if not warnings:
warnings = self._check_pattern_startswith_slash()
return warnings
def _check_include_trailing_dollar(self):
"""
Check that include is not used with a regex ending with a dollar.
"""
regex_pattern = self.regex.pattern
if regex_pattern.endswith('$') and not regex_pattern.endswith(r'\$'):
warning = Warning(
"Your URL pattern {} uses include with a regex ending with a '$'. "
"Remove the dollar from the regex to avoid problems including "
"URLs.".format(self.describe()),
id="urls.W001",
)
return [warning]
else:
return []
def _populate(self):
# Short-circuit if called recursively in this thread to prevent
# infinite recursion. Concurrent threads may call this at the same
# time and will need to continue, so set 'populating' on a
# thread-local variable.
if getattr(self._local, 'populating', False):
return
self._local.populating = True
lookups = MultiValueDict()
namespaces = {}
apps = {}
language_code = get_language()
for pattern in reversed(self.url_patterns):
if isinstance(pattern, RegexURLPattern):
self._callback_strs.add(pattern.lookup_str)
p_pattern = pattern.regex.pattern
if p_pattern.startswith('^'):
p_pattern = p_pattern[1:]
if isinstance(pattern, RegexURLResolver):
if pattern.namespace:
namespaces[pattern.namespace] = (p_pattern, pattern)
if pattern.app_name:
apps.setdefault(pattern.app_name, []).append(pattern.namespace)
else:
parent_pat = pattern.regex.pattern
for name in pattern.reverse_dict:
for matches, pat, defaults in pattern.reverse_dict.getlist(name):
new_matches = normalize(parent_pat + pat)
lookups.appendlist(
name,
(
new_matches,
p_pattern + pat,
dict(defaults, **pattern.default_kwargs),
)
)
for namespace, (prefix, sub_pattern) in pattern.namespace_dict.items():
namespaces[namespace] = (p_pattern + prefix, sub_pattern)
for app_name, namespace_list in pattern.app_dict.items():
apps.setdefault(app_name, []).extend(namespace_list)
if not getattr(pattern._local, 'populating', False):
pattern._populate()
self._callback_strs.update(pattern._callback_strs)
else:
bits = normalize(p_pattern)
lookups.appendlist(pattern.callback, (bits, p_pattern, pattern.default_args))
if pattern.name is not None:
lookups.appendlist(pattern.name, (bits, p_pattern, pattern.default_args))
self._reverse_dict[language_code] = lookups
self._namespace_dict[language_code] = namespaces
self._app_dict[language_code] = apps
self._populated = True
self._local.populating = False
@property
def reverse_dict(self):
language_code = get_language()
if language_code not in self._reverse_dict:
self._populate()
return self._reverse_dict[language_code]
@property
def namespace_dict(self):
language_code = get_language()
if language_code not in self._namespace_dict:
self._populate()
return self._namespace_dict[language_code]
@property
def app_dict(self):
language_code = get_language()
if language_code not in self._app_dict:
self._populate()
return self._app_dict[language_code]
def _is_callback(self, name):
if not self._populated:
self._populate()
return name in self._callback_strs
def resolve(self, path):
path = force_text(path) # path may be a reverse_lazy object
tried = []
match = self.regex.search(path)
if match:
new_path = path[match.end():]
for pattern in self.url_patterns:
try:
sub_match = pattern.resolve(new_path)
except Resolver404 as e:
sub_tried = e.args[0].get('tried')
if sub_tried is not None:
tried.extend([pattern] + t for t in sub_tried)
else:
tried.append([pattern])
else:
if sub_match:
# Merge captured arguments in match with submatch
sub_match_dict = dict(match.groupdict(), **self.default_kwargs)
sub_match_dict.update(sub_match.kwargs)
# If there are *any* named groups, ignore all non-named groups.
# Otherwise, pass all non-named arguments as positional arguments.
sub_match_args = sub_match.args
if not sub_match_dict:
sub_match_args = match.groups() + sub_match.args
return ResolverMatch(
sub_match.func,
sub_match_args,
sub_match_dict,
sub_match.url_name,
[self.app_name] + sub_match.app_names,
[self.namespace] + sub_match.namespaces,
)
tried.append([pattern])
raise Resolver404({'tried': tried, 'path': new_path})
raise Resolver404({'path': path})
@cached_property
def urlconf_module(self):
if isinstance(self.urlconf_name, six.string_types):
return import_module(self.urlconf_name)
else:
return self.urlconf_name
@cached_property
def url_patterns(self):
# urlconf_module might be a valid set of patterns, so we default to it
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
try:
iter(patterns)
except TypeError:
msg = (
"The included URLconf '{name}' does not appear to have any "
"patterns in it. If you see valid patterns in the file then "
"the issue is probably caused by a circular import."
)
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
return patterns
def resolve_error_handler(self, view_type):
callback = getattr(self.urlconf_module, 'handler%s' % view_type, None)
if not callback:
# No handler specified in file; use lazy import, since
# django.conf.urls imports this file.
from django.conf import urls
callback = getattr(urls, 'handler%s' % view_type)
return get_callable(callback), {}
def reverse(self, lookup_view, *args, **kwargs):
return self._reverse_with_prefix(lookup_view, '', *args, **kwargs)
def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
if args and kwargs:
raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
text_args = [force_text(v) for v in args]
text_kwargs = {k: force_text(v) for (k, v) in kwargs.items()}
if not self._populated:
self._populate()
possibilities = self.reverse_dict.getlist(lookup_view)
for possibility, pattern, defaults in possibilities:
for result, params in possibility:
if args:
if len(args) != len(params):
continue
candidate_subs = dict(zip(params, text_args))
else:
if (set(kwargs.keys()) | set(defaults.keys()) != set(params) |
set(defaults.keys())):
continue
matches = True
for k, v in defaults.items():
if kwargs.get(k, v) != v:
matches = False
break
if not matches:
continue
candidate_subs = text_kwargs
# WSGI provides decoded URLs, without %xx escapes, and the URL
# resolver operates on such URLs. First substitute arguments
# without quoting to build a decoded URL and look for a match.
# Then, if we have a match, redo the substitution with quoted
# arguments in order to return a properly encoded URL.
candidate_pat = _prefix.replace('%', '%%') + result
if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % candidate_subs, re.UNICODE):
# safe characters from `pchar` definition of RFC 3986
url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@'))
# Don't allow construction of scheme relative urls.
if url.startswith('//'):
url = '/%%2F%s' % url[2:]
return url
# lookup_view can be URL name or callable, but callables are not
# friendly in error messages.
m = getattr(lookup_view, '__module__', None)
n = getattr(lookup_view, '__name__', None)
if m is not None and n is not None:
lookup_view_s = "%s.%s" % (m, n)
else:
lookup_view_s = lookup_view
patterns = [pattern for (possibility, pattern, defaults) in possibilities]
if patterns:
if args:
arg_msg = "arguments '%s'" % (args,)
elif kwargs:
arg_msg = "keyword arguments '%s'" % (kwargs,)
else:
arg_msg = "no arguments"
msg = (
"Reverse for '%s' with %s not found. %d pattern(s) tried: %s" %
(lookup_view_s, arg_msg, len(patterns), patterns)
)
else:
msg = (
"Reverse for '%(view)s' not found. '%(view)s' is not "
"a valid view function or pattern name." % {'view': lookup_view_s}
)
raise NoReverseMatch(msg)
class LocaleRegexURLResolver(RegexURLResolver):
"""
A URL resolver that always matches the active language code as URL prefix.
Rather than taking a regex argument, we just override the ``regex``
function to always return the active language-code as regex.
"""
def __init__(
self, urlconf_name, default_kwargs=None, app_name=None, namespace=None,
prefix_default_language=True,
):
super(LocaleRegexURLResolver, self).__init__(
None, urlconf_name, default_kwargs, app_name, namespace,
)
self.prefix_default_language = prefix_default_language
@property
def regex(self):
language_code = get_language() or settings.LANGUAGE_CODE
if language_code not in self._regex_dict:
if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language:
regex_string = ''
else:
regex_string = '^%s/' % language_code
self._regex_dict[language_code] = re.compile(regex_string, re.UNICODE)
return self._regex_dict[language_code]
| mit |
vwvww/servo | tests/wpt/web-platform-tests/tools/html5lib/utils/spider.py | 436 | 4157 | #!/usr/bin/env python
"""Spider to try and find bugs in the parser. Requires httplib2 and elementtree
usage:
import spider
s = spider.Spider()
s.spider("http://www.google.com", maxURLs=100)
"""
import urllib.request, urllib.error, urllib.parse
import urllib.robotparser
import md5
import httplib2
import html5lib
from html5lib.treebuilders import etree
class Spider(object):
def __init__(self):
self.unvisitedURLs = set()
self.visitedURLs = set()
self.buggyURLs=set()
self.robotParser = urllib.robotparser.RobotFileParser()
self.contentDigest = {}
self.http = httplib2.Http(".cache")
def run(self, initialURL, maxURLs=1000):
urlNumber = 0
self.visitedURLs.add(initialURL)
content = self.loadURL(initialURL)
while maxURLs is None or urlNumber < maxURLs:
if content is not None:
self.parse(content)
urlNumber += 1
if not self.unvisitedURLs:
break
content = self.loadURL(self.unvisitedURLs.pop())
def parse(self, content):
failed = False
p = html5lib.HTMLParser(tree=etree.TreeBuilder)
try:
tree = p.parse(content)
except:
self.buggyURLs.add(self.currentURL)
failed = True
print("BUGGY:", self.currentURL)
self.visitedURLs.add(self.currentURL)
if not failed:
self.updateURLs(tree)
def loadURL(self, url):
resp, content = self.http.request(url, "GET")
self.currentURL = url
digest = md5.md5(content).hexdigest()
if digest in self.contentDigest:
content = None
self.visitedURLs.add(url)
else:
self.contentDigest[digest] = url
if resp['status'] != "200":
content = None
return content
def updateURLs(self, tree):
"""Take all the links in the current document, extract the URLs and
update the list of visited and unvisited URLs according to whether we
have seen them before or not"""
urls = set()
#Remove all links we have already visited
for link in tree.findall(".//a"):
try:
url = urllib.parse.urldefrag(link.attrib['href'])[0]
if (url and url not in self.unvisitedURLs and url
not in self.visitedURLs):
urls.add(url)
except KeyError:
pass
#Remove all non-http URLs and a dd a sutiable base URL where that is
#missing
newUrls = set()
for url in urls:
splitURL = list(urllib.parse.urlsplit(url))
if splitURL[0] != "http":
continue
if splitURL[1] == "":
splitURL[1] = urllib.parse.urlsplit(self.currentURL)[1]
newUrls.add(urllib.parse.urlunsplit(splitURL))
urls = newUrls
responseHeaders = {}
#Now we want to find the content types of the links we haven't visited
for url in urls:
try:
resp, content = self.http.request(url, "HEAD")
responseHeaders[url] = resp
except AttributeError as KeyError:
#Don't know why this happens
pass
#Remove links not of content-type html or pages not found
#XXX - need to deal with other status codes?
toVisit = set([url for url in urls if url in responseHeaders and
"html" in responseHeaders[url]['content-type'] and
responseHeaders[url]['status'] == "200"])
#Now check we are allowed to spider the page
for url in toVisit:
robotURL = list(urllib.parse.urlsplit(url)[:2])
robotURL.extend(["robots.txt", "", ""])
robotURL = urllib.parse.urlunsplit(robotURL)
self.robotParser.set_url(robotURL)
if not self.robotParser.can_fetch("*", url):
toVisit.remove(url)
self.visitedURLs.update(urls)
self.unvisitedURLs.update(toVisit)
| mpl-2.0 |
adaur/SickRage | lib/hachoir_core/field/link.py | 95 | 3176 | from hachoir_core.field import Field, FieldSet, ParserError, Bytes, MissingField
from hachoir_core.stream import FragmentedStream
class Link(Field):
def __init__(self, parent, name, *args, **kw):
Field.__init__(self, parent, name, 0, *args, **kw)
def hasValue(self):
return True
def createValue(self):
return self._parent[self.display]
def createDisplay(self):
value = self.value
if value is None:
return "<%s>" % MissingField.__name__
return value.path
def _getField(self, name, const):
target = self.value
assert self != target
return target._getField(name, const)
class Fragments:
def __init__(self, first):
self.first = first
def __iter__(self):
fragment = self.first
while fragment is not None:
data = fragment.getData()
yield data and data.size
fragment = fragment.next
class Fragment(FieldSet):
_first = None
def __init__(self, *args, **kw):
FieldSet.__init__(self, *args, **kw)
self._field_generator = self._createFields(self._field_generator)
if self.__class__.createFields == Fragment.createFields:
self._getData = lambda: self
def getData(self):
try:
return self._getData()
except MissingField, e:
self.error(str(e))
return None
def setLinks(self, first, next=None):
self._first = first or self
self._next = next
self._feedLinks = lambda: self
return self
def _feedLinks(self):
while self._first is None and self.readMoreFields(1):
pass
if self._first is None:
raise ParserError("first is None")
return self
first = property(lambda self: self._feedLinks()._first)
def _getNext(self):
next = self._feedLinks()._next
if callable(next):
self._next = next = next()
return next
next = property(_getNext)
def _createInputStream(self, **args):
first = self.first
if first is self and hasattr(first, "_getData"):
return FragmentedStream(first, packets=Fragments(first), **args)
return FieldSet._createInputStream(self, **args)
def _createFields(self, field_generator):
if self._first is None:
for field in field_generator:
if self._first is not None:
break
yield field
else:
raise ParserError("Fragment.setLinks not called")
else:
field = None
if self._first is not self:
link = Link(self, "first", None)
link._getValue = lambda: self._first
yield link
if self._next:
link = Link(self, "next", None)
link.createValue = self._getNext
yield link
if field:
yield field
for field in field_generator:
yield field
def createFields(self):
if self._size is None:
self._size = self._getSize()
yield Bytes(self, "data", self._size/8)
| gpl-3.0 |
lokirius/python-for-android | python3-alpha/python3-src/Lib/idlelib/RemoteDebugger.py | 137 | 12029 | """Support for remote Python debugging.
Some ASCII art to describe the structure:
IN PYTHON SUBPROCESS # IN IDLE PROCESS
#
# oid='gui_adapter'
+----------+ # +------------+ +-----+
| GUIProxy |--remote#call-->| GUIAdapter |--calls-->| GUI |
+-----+--calls-->+----------+ # +------------+ +-----+
| Idb | # /
+-----+<-calls--+------------+ # +----------+<--calls-/
| IdbAdapter |<--remote#call--| IdbProxy |
+------------+ # +----------+
oid='idb_adapter' #
The purpose of the Proxy and Adapter classes is to translate certain
arguments and return values that cannot be transported through the RPC
barrier, in particular frame and traceback objects.
"""
import types
from idlelib import rpc
from idlelib import Debugger
debugging = 0
idb_adap_oid = "idb_adapter"
gui_adap_oid = "gui_adapter"
#=======================================
#
# In the PYTHON subprocess:
frametable = {}
dicttable = {}
codetable = {}
tracebacktable = {}
def wrap_frame(frame):
fid = id(frame)
frametable[fid] = frame
return fid
def wrap_info(info):
"replace info[2], a traceback instance, by its ID"
if info is None:
return None
else:
traceback = info[2]
assert isinstance(traceback, types.TracebackType)
traceback_id = id(traceback)
tracebacktable[traceback_id] = traceback
modified_info = (info[0], info[1], traceback_id)
return modified_info
class GUIProxy:
def __init__(self, conn, gui_adap_oid):
self.conn = conn
self.oid = gui_adap_oid
def interaction(self, message, frame, info=None):
# calls rpc.SocketIO.remotecall() via run.MyHandler instance
# pass frame and traceback object IDs instead of the objects themselves
self.conn.remotecall(self.oid, "interaction",
(message, wrap_frame(frame), wrap_info(info)),
{})
class IdbAdapter:
def __init__(self, idb):
self.idb = idb
#----------called by an IdbProxy----------
def set_step(self):
self.idb.set_step()
def set_quit(self):
self.idb.set_quit()
def set_continue(self):
self.idb.set_continue()
def set_next(self, fid):
frame = frametable[fid]
self.idb.set_next(frame)
def set_return(self, fid):
frame = frametable[fid]
self.idb.set_return(frame)
def get_stack(self, fid, tbid):
frame = frametable[fid]
if tbid is None:
tb = None
else:
tb = tracebacktable[tbid]
stack, i = self.idb.get_stack(frame, tb)
stack = [(wrap_frame(frame), k) for frame, k in stack]
return stack, i
def run(self, cmd):
import __main__
self.idb.run(cmd, __main__.__dict__)
def set_break(self, filename, lineno):
msg = self.idb.set_break(filename, lineno)
return msg
def clear_break(self, filename, lineno):
msg = self.idb.clear_break(filename, lineno)
return msg
def clear_all_file_breaks(self, filename):
msg = self.idb.clear_all_file_breaks(filename)
return msg
#----------called by a FrameProxy----------
def frame_attr(self, fid, name):
frame = frametable[fid]
return getattr(frame, name)
def frame_globals(self, fid):
frame = frametable[fid]
dict = frame.f_globals
did = id(dict)
dicttable[did] = dict
return did
def frame_locals(self, fid):
frame = frametable[fid]
dict = frame.f_locals
did = id(dict)
dicttable[did] = dict
return did
def frame_code(self, fid):
frame = frametable[fid]
code = frame.f_code
cid = id(code)
codetable[cid] = code
return cid
#----------called by a CodeProxy----------
def code_name(self, cid):
code = codetable[cid]
return code.co_name
def code_filename(self, cid):
code = codetable[cid]
return code.co_filename
#----------called by a DictProxy----------
def dict_keys(self, did):
raise NotImplemented("dict_keys not public or pickleable")
## dict = dicttable[did]
## return dict.keys()
### Needed until dict_keys is type is finished and pickealable.
### Will probably need to extend rpc.py:SocketIO._proxify at that time.
def dict_keys_list(self, did):
dict = dicttable[did]
return list(dict.keys())
def dict_item(self, did, key):
dict = dicttable[did]
value = dict[key]
value = repr(value) ### can't pickle module 'builtins'
return value
#----------end class IdbAdapter----------
def start_debugger(rpchandler, gui_adap_oid):
"""Start the debugger and its RPC link in the Python subprocess
Start the subprocess side of the split debugger and set up that side of the
RPC link by instantiating the GUIProxy, Idb debugger, and IdbAdapter
objects and linking them together. Register the IdbAdapter with the
RPCServer to handle RPC requests from the split debugger GUI via the
IdbProxy.
"""
gui_proxy = GUIProxy(rpchandler, gui_adap_oid)
idb = Debugger.Idb(gui_proxy)
idb_adap = IdbAdapter(idb)
rpchandler.register(idb_adap_oid, idb_adap)
return idb_adap_oid
#=======================================
#
# In the IDLE process:
class FrameProxy:
def __init__(self, conn, fid):
self._conn = conn
self._fid = fid
self._oid = "idb_adapter"
self._dictcache = {}
def __getattr__(self, name):
if name[:1] == "_":
raise AttributeError(name)
if name == "f_code":
return self._get_f_code()
if name == "f_globals":
return self._get_f_globals()
if name == "f_locals":
return self._get_f_locals()
return self._conn.remotecall(self._oid, "frame_attr",
(self._fid, name), {})
def _get_f_code(self):
cid = self._conn.remotecall(self._oid, "frame_code", (self._fid,), {})
return CodeProxy(self._conn, self._oid, cid)
def _get_f_globals(self):
did = self._conn.remotecall(self._oid, "frame_globals",
(self._fid,), {})
return self._get_dict_proxy(did)
def _get_f_locals(self):
did = self._conn.remotecall(self._oid, "frame_locals",
(self._fid,), {})
return self._get_dict_proxy(did)
def _get_dict_proxy(self, did):
if did in self._dictcache:
return self._dictcache[did]
dp = DictProxy(self._conn, self._oid, did)
self._dictcache[did] = dp
return dp
class CodeProxy:
def __init__(self, conn, oid, cid):
self._conn = conn
self._oid = oid
self._cid = cid
def __getattr__(self, name):
if name == "co_name":
return self._conn.remotecall(self._oid, "code_name",
(self._cid,), {})
if name == "co_filename":
return self._conn.remotecall(self._oid, "code_filename",
(self._cid,), {})
class DictProxy:
def __init__(self, conn, oid, did):
self._conn = conn
self._oid = oid
self._did = did
## def keys(self):
## return self._conn.remotecall(self._oid, "dict_keys", (self._did,), {})
# 'temporary' until dict_keys is a pickleable built-in type
def keys(self):
return self._conn.remotecall(self._oid,
"dict_keys_list", (self._did,), {})
def __getitem__(self, key):
return self._conn.remotecall(self._oid, "dict_item",
(self._did, key), {})
def __getattr__(self, name):
##print("*** Failed DictProxy.__getattr__:", name)
raise AttributeError(name)
class GUIAdapter:
def __init__(self, conn, gui):
self.conn = conn
self.gui = gui
def interaction(self, message, fid, modified_info):
##print("*** Interaction: (%s, %s, %s)" % (message, fid, modified_info))
frame = FrameProxy(self.conn, fid)
self.gui.interaction(message, frame, modified_info)
class IdbProxy:
def __init__(self, conn, shell, oid):
self.oid = oid
self.conn = conn
self.shell = shell
def call(self, methodname, *args, **kwargs):
##print("*** IdbProxy.call %s %s %s" % (methodname, args, kwargs))
value = self.conn.remotecall(self.oid, methodname, args, kwargs)
##print("*** IdbProxy.call %s returns %r" % (methodname, value))
return value
def run(self, cmd, locals):
# Ignores locals on purpose!
seq = self.conn.asyncqueue(self.oid, "run", (cmd,), {})
self.shell.interp.active_seq = seq
def get_stack(self, frame, tbid):
# passing frame and traceback IDs, not the objects themselves
stack, i = self.call("get_stack", frame._fid, tbid)
stack = [(FrameProxy(self.conn, fid), k) for fid, k in stack]
return stack, i
def set_continue(self):
self.call("set_continue")
def set_step(self):
self.call("set_step")
def set_next(self, frame):
self.call("set_next", frame._fid)
def set_return(self, frame):
self.call("set_return", frame._fid)
def set_quit(self):
self.call("set_quit")
def set_break(self, filename, lineno):
msg = self.call("set_break", filename, lineno)
return msg
def clear_break(self, filename, lineno):
msg = self.call("clear_break", filename, lineno)
return msg
def clear_all_file_breaks(self, filename):
msg = self.call("clear_all_file_breaks", filename)
return msg
def start_remote_debugger(rpcclt, pyshell):
"""Start the subprocess debugger, initialize the debugger GUI and RPC link
Request the RPCServer start the Python subprocess debugger and link. Set
up the Idle side of the split debugger by instantiating the IdbProxy,
debugger GUI, and debugger GUIAdapter objects and linking them together.
Register the GUIAdapter with the RPCClient to handle debugger GUI
interaction requests coming from the subprocess debugger via the GUIProxy.
The IdbAdapter will pass execution and environment requests coming from the
Idle debugger GUI to the subprocess debugger via the IdbProxy.
"""
global idb_adap_oid
idb_adap_oid = rpcclt.remotecall("exec", "start_the_debugger",\
(gui_adap_oid,), {})
idb_proxy = IdbProxy(rpcclt, pyshell, idb_adap_oid)
gui = Debugger.Debugger(pyshell, idb_proxy)
gui_adap = GUIAdapter(rpcclt, gui)
rpcclt.register(gui_adap_oid, gui_adap)
return gui
def close_remote_debugger(rpcclt):
"""Shut down subprocess debugger and Idle side of debugger RPC link
Request that the RPCServer shut down the subprocess debugger and link.
Unregister the GUIAdapter, which will cause a GC on the Idle process
debugger and RPC link objects. (The second reference to the debugger GUI
is deleted in PyShell.close_remote_debugger().)
"""
close_subprocess_debugger(rpcclt)
rpcclt.unregister(gui_adap_oid)
def close_subprocess_debugger(rpcclt):
rpcclt.remotecall("exec", "stop_the_debugger", (idb_adap_oid,), {})
def restart_subprocess_debugger(rpcclt):
idb_adap_oid_ret = rpcclt.remotecall("exec", "start_the_debugger",\
(gui_adap_oid,), {})
assert idb_adap_oid_ret == idb_adap_oid, 'Idb restarted with different oid'
| apache-2.0 |
kustodian/ansible | lib/ansible/modules/network/check_point/cp_mgmt_service_icmp6.py | 20 | 5607 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Ansible module to manage Check Point Firewall (c) 2019
#
# 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 Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: cp_mgmt_service_icmp6
short_description: Manages service-icmp6 objects on Check Point over Web Services API
description:
- Manages service-icmp6 objects on Check Point devices including creating, updating and removing objects.
- All operations are performed over Web Services API.
version_added: "2.9"
author: "Or Soffer (@chkp-orso)"
options:
name:
description:
- Object name.
type: str
required: True
icmp_code:
description:
- As listed in, <a href="http,//www.iana.org/assignments/icmp-parameters" target="_blank">RFC 792</a>.
type: int
icmp_type:
description:
- As listed in, <a href="http,//www.iana.org/assignments/icmp-parameters" target="_blank">RFC 792</a>.
type: int
keep_connections_open_after_policy_installation:
description:
- Keep connections open after policy has been installed even if they are not allowed under the new policy. This overrides the settings in the
Connection Persistence page. If you change this property, the change will not affect open connections, but only future connections.
type: bool
tags:
description:
- Collection of tag identifiers.
type: list
color:
description:
- Color of the object. Should be one of existing colors.
type: str
choices: ['aquamarine', 'black', 'blue', 'crete blue', 'burlywood', 'cyan', 'dark green', 'khaki', 'orchid', 'dark orange', 'dark sea green',
'pink', 'turquoise', 'dark blue', 'firebrick', 'brown', 'forest green', 'gold', 'dark gold', 'gray', 'dark gray', 'light green', 'lemon chiffon',
'coral', 'sea green', 'sky blue', 'magenta', 'purple', 'slate blue', 'violet red', 'navy blue', 'olive', 'orange', 'red', 'sienna', 'yellow']
comments:
description:
- Comments string.
type: str
details_level:
description:
- The level of detail for some of the fields in the response can vary from showing only the UID value of the object to a fully detailed
representation of the object.
type: str
choices: ['uid', 'standard', 'full']
groups:
description:
- Collection of group identifiers.
type: list
ignore_warnings:
description:
- Apply changes ignoring warnings.
type: bool
ignore_errors:
description:
- Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.
type: bool
extends_documentation_fragment: checkpoint_objects
"""
EXAMPLES = """
- name: add-service-icmp6
cp_mgmt_service_icmp6:
icmp_code: 7
icmp_type: 5
name: Icmp1
state: present
- name: set-service-icmp6
cp_mgmt_service_icmp6:
icmp_code: 13
icmp_type: 45
name: icmp1
state: present
- name: delete-service-icmp6
cp_mgmt_service_icmp6:
name: icmp2
state: absent
"""
RETURN = """
cp_mgmt_service_icmp6:
description: The checkpoint object created or updated.
returned: always, except when deleting the object.
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.checkpoint.checkpoint import checkpoint_argument_spec_for_objects, api_call
def main():
argument_spec = dict(
name=dict(type='str', required=True),
icmp_code=dict(type='int'),
icmp_type=dict(type='int'),
keep_connections_open_after_policy_installation=dict(type='bool'),
tags=dict(type='list'),
color=dict(type='str', choices=['aquamarine', 'black', 'blue', 'crete blue', 'burlywood', 'cyan', 'dark green',
'khaki', 'orchid', 'dark orange', 'dark sea green', 'pink', 'turquoise', 'dark blue', 'firebrick', 'brown',
'forest green', 'gold', 'dark gold', 'gray', 'dark gray', 'light green', 'lemon chiffon', 'coral', 'sea green',
'sky blue', 'magenta', 'purple', 'slate blue', 'violet red', 'navy blue', 'olive', 'orange', 'red', 'sienna',
'yellow']),
comments=dict(type='str'),
details_level=dict(type='str', choices=['uid', 'standard', 'full']),
groups=dict(type='list'),
ignore_warnings=dict(type='bool'),
ignore_errors=dict(type='bool')
)
argument_spec.update(checkpoint_argument_spec_for_objects)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
api_call_object = 'service-icmp6'
result = api_call(module, api_call_object)
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
GNS3/gns3-server | gns3server/controller/topology.py | 1 | 29949 | #!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies 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 License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import html
import json
import copy
import uuid
import glob
import shutil
import zipfile
import aiohttp
import jsonschema
from ..version import __version__
from ..schemas.topology import TOPOLOGY_SCHEMA
from ..schemas import dynamips_vm
from ..utils.qt import qt_font_to_style
from ..compute.dynamips import PLATFORMS_DEFAULT_RAM
import logging
log = logging.getLogger(__name__)
GNS3_FILE_FORMAT_REVISION = 9
def _check_topology_schema(topo):
try:
jsonschema.validate(topo, TOPOLOGY_SCHEMA)
# Check the nodes property against compute schemas
for node in topo["topology"].get("nodes", []):
schema = None
if node["node_type"] == "dynamips":
schema = copy.deepcopy(dynamips_vm.VM_CREATE_SCHEMA)
if schema:
# Properties send to compute but in an other place in topology
delete_properties = ["name", "node_id"]
for prop in delete_properties:
del schema["properties"][prop]
schema["required"] = [p for p in schema["required"] if p not in delete_properties]
jsonschema.validate(node.get("properties", {}), schema)
except jsonschema.ValidationError as e:
error = "Invalid data in topology file: {} in schema: {}".format(
e.message,
json.dumps(e.schema))
log.debug(error)
raise aiohttp.web.HTTPConflict(text=error)
def project_to_topology(project):
"""
:return: A dictionary with the topology ready to dump to a .gns3
"""
data = {
"project_id": project.id,
"name": project.name,
"auto_start": project.auto_start,
"auto_open": project.auto_open,
"auto_close": project.auto_close,
"scene_width": project.scene_width,
"scene_height": project.scene_height,
"zoom": project.zoom,
"show_layers": project.show_layers,
"snap_to_grid": project.snap_to_grid,
"show_grid": project.show_grid,
"grid_size": project.grid_size,
"drawing_grid_size": project.drawing_grid_size,
"show_interface_labels": project.show_interface_labels,
"variables": project.variables,
"supplier": project.supplier,
"topology": {
"nodes": [],
"links": [],
"computes": [],
"drawings": []
},
"type": "topology",
"revision": GNS3_FILE_FORMAT_REVISION,
"version": __version__
}
for node in project.nodes.values():
if hasattr(node, "__json__"):
data["topology"]["nodes"].append(node.__json__(topology_dump=True))
else:
data["topology"]["nodes"].append(node)
for link in project.links.values():
if hasattr(link, "__json__"):
data["topology"]["links"].append(link.__json__(topology_dump=True))
else:
data["topology"]["links"].append(link)
for drawing in project.drawings.values():
if hasattr(drawing, "__json__"):
data["topology"]["drawings"].append(drawing.__json__(topology_dump=True))
else:
data["topology"]["drawings"].append(drawing)
for compute in project.computes:
if hasattr(compute, "__json__"):
compute = compute.__json__(topology_dump=True)
if compute["compute_id"] not in ("vm", "local", ):
data["topology"]["computes"].append(compute)
elif isinstance(compute, dict):
data["topology"]["computes"].append(compute)
_check_topology_schema(data)
return data
def load_topology(path):
"""
Open a topology file, patch it for last GNS3 release and return it
"""
log.debug("Read topology %s", path)
try:
with open(path, encoding="utf-8") as f:
topo = json.load(f)
except (OSError, UnicodeDecodeError, ValueError) as e:
raise aiohttp.web.HTTPConflict(text="Could not load topology {}: {}".format(path, str(e)))
if topo.get("revision", 0) > GNS3_FILE_FORMAT_REVISION:
raise aiohttp.web.HTTPConflict(text="This project was created with more recent version of GNS3 (file revision: {}). Please upgrade GNS3 to version {} or later".format(topo["revision"], topo["version"]))
changed = False
if "revision" not in topo or topo["revision"] < GNS3_FILE_FORMAT_REVISION:
# Convert the topology if this is an old one but backup the file first
try:
shutil.copy(path, path + ".backup{}".format(topo.get("revision", 0)))
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can't write backup of the topology {}: {}".format(path, str(e)))
changed = True
# update the version because we converted the topology
topo["version"] = __version__
if "revision" not in topo or topo["revision"] < 5:
topo = _convert_1_3_later(topo, path)
# Version before GNS3 2.0 alpha 4
if topo["revision"] < 6:
topo = _convert_2_0_0_alpha(topo, path)
# Version before GNS3 2.0 beta 3
if topo["revision"] < 7:
topo = _convert_2_0_0_beta_2(topo, path)
# Version before GNS3 2.1
if topo["revision"] < 8:
topo = _convert_2_0_0(topo, path)
# Version before GNS3 2.1
if topo["revision"] < 9:
topo = _convert_2_1_0(topo, path)
# Version GNS3 2.2 dev (for project created with 2.2dev).
# Appliance ID has been replaced by Template ID
if topo["revision"] == 9:
for node in topo.get("topology", {}).get("nodes", []):
if "appliance_id" in node:
node["template_id"] = node["appliance_id"]
del node["appliance_id"]
# make sure console_type is not None but "none" string
if "console_type" in node and node["console_type"] is None:
node["console_type"] = "none"
# make sure we can open a project with empty variable name
variables = topo.get("variables")
if variables:
topo["variables"] = [var for var in variables if var.get("name")]
try:
_check_topology_schema(topo)
except aiohttp.web.HTTPConflict as e:
log.error("Can't load the topology %s", path)
raise e
if changed:
try:
with open(path, "w+", encoding="utf-8") as f:
json.dump(topo, f, indent=4, sort_keys=True)
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can't write the topology {}: {}".format(path, str(e)))
return topo
def _convert_2_1_0(topo, topo_path):
"""
Convert topologies from GNS3 2.1.x to 2.2
Changes:
* Removed acpi_shutdown option from Qemu, VMware and VirtualBox
"""
topo["revision"] = 9
if "grid_size" in topo:
# drawing_grid_size should be the same size as grid_size
# to avoid overlapping grids
topo["drawing_grid_size"] = topo["grid_size"]
for node in topo.get("topology", {}).get("nodes", []):
# make sure console_type is not None but "none" string
if "console_type" in node and node["console_type"] is None:
node["console_type"] = "none"
if "properties" in node:
if node["node_type"] in ("qemu", "vmware", "virtualbox"):
if "acpi_shutdown" in node["properties"]:
if node["properties"]["acpi_shutdown"] is True:
node["properties"]["on_close"] = "save_vm_sate"
else:
node["properties"]["on_close"] = "power_off"
del node["properties"]["acpi_shutdown"]
if "save_vm_state" in node["properties"]:
del node["properties"]["save_vm_state"]
return topo
def _convert_2_0_0(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 to 2.1
Changes:
* Remove startup_script_path from VPCS and base config file for IOU and Dynamips
"""
topo["revision"] = 8
for node in topo.get("topology", {}).get("nodes", []):
if "properties" in node:
if node["node_type"] == "vpcs":
if "startup_script_path" in node["properties"]:
del node["properties"]["startup_script_path"]
if "startup_script" in node["properties"]:
del node["properties"]["startup_script"]
elif node["node_type"] == "dynamips" or node["node_type"] == "iou":
if "startup_config" in node["properties"]:
del node["properties"]["startup_config"]
if "private_config" in node["properties"]:
del node["properties"]["private_config"]
if "startup_config_content" in node["properties"]:
del node["properties"]["startup_config_content"]
if "private_config_content" in node["properties"]:
del node["properties"]["private_config_content"]
return topo
def _convert_2_0_0_beta_2(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 beta 2 to beta 3.
Changes:
* Node id folders for dynamips
"""
topo_dir = os.path.dirname(topo_path)
topo["revision"] = 7
for node in topo.get("topology", {}).get("nodes", []):
if node["node_type"] == "dynamips":
node_id = node["node_id"]
dynamips_id = node["properties"]["dynamips_id"]
dynamips_dir = os.path.join(topo_dir, "project-files", "dynamips")
node_dir = os.path.join(dynamips_dir, node_id)
try:
os.makedirs(os.path.join(node_dir, "configs"), exist_ok=True)
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))):
shutil.move(path, os.path.join(node_dir, os.path.basename(path)))
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))):
shutil.move(path, os.path.join(node_dir, "configs", os.path.basename(path)))
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can't convert project {}: {}".format(topo_path, str(e)))
return topo
def _convert_2_0_0_alpha(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final.
Changes:
* No more serial console
* No more option for VMware / VirtualBox remote console (always use telnet)
"""
topo["revision"] = 6
for node in topo.get("topology", {}).get("nodes", []):
if node.get("console_type") == "serial":
node["console_type"] = "telnet"
if node["node_type"] in ("vmware", "virtualbox"):
prop = node.get("properties")
if "enable_remote_console" in prop:
del prop["enable_remote_console"]
return topo
def _convert_1_3_later(topo, topo_path):
"""
Convert topologies from 1_3 to the new file format
Look in tests/topologies/README.rst for instructions to test changes here
"""
topo_dir = os.path.dirname(topo_path)
_convert_snapshots(topo_dir)
new_topo = {
"type": "topology",
"revision": 5,
"version": __version__,
"auto_start": topo.get("auto_start", False),
"name": topo["name"],
"project_id": topo.get("project_id"),
"topology": {
"links": [],
"drawings": [],
"computes": [],
"nodes": []
}
}
if new_topo["project_id"] is None:
new_topo["project_id"] = str(uuid.uuid4()) # Could arrive for topologues with drawing only
if "topology" not in topo:
return new_topo
topo = topo["topology"]
# Create computes
server_id_to_compute_id = {}
for server in topo.get("servers", []):
compute = {
"host": server.get("host", "localhost"),
"port": server.get("port", 3080),
"protocol": server.get("protocol", "http")
}
if server["local"]:
compute["compute_id"] = "local"
compute["name"] = "Local"
elif server.get("vm", False):
compute["compute_id"] = "vm"
compute["name"] = "GNS3 VM"
else:
compute["name"] = "Remote {}".format(server["id"])
compute["compute_id"] = str(uuid.uuid4())
server_id_to_compute_id[server["id"]] = compute["compute_id"]
new_topo["topology"]["computes"].append(compute)
# Create nodes
ports = {}
node_id_to_node_uuid = {}
for old_node in topo.get("nodes", []):
node = {}
node["console"] = old_node["properties"].get("console", None)
try:
node["compute_id"] = server_id_to_compute_id[old_node["server_id"]]
except KeyError:
node["compute_id"] = "local"
node["console_type"] = old_node["properties"].get("console_type", "telnet")
if "label" in old_node:
node["name"] = old_node["label"]["text"]
node["label"] = _convert_label(old_node["label"])
else:
node["name"] = old_node["properties"]["name"]
node["node_id"] = old_node.get("vm_id", str(uuid.uuid4()))
node["symbol"] = old_node.get("symbol", None)
# Compatibility with <= 1.3
if node["symbol"] is None and "default_symbol" in old_node:
if old_node["default_symbol"].endswith("normal.svg"):
node["symbol"] = old_node["default_symbol"][:-11] + ".svg"
else:
node["symbol"] = old_node["default_symbol"]
node["x"] = int(old_node["x"])
node["y"] = int(old_node["y"])
node["z"] = int(old_node.get("z", 1))
node["port_name_format"] = old_node.get("port_name_format", "Ethernet{0}")
node["port_segment_size"] = int(old_node.get("port_segment_size", "0"))
node["first_port_name"] = old_node.get("first_port_name")
node["properties"] = {}
# Some old dynamips node don't have type
if "type" not in old_node:
old_node["type"] = old_node["properties"]["platform"].upper()
if old_node["type"] == "VPCSDevice":
node["node_type"] = "vpcs"
elif old_node["type"] == "QemuVM":
node = _convert_qemu_node(node, old_node)
elif old_node["type"] == "DockerVM":
node["node_type"] = "docker"
if node["symbol"] is None:
node["symbol"] = ":/symbols/docker_guest.svg"
elif old_node["type"] == "ATMSwitch":
node["node_type"] = "atm_switch"
node["symbol"] = ":/symbols/atm_switch.svg"
node["console_type"] = None
elif old_node["type"] == "EthernetHub":
node["node_type"] = "ethernet_hub"
node["console_type"] = None
node["symbol"] = ":/symbols/hub.svg"
node["properties"]["ports_mapping"] = []
for port in old_node.get("ports", []):
node["properties"]["ports_mapping"].append({
"name": "Ethernet{}".format(port["port_number"] - 1),
"port_number": port["port_number"] - 1
})
elif old_node["type"] == "EthernetSwitch":
node["node_type"] = "ethernet_switch"
node["symbol"] = ":/symbols/ethernet_switch.svg"
node["console_type"] = None
node["properties"]["ports_mapping"] = []
for port in old_node.get("ports", []):
node["properties"]["ports_mapping"].append({
"name": "Ethernet{}".format(port["port_number"] - 1),
"port_number": port["port_number"] - 1,
"type": port["type"],
"vlan": port["vlan"]
})
elif old_node["type"] == "FrameRelaySwitch":
node["node_type"] = "frame_relay_switch"
node["symbol"] = ":/symbols/frame_relay_switch.svg"
node["console_type"] = None
elif old_node["type"].upper() in ["C1700", "C2600", "C2691", "C3600", "C3620", "C3640", "C3660", "C3725", "C3745", "C7200", "EtherSwitchRouter"]:
if node["symbol"] is None:
node["symbol"] = ":/symbols/router.svg"
node["node_type"] = "dynamips"
node["properties"]["dynamips_id"] = old_node.get("dynamips_id")
if "platform" not in node["properties"] and old_node["type"].upper().startswith("C"):
node["properties"]["platform"] = old_node["type"].lower()
if node["properties"]["platform"].startswith("c36"):
node["properties"]["platform"] = "c3600"
if "ram" not in node["properties"] and old_node["type"].startswith("C"):
node["properties"]["ram"] = PLATFORMS_DEFAULT_RAM[old_node["type"].lower()]
elif old_node["type"] == "VMwareVM":
node["node_type"] = "vmware"
node["properties"]["linked_clone"] = old_node.get("linked_clone", False)
if node["symbol"] is None:
node["symbol"] = ":/symbols/vmware_guest.svg"
elif old_node["type"] == "VirtualBoxVM":
node["node_type"] = "virtualbox"
node["properties"]["linked_clone"] = old_node.get("linked_clone", False)
if node["symbol"] is None:
node["symbol"] = ":/symbols/vbox_guest.svg"
elif old_node["type"] == "IOUDevice":
node["node_type"] = "iou"
node["port_name_format"] = old_node.get("port_name_format", "Ethernet{segment0}/{port0}")
node["port_segment_size"] = int(old_node.get("port_segment_size", "4"))
if node["symbol"] is None:
if "l2" in node["properties"].get("path", ""):
node["symbol"] = ":/symbols/multilayer_switch.svg"
else:
node["symbol"] = ":/symbols/router.svg"
elif old_node["type"] == "Cloud":
symbol = old_node.get("symbol", ":/symbols/cloud.svg")
old_node["ports"] = _create_cloud(node, old_node, symbol)
elif old_node["type"] == "Host":
symbol = old_node.get("symbol", ":/symbols/computer.svg")
old_node["ports"] = _create_cloud(node, old_node, symbol)
else:
raise aiohttp.web.HTTPConflict(text="Conversion of {} is not supported".format(old_node["type"]))
for prop in old_node.get("properties", {}):
if prop not in ["console", "name", "console_type", "console_host", "use_ubridge"]:
node["properties"][prop] = old_node["properties"][prop]
node_id_to_node_uuid[old_node["id"]] = node["node_id"]
for port in old_node.get("ports", []):
if node["node_type"] in ("ethernet_hub", "ethernet_switch"):
port["port_number"] -= 1
ports[port["id"]] = port
new_topo["topology"]["nodes"].append(node)
# Create links
for old_link in topo.get("links", []):
try:
nodes = []
source_node = {
"adapter_number": ports[old_link["source_port_id"]].get("adapter_number", 0),
"port_number": ports[old_link["source_port_id"]].get("port_number", 0),
"node_id": node_id_to_node_uuid[old_link["source_node_id"]]
}
nodes.append(source_node)
destination_node = {
"adapter_number": ports[old_link["destination_port_id"]].get("adapter_number", 0),
"port_number": ports[old_link["destination_port_id"]].get("port_number", 0),
"node_id": node_id_to_node_uuid[old_link["destination_node_id"]]
}
nodes.append(destination_node)
except KeyError:
continue
link = {
"link_id": str(uuid.uuid4()),
"nodes": nodes
}
new_topo["topology"]["links"].append(link)
# Ellipse
for ellipse in topo.get("ellipses", []):
svg = '<svg height="{height}" width="{width}"><ellipse cx="{cx}" cy="{cy}" fill="{fill}" fill-opacity="1.0" rx="{rx}" ry="{ry}" {border_style} /></svg>'.format(
height=int(ellipse["height"]),
width=int(ellipse["width"]),
cx=int(ellipse["width"] / 2),
cy=int(ellipse["height"] / 2),
rx=int(ellipse["width"] / 2),
ry=int(ellipse["height"] / 2),
fill=ellipse.get("color", "#ffffff"),
border_style=_convert_border_style(ellipse)
)
new_ellipse = {
"drawing_id": str(uuid.uuid4()),
"x": int(ellipse["x"]),
"y": int(ellipse["y"]),
"z": int(ellipse.get("z", 0)),
"rotation": int(ellipse.get("rotation", 0)),
"svg": svg
}
new_topo["topology"]["drawings"].append(new_ellipse)
# Notes
for note in topo.get("notes", []):
font_info = note.get("font", "TypeWriter,10,-1,5,75,0,0,0,0,0").split(",")
if font_info[4] == "75":
weight = "bold"
else:
weight = "normal"
if font_info[5] == "1":
style = "italic"
else:
style = "normal"
svg = '<svg height="{height}" width="{width}"><text fill="{fill}" fill-opacity="{opacity}" font-family="{family}" font-size="{size}" font-weight="{weight}" font-style="{style}">{text}</text></svg>'.format(
height=int(font_info[1]) * 2,
width=int(font_info[1]) * len(note["text"]),
fill="#" + note.get("color", "#00000000")[-6:],
opacity=round(1.0 / 255 * int(note.get("color", "#ffffffff")[:3][-2:], base=16), 2), # Extract the alpha channel from the hexa version
family=font_info[0],
size=int(font_info[1]),
weight=weight,
style=style,
text=html.escape(note["text"])
)
new_note = {
"drawing_id": str(uuid.uuid4()),
"x": int(note["x"]),
"y": int(note["y"]),
"z": int(note.get("z", 0)),
"rotation": int(note.get("rotation", 0)),
"svg": svg
}
new_topo["topology"]["drawings"].append(new_note)
# Images
for image in topo.get("images", []):
img_path = image["path"]
# Absolute image path are rewrite to project specific image
if os.path.abspath(img_path):
try:
os.makedirs(os.path.join(topo_dir, "images"), exist_ok=True)
shutil.copy(img_path, os.path.join(topo_dir, "images", os.path.basename(img_path)))
except OSError:
pass
new_image = {
"drawing_id": str(uuid.uuid4()),
"x": int(image["x"]),
"y": int(image["y"]),
"z": int(image.get("z", 0)),
"rotation": int(image.get("rotation", 0)),
"svg": os.path.basename(img_path)
}
new_topo["topology"]["drawings"].append(new_image)
# Rectangles
for rectangle in topo.get("rectangles", []):
svg = '<svg height="{height}" width="{width}"><rect fill="{fill}" fill-opacity="1.0" height="{height}" width="{width}" {border_style} /></svg>'.format(
height=int(rectangle["height"]),
width=int(rectangle["width"]),
fill=rectangle.get("color", "#ffffff"),
border_style=_convert_border_style(rectangle)
)
new_rectangle = {
"drawing_id": str(uuid.uuid4()),
"x": int(rectangle["x"]),
"y": int(rectangle["y"]),
"z": int(rectangle.get("z", 0)),
"rotation": int(rectangle.get("rotation", 0)),
"svg": svg
}
new_topo["topology"]["drawings"].append(new_rectangle)
# Convert instructions.txt to README.txt
instructions_path = os.path.join(topo_dir, "instructions.txt")
readme_path = os.path.join(topo_dir, "README.txt")
if os.path.exists(instructions_path) and not os.path.exists(readme_path):
shutil.move(instructions_path, readme_path)
return new_topo
def _convert_border_style(element):
QT_DASH_TO_SVG = {
2: "25, 25",
3: "5, 25",
4: "5, 25, 25",
5: "25, 25, 5, 25, 5"
}
border_style = int(element.get("border_style", 0))
style = ""
if border_style == 1: # No border
return ""
elif border_style == 0:
pass # Solid line
else:
style += 'stroke-dasharray="{}" '.format(QT_DASH_TO_SVG[border_style])
style += 'stroke="{stroke}" stroke-width="{stroke_width}"'.format(
stroke=element.get("border_color", "#000000"),
stroke_width=element.get("border_width", 2)
)
return style
def _convert_label(label):
"""
Convert a label from 1.X to the new format
"""
style = qt_font_to_style(label.get("font"), label.get("color"))
return {
"text": html.escape(label["text"]),
"rotation": 0,
"style": style,
"x": int(label["x"]),
"y": int(label["y"])
}
def _create_cloud(node, old_node, icon):
node["node_type"] = "cloud"
node["symbol"] = icon
node["console_type"] = None
node["console"] = None
del old_node["properties"]["nios"]
ports = []
keep_ports = []
for old_port in old_node.get("ports", []):
if old_port["name"].startswith("nio_gen_eth"):
port_type = "ethernet"
elif old_port["name"].startswith("nio_gen_linux"):
port_type = "ethernet"
elif old_port["name"].startswith("nio_tap"):
port_type = "tap"
elif old_port["name"].startswith("nio_udp"):
port_type = "udp"
elif old_port["name"].startswith("nio_nat"):
continue
else:
raise aiohttp.web.HTTPConflict(text="The conversion of cloud with {} is not supported".format(old_port["name"]))
if port_type == "udp":
try:
_, lport, rhost, rport = old_port["name"].split(":")
except ValueError:
raise aiohttp.web.HTTPConflict(text="UDP tunnel using IPV6 is not supported in cloud")
port = {
"name": "UDP tunnel {}".format(len(ports) + 1),
"port_number": len(ports) + 1,
"type": port_type,
"lport": int(lport),
"rhost": rhost,
"rport": int(rport)
}
else:
port = {
"interface": old_port["name"].split(":")[1],
"name": old_port["name"].split(":")[1],
"port_number": len(ports) + 1,
"type": port_type
}
keep_ports.append(old_port)
ports.append(port)
node["properties"]["ports_mapping"] = ports
node["properties"]["interfaces"] = []
return keep_ports
def _convert_snapshots(topo_dir):
"""
Convert 1.x snapshot to the new format
"""
old_snapshots_dir = os.path.join(topo_dir, "project-files", "snapshots")
if os.path.exists(old_snapshots_dir):
new_snapshots_dir = os.path.join(topo_dir, "snapshots")
os.makedirs(new_snapshots_dir, exist_ok=True)
for snapshot in os.listdir(old_snapshots_dir):
snapshot_dir = os.path.join(old_snapshots_dir, snapshot)
if os.path.isdir(snapshot_dir):
is_gns3_topo = False
# In .gns3project fileformat the .gns3 should be name project.gns3
for file in os.listdir(snapshot_dir):
if file.endswith(".gns3"):
shutil.move(os.path.join(snapshot_dir, file), os.path.join(snapshot_dir, "project.gns3"))
is_gns3_topo = True
if is_gns3_topo:
snapshot_arc = os.path.join(new_snapshots_dir, snapshot + ".gns3project")
with zipfile.ZipFile(snapshot_arc, 'w', allowZip64=True) as myzip:
for root, dirs, files in os.walk(snapshot_dir):
for file in files:
myzip.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), snapshot_dir), compress_type=zipfile.ZIP_DEFLATED)
shutil.rmtree(old_snapshots_dir)
def _convert_qemu_node(node, old_node):
"""
Convert qemu node from 1.X to 2.0
"""
# In 2.0 the internet VM is replaced by the NAT node
if old_node.get("properties", {}).get("hda_disk_image_md5sum") == "8ebc5a6ec53a1c05b7aa101b5ceefe31":
node["console"] = None
node["console_type"] = None
node["node_type"] = "nat"
del old_node["properties"]
node["properties"] = {
"ports": [
{
"interface": "eth1",
"name": "nat0",
"port_number": 0,
"type": "ethernet"
}
]
}
if node["symbol"] is None:
node["symbol"] = ":/symbols/cloud.svg"
return node
node["node_type"] = "qemu"
if node["symbol"] is None:
node["symbol"] = ":/symbols/qemu_guest.svg"
return node
| gpl-3.0 |
tsdmgz/ansible | lib/ansible/modules/remote_management/oneview/oneview_enclosure_facts.py | 84 | 6416 | #!/usr/bin/python
# Copyright: (c) 2016-2017, Hewlett Packard Enterprise Development LP
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: oneview_enclosure_facts
short_description: Retrieve facts about one or more Enclosures
description:
- Retrieve facts about one or more of the Enclosures from OneView.
version_added: "2.5"
requirements:
- hpOneView >= 2.0.1
author:
- Felipe Bulsoni (@fgbulsoni)
- Thiago Miotto (@tmiotto)
- Adriane Cardozo (@adriane-cardozo)
options:
name:
description:
- Enclosure name.
options:
description:
- "List with options to gather additional facts about an Enclosure and related resources.
Options allowed: C(script), C(environmentalConfiguration), and C(utilization). For the option C(utilization),
you can provide specific parameters."
extends_documentation_fragment:
- oneview
- oneview.factsparams
'''
EXAMPLES = '''
- name: Gather facts about all Enclosures
oneview_enclosure_facts:
hostname: 172.16.101.48
username: administrator
password: my_password
api_version: 500
no_log: true
delegate_to: localhost
- debug: var=enclosures
- name: Gather paginated, filtered and sorted facts about Enclosures
oneview_enclosure_facts:
params:
start: 0
count: 3
sort: name:descending
filter: status=OK
hostname: 172.16.101.48
username: administrator
password: my_password
api_version: 500
no_log: true
delegate_to: localhost
- debug: var=enclosures
- name: Gather facts about an Enclosure by name
oneview_enclosure_facts:
name: Enclosure-Name
hostname: 172.16.101.48
username: administrator
password: my_password
api_version: 500
no_log: true
delegate_to: localhost
- debug: var=enclosures
- name: Gather facts about an Enclosure by name with options
oneview_enclosure_facts:
name: Test-Enclosure
options:
- script # optional
- environmentalConfiguration # optional
- utilization # optional
hostname: 172.16.101.48
username: administrator
password: my_password
api_version: 500
no_log: true
delegate_to: localhost
- debug: var=enclosures
- debug: var=enclosure_script
- debug: var=enclosure_environmental_configuration
- debug: var=enclosure_utilization
- name: "Gather facts about an Enclosure with temperature data at a resolution of one sample per day, between two
specified dates"
oneview_enclosure_facts:
name: Test-Enclosure
options:
- utilization: # optional
fields: AmbientTemperature
filter:
- startDate=2016-07-01T14:29:42.000Z
- endDate=2017-07-01T03:29:42.000Z
view: day
refresh: false
hostname: 172.16.101.48
username: administrator
password: my_password
api_version: 500
no_log: true
delegate_to: localhost
- debug: var=enclosures
- debug: var=enclosure_utilization
'''
RETURN = '''
enclosures:
description: Has all the OneView facts about the Enclosures.
returned: Always, but can be null.
type: dict
enclosure_script:
description: Has all the OneView facts about the script of an Enclosure.
returned: When requested, but can be null.
type: string
enclosure_environmental_configuration:
description: Has all the OneView facts about the environmental configuration of an Enclosure.
returned: When requested, but can be null.
type: dict
enclosure_utilization:
description: Has all the OneView facts about the utilization of an Enclosure.
returned: When requested, but can be null.
type: dict
'''
from ansible.module_utils.oneview import OneViewModuleBase
class EnclosureFactsModule(OneViewModuleBase):
argument_spec = dict(name=dict(type='str'), options=dict(type='list'), params=dict(type='dict'))
def __init__(self):
super(EnclosureFactsModule, self).__init__(additional_arg_spec=self.argument_spec)
def execute_module(self):
ansible_facts = {}
if self.module.params['name']:
enclosures = self._get_by_name(self.module.params['name'])
if self.options and enclosures:
ansible_facts = self._gather_optional_facts(self.options, enclosures[0])
else:
enclosures = self.oneview_client.enclosures.get_all(**self.facts_params)
ansible_facts['enclosures'] = enclosures
return dict(changed=False,
ansible_facts=ansible_facts)
def _gather_optional_facts(self, options, enclosure):
enclosure_client = self.oneview_client.enclosures
ansible_facts = {}
if options.get('script'):
ansible_facts['enclosure_script'] = enclosure_client.get_script(enclosure['uri'])
if options.get('environmentalConfiguration'):
env_config = enclosure_client.get_environmental_configuration(enclosure['uri'])
ansible_facts['enclosure_environmental_configuration'] = env_config
if options.get('utilization'):
ansible_facts['enclosure_utilization'] = self._get_utilization(enclosure, options['utilization'])
return ansible_facts
def _get_utilization(self, enclosure, params):
fields = view = refresh = filter = ''
if isinstance(params, dict):
fields = params.get('fields')
view = params.get('view')
refresh = params.get('refresh')
filter = params.get('filter')
return self.oneview_client.enclosures.get_utilization(enclosure['uri'],
fields=fields,
filter=filter,
refresh=refresh,
view=view)
def _get_by_name(self, name):
return self.oneview_client.enclosures.get_by('name', name)
def main():
EnclosureFactsModule().run()
if __name__ == '__main__':
main()
| gpl-3.0 |
nosun/shadowsocks | shadowsocks/lru_cache.py | 983 | 4290 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 clowwindy
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement
import collections
import logging
import time
# this LRUCache is optimized for concurrency, not QPS
# n: concurrency, keys stored in the cache
# m: visits not timed out, proportional to QPS * timeout
# get & set is O(1), not O(n). thus we can support very large n
# TODO: if timeout or QPS is too large, then this cache is not very efficient,
# as sweep() causes long pause
class LRUCache(collections.MutableMapping):
"""This class is not thread safe"""
def __init__(self, timeout=60, close_callback=None, *args, **kwargs):
self.timeout = timeout
self.close_callback = close_callback
self._store = {}
self._time_to_keys = collections.defaultdict(list)
self._keys_to_last_time = {}
self._last_visits = collections.deque()
self._closed_values = set()
self.update(dict(*args, **kwargs)) # use the free update to set keys
def __getitem__(self, key):
# O(1)
t = time.time()
self._keys_to_last_time[key] = t
self._time_to_keys[t].append(key)
self._last_visits.append(t)
return self._store[key]
def __setitem__(self, key, value):
# O(1)
t = time.time()
self._keys_to_last_time[key] = t
self._store[key] = value
self._time_to_keys[t].append(key)
self._last_visits.append(t)
def __delitem__(self, key):
# O(1)
del self._store[key]
del self._keys_to_last_time[key]
def __iter__(self):
return iter(self._store)
def __len__(self):
return len(self._store)
def sweep(self):
# O(m)
now = time.time()
c = 0
while len(self._last_visits) > 0:
least = self._last_visits[0]
if now - least <= self.timeout:
break
if self.close_callback is not None:
for key in self._time_to_keys[least]:
if key in self._store:
if now - self._keys_to_last_time[key] > self.timeout:
value = self._store[key]
if value not in self._closed_values:
self.close_callback(value)
self._closed_values.add(value)
for key in self._time_to_keys[least]:
self._last_visits.popleft()
if key in self._store:
if now - self._keys_to_last_time[key] > self.timeout:
del self._store[key]
del self._keys_to_last_time[key]
c += 1
del self._time_to_keys[least]
if c:
self._closed_values.clear()
logging.debug('%d keys swept' % c)
def test():
c = LRUCache(timeout=0.3)
c['a'] = 1
assert c['a'] == 1
time.sleep(0.5)
c.sweep()
assert 'a' not in c
c['a'] = 2
c['b'] = 3
time.sleep(0.2)
c.sweep()
assert c['a'] == 2
assert c['b'] == 3
time.sleep(0.2)
c.sweep()
c['b']
time.sleep(0.2)
c.sweep()
assert 'a' not in c
assert c['b'] == 3
time.sleep(0.5)
c.sweep()
assert 'a' not in c
assert 'b' not in c
global close_cb_called
close_cb_called = False
def close_cb(t):
global close_cb_called
assert not close_cb_called
close_cb_called = True
c = LRUCache(timeout=0.1, close_callback=close_cb)
c['s'] = 1
c['s']
time.sleep(0.1)
c['s']
time.sleep(0.3)
c.sweep()
if __name__ == '__main__':
test()
| apache-2.0 |
ThomasTheSpaceFox/T-IMG | T-CODE-RAW.py | 2 | 8148 | #!/usr/bin/env python
# coding=utf-8
#(c) 2015 Thomas Leathers
#T-IMG -Terminal Image System.
#v4.1
#(python version)
#the python version of the T-IMG raw converter MUST have a valid T-IMG image specified as a command line argument!
#ie ./T-IMG.py ./sample.TIMG
# first color chart
#R=red
#B=blue
#G=green
#1=white
#0=black
#C=cyan
#Y=yellow
#P=purple
# second "mixed" color table
#O=orange
#g=grey
#v=blue-violet
#V=red-violet
#p=pink
#c=cyan-green
#b=blue-green
#y=yellow-green
#d=dark-green
#l=light-green
#x=blue-cyan
#Q=light-cyan
#z=dark-cyan
#Z=dark-blue
#X=light-blue
#A=Light-Yellow
#q=dark-yellow
#r=dark-red
#F=brown
#f=tan
#K=light-grey
#k=dark-grey
#E=red-orange
#e=orange-yellow
#s=SUPER-white
#_=blank
#M=SUPER-red
#m=SUPER-blue
#I=SUPER-green
#i=SUPER-orange
#u=SUPER-Cyan
#U=SUPER-purple
#W=SUPER-yellow
#w=SUB-red
#H=SUB-blue
#h=SUB-green
#2=SUB-Cyan
#3=SUB-purple
#4=SUB-yellow
#5=MEDHIGH-red
#6=MEDHIGH-blue
#7=MEDHIGH-green
#8=MEDHIGH-Cyan
#9=MEDHIGH-purple
#S=MEDHIGH-yellow
#n=light-purple
#third translucency color chart
#t=T-Red
#o=T-Blue
#a=T-Green
#j=T-white
#T=T-black
#D=T-Cyan
#J=T-Purple
#N=T-Yellow
#L=Light Black
import fileinput
outraw = open('./output-raw.txt', 'w')
RED=('\033[0;41m')
URED=('\033[0;40m\033[1;31m')
MRED=('\033[0;41m\033[1;37m')
SRED=('\033[0;101m')
TRED=('\033[0;91m')
BLUE=('\033[0;44m')
UBLUE=('\033[0;40m\033[1;34m')
MBLUE=('\033[0;44m\033[1;37m')
SBLUE=('\033[0;104m')
TBLUE=('\033[0;94m')
GREEN=('\033[0;42m')
UGREEN=('\033[0;40m\033[1;32m')
MGREEN=('\033[0;42m\033[1;37m')
SGREEN=('\033[0;102m')
TGREEN=('\033[0;92m')
ORANGE=('\033[0;43m\033[1;31m')
SORANGE=('\033[0;103m\033[1;91m')
GREY=('\033[0;47m\033[1;30m')
LGREY=('\033[0;47m\033[1;30m')
DGREY=('\033[0;40m\033[1;37m')
WH=('\033[0;47m')
TWH=('\033[0;97m')
SWH=('\033[0;107m')
BL=('\033[0;40m')
TBL=('\033[0;30m')
LBL=('\033[0;100m')
DY=('\033[0;40m\033[1;33m')
DR=('\033[0;40m\033[1;31m')
BROWN=('\033[0;41m\033[1;32m')
TAN=('\033[0;45m\033[1;33m')
bv=('\033[0;44m\033[1;35m')
rv=('\033[0;44m\033[1;31m')
DC=('\033[0;40m\033[1;36m')
DB=('\033[0;40m\033[1;34m')
LB=('\033[0;47m\033[1;34m')
LY=('\033[0;47m\033[1;33m')
BC=('\033[0;44m\033[1;36m')
PINK=('\033[0;47m\033[1;31m')
LC=('\033[0;47m\033[1;36m')
YELLOW=('\033[0;43m')
UYELLOW=('\033[0;40m\033[1;33m')
MYELLOW=('\033[0;43m\033[1;37m')
SYELLOW=('\033[0;103m')
TYELLOW=('\033[0;93m')
CYAN=('\033[0;46m')
UCYAN=('\033[0;40m\033[1;36m')
MCYAN=('\033[0;46m\033[1;37m')
SCYAN=('\033[0;106m')
TCYAN=('\033[0;96m')
OR=('\033[0;41m\033[1;33m')
OY=('\033[0;43m\033[1;31m')
CG=('\033[0;46m\033[1;32m')
BG=('\033[0;44m\033[1;32m')
YG=('\033[0;43m\033[1;32m')
DG=('\033[0;40m\033[1;32m')
LG=('\033[0;47m\033[1;32m')
PURPLE=('\033[0;45m')
UPURPLE=('\033[0;40m\033[1;35m')
MPURPLE=('\033[0;45m\033[1;37m')
LPURPLE=('\033[0;47m\033[1;35m')
SPURPLE=('\033[0;105m')
TPURPLE=('\033[0;95m')
RESET='\033[0m'
#print ("loading header data from:" + filetoload)
#n = open(filetoload)
datacnt = 1
for datalst in fileinput.input():
if datacnt==1:
PICTITLE = datalst.replace("\n", "")
#print ("maze title:" + datalst.replace("\n", ""))
if datacnt==2:
CHARMODE = (datalst.replace("\n", ""))
#print ('.MOD.txt file: \n' + "./MAZE/" + datalst.replace("\n", ""))
datacnt += 1
#comment this line if you dont want timg to print the title:
print (PICTITLE)
if CHARMODE==('1'):
DRAW=(" ")
MIX=('▒')
MIX2=('░')
elif CHARMODE==('2'):
DRAW=(" ")
MIX=('▒▒')
MIX2=('░░')
LINENO=1
#n = open(filetoload)
for culine in fileinput.input():
curline = culine.replace("\n", "")
if (LINENO > 2 and curline!=('!')):
#print curline
LINEBLOCK=('')
for CHARCODE in curline:
if CHARCODE==('R'):
LINEBLOCK=(LINEBLOCK + RED + DRAW + RESET)
if CHARCODE==('B'):
LINEBLOCK=(LINEBLOCK + BLUE + DRAW + RESET)
if CHARCODE==('G'):
LINEBLOCK=(LINEBLOCK + GREEN + DRAW + RESET)
if CHARCODE==('1'):
LINEBLOCK=(LINEBLOCK + WH + DRAW + RESET)
if CHARCODE==('0'):
LINEBLOCK=(LINEBLOCK + BL + DRAW + RESET)
if CHARCODE==('Y'):
LINEBLOCK=(LINEBLOCK + YELLOW + DRAW + RESET)
if CHARCODE==('C'):
LINEBLOCK=(LINEBLOCK + CYAN + DRAW + RESET)
if CHARCODE==('P'):
LINEBLOCK=(LINEBLOCK + PURPLE + DRAW + RESET)
if CHARCODE==('O'):
LINEBLOCK=(LINEBLOCK + ORANGE + MIX + RESET)
if CHARCODE==('g'):
LINEBLOCK=(LINEBLOCK + GREY + MIX + RESET)
if CHARCODE==('v'):
LINEBLOCK=(LINEBLOCK + bv + MIX + RESET)
if CHARCODE==('V'):
LINEBLOCK=(LINEBLOCK + rv + MIX + RESET)
if CHARCODE==('p'):
LINEBLOCK=(LINEBLOCK + PINK + MIX + RESET)
if CHARCODE==('c'):
LINEBLOCK=(LINEBLOCK + CG + MIX + RESET)
if CHARCODE==('y'):
LINEBLOCK=(LINEBLOCK + YG + MIX + RESET)
if CHARCODE==('b'):
LINEBLOCK=(LINEBLOCK + BG + MIX + RESET)
if CHARCODE==('d'):
LINEBLOCK=(LINEBLOCK + DG + MIX + RESET)
if CHARCODE==('l'):
LINEBLOCK=(LINEBLOCK + LG + MIX + RESET)
if CHARCODE==('z'):
LINEBLOCK=(LINEBLOCK + DC + MIX + RESET)
if CHARCODE==('x'):
LINEBLOCK=(LINEBLOCK + BC + MIX + RESET)
if CHARCODE==('Z'):
LINEBLOCK=(LINEBLOCK + DB + MIX + RESET)
if CHARCODE==('X'):
LINEBLOCK=(LINEBLOCK + LB + MIX + RESET)
if CHARCODE==('A'):
LINEBLOCK=(LINEBLOCK + LY + MIX + RESET)
if CHARCODE==('Q'):
LINEBLOCK=(LINEBLOCK + LC + MIX + RESET)
if CHARCODE==('q'):
LINEBLOCK=(LINEBLOCK + DY + MIX + RESET)
if CHARCODE==('r'):
LINEBLOCK=(LINEBLOCK + DR + MIX + RESET)
if CHARCODE==('F'):
LINEBLOCK=(LINEBLOCK + BROWN + MIX2 + RESET)
if CHARCODE==('f'):
LINEBLOCK=(LINEBLOCK + TAN + MIX + RESET)
if CHARCODE==('k'):
LINEBLOCK=(LINEBLOCK + DGREY + MIX2 + RESET)
if CHARCODE==('K'):
LINEBLOCK=(LINEBLOCK + LGREY + MIX2 + RESET)
if CHARCODE==('E'):
LINEBLOCK=(LINEBLOCK + OR + MIX2 + RESET)
if CHARCODE==('e'):
LINEBLOCK=(LINEBLOCK + OY + MIX2 + RESET)
if CHARCODE==('s'):
LINEBLOCK=(LINEBLOCK + SWH + DRAW + RESET)
if CHARCODE==('_'):
LINEBLOCK=(LINEBLOCK + RESET + DRAW + RESET)
if CHARCODE==('M'):
LINEBLOCK=(LINEBLOCK + SRED + DRAW + RESET)
if CHARCODE==('m'):
LINEBLOCK=(LINEBLOCK + SBLUE + DRAW + RESET)
if CHARCODE==('I'):
LINEBLOCK=(LINEBLOCK + SGREEN + DRAW + RESET)
if CHARCODE==('i'):
LINEBLOCK=(LINEBLOCK + SORANGE + MIX + RESET)
if CHARCODE==('u'):
LINEBLOCK=(LINEBLOCK + SCYAN + DRAW + RESET)
if CHARCODE==('U'):
LINEBLOCK=(LINEBLOCK + SPURPLE + DRAW + RESET)
if CHARCODE==('W'):
LINEBLOCK=(LINEBLOCK + SYELLOW + DRAW + RESET)
if CHARCODE==('w'):
LINEBLOCK=(LINEBLOCK + URED + MIX2 + RESET)
if CHARCODE==('H'):
LINEBLOCK=(LINEBLOCK + UBLUE + MIX2 + RESET)
if CHARCODE==('h'):
LINEBLOCK=(LINEBLOCK + UGREEN + MIX2 + RESET)
if CHARCODE==('2'):
LINEBLOCK=(LINEBLOCK + UCYAN + MIX2 + RESET)
if CHARCODE==('3'):
LINEBLOCK=(LINEBLOCK + UPURPLE + MIX2 + RESET)
if CHARCODE==('4'):
LINEBLOCK=(LINEBLOCK + UYELLOW + MIX2 + RESET)
if CHARCODE==('5'):
LINEBLOCK=(LINEBLOCK + MRED + MIX2 + RESET)
if CHARCODE==('6'):
LINEBLOCK=(LINEBLOCK + MBLUE + MIX2 + RESET)
if CHARCODE==('7'):
LINEBLOCK=(LINEBLOCK + MGREEN + MIX2 + RESET)
if CHARCODE==('8'):
LINEBLOCK=(LINEBLOCK + MCYAN + MIX2 + RESET)
if CHARCODE==('9'):
LINEBLOCK=(LINEBLOCK + MPURPLE + MIX2 + RESET)
if CHARCODE==('S'):
LINEBLOCK=(LINEBLOCK + MYELLOW + MIX2 + RESET)
if CHARCODE==('n'):
LINEBLOCK=(LINEBLOCK + LPURPLE + MIX + RESET)
if CHARCODE==('t'):
LINEBLOCK=(LINEBLOCK + TRED + MIX + RESET)
if CHARCODE==('o'):
LINEBLOCK=(LINEBLOCK + TBLUE + MIX + RESET)
if CHARCODE==('a'):
LINEBLOCK=(LINEBLOCK + TGREEN + MIX + RESET)
if CHARCODE==('T'):
LINEBLOCK=(LINEBLOCK + TBL + MIX + RESET)
if CHARCODE==('j'):
LINEBLOCK=(LINEBLOCK + TWH + MIX + RESET)
if CHARCODE==('D'):
LINEBLOCK=(LINEBLOCK + TCYAN + MIX + RESET)
if CHARCODE==('J'):
LINEBLOCK=(LINEBLOCK + TPURPLE + MIX + RESET)
if CHARCODE==('N'):
LINEBLOCK=(LINEBLOCK + TYELLOW + MIX + RESET)
if CHARCODE==('L'):
LINEBLOCK=(LINEBLOCK + LBL + DRAW + RESET)
outraw.write(LINEBLOCK + "\n")
LINENO += 1
| lgpl-3.0 |
AunShiLord/sympy | sympy/matrices/immutable.py | 60 | 4889 | from __future__ import print_function, division
from sympy.core import Basic, Integer, Tuple, Dict, S, sympify
from sympy.core.sympify import converter as sympify_converter
from sympy.matrices.matrices import MatrixBase
from sympy.matrices.dense import DenseMatrix
from sympy.matrices.sparse import SparseMatrix, MutableSparseMatrix
from sympy.matrices.expressions import MatrixExpr
def sympify_matrix(arg):
return arg.as_immutable()
sympify_converter[MatrixBase] = sympify_matrix
class ImmutableMatrix(MatrixExpr, DenseMatrix):
"""Create an immutable version of a matrix.
Examples
========
>>> from sympy import eye
>>> from sympy.matrices import ImmutableMatrix
>>> ImmutableMatrix(eye(3))
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> _[0, 0] = 42
Traceback (most recent call last):
...
TypeError: Cannot set values of ImmutableDenseMatrix
"""
_class_priority = 8
@classmethod
def _new(cls, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], ImmutableMatrix):
return args[0]
rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)
rows = Integer(rows)
cols = Integer(cols)
mat = Tuple(*flat_list)
return Basic.__new__(cls, rows, cols, mat)
def __new__(cls, *args, **kwargs):
return cls._new(*args, **kwargs)
@property
def shape(self):
return tuple([int(i) for i in self.args[:2]])
@property
def _mat(self):
return list(self.args[2])
def _entry(self, i, j):
return DenseMatrix.__getitem__(self, (i, j))
__getitem__ = DenseMatrix.__getitem__
def __setitem__(self, *args):
raise TypeError("Cannot set values of ImmutableMatrix")
def _eval_Eq(self, other):
"""Helper method for Equality with matrices.
Relational automatically converts matrices to ImmutableMatrix
instances, so this method only applies here. Returns True if the
matrices are definitively the same, False if they are definitively
different, and None if undetermined (e.g. if they contain Symbols).
Returning None triggers default handling of Equalities.
"""
if not hasattr(other, 'shape') or self.shape != other.shape:
return S.false
if isinstance(other, MatrixExpr) and not isinstance(
other, ImmutableMatrix):
return None
diff = self - other
return sympify(diff.is_zero)
adjoint = MatrixBase.adjoint
conjugate = MatrixBase.conjugate
# C and T are defined in MatrixExpr...I don't know why C alone
# needs to be defined here
C = MatrixBase.C
as_mutable = DenseMatrix.as_mutable
_eval_trace = DenseMatrix._eval_trace
_eval_transpose = DenseMatrix._eval_transpose
_eval_conjugate = DenseMatrix._eval_conjugate
_eval_adjoint = DenseMatrix._eval_adjoint
_eval_inverse = DenseMatrix._eval_inverse
_eval_simplify = DenseMatrix._eval_simplify
equals = DenseMatrix.equals
is_Identity = DenseMatrix.is_Identity
__add__ = MatrixBase.__add__
__radd__ = MatrixBase.__radd__
__mul__ = MatrixBase.__mul__
__rmul__ = MatrixBase.__rmul__
__pow__ = MatrixBase.__pow__
__sub__ = MatrixBase.__sub__
__rsub__ = MatrixBase.__rsub__
__neg__ = MatrixBase.__neg__
__div__ = MatrixBase.__div__
__truediv__ = MatrixBase.__truediv__
# This is included after the class definition as a workaround for issue 7213.
# See https://github.com/sympy/sympy/issues/7213
ImmutableMatrix.is_zero = DenseMatrix.is_zero
class ImmutableSparseMatrix(Basic, SparseMatrix):
"""Create an immutable version of a sparse matrix.
Examples
========
>>> from sympy import eye
>>> from sympy.matrices.immutable import ImmutableSparseMatrix
>>> ImmutableSparseMatrix(1, 1, {})
Matrix([[0]])
>>> ImmutableSparseMatrix(eye(3))
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> _[0, 0] = 42
Traceback (most recent call last):
...
TypeError: Cannot set values of ImmutableSparseMatrix
>>> _.shape
(3, 3)
"""
_class_priority = 9
@classmethod
def _new(cls, *args, **kwargs):
s = MutableSparseMatrix(*args)
rows = Integer(s.rows)
cols = Integer(s.cols)
mat = Dict(s._smat)
obj = Basic.__new__(cls, rows, cols, mat)
obj.rows = s.rows
obj.cols = s.cols
obj._smat = s._smat
return obj
def __new__(cls, *args, **kwargs):
return cls._new(*args, **kwargs)
def __setitem__(self, *args):
raise TypeError("Cannot set values of ImmutableSparseMatrix")
subs = MatrixBase.subs
def __hash__(self):
return hash((type(self).__name__,) + (self.shape, tuple(self._smat)))
_eval_Eq = ImmutableMatrix._eval_Eq
| bsd-3-clause |
endolith/scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_B.py | 21 | 21664 | # -*- coding: utf-8 -*-
from numpy import abs, cos, exp, log, arange, pi, sin, sqrt, sum
from .go_benchmark import Benchmark
class BartelsConn(Benchmark):
r"""
Bartels-Conn objective function.
The BartelsConn [1]_ global optimization problem is a multimodal
minimization problem defined as follows:
.. math::
f_{\text{BartelsConn}}(x) = \lvert {x_1^2 + x_2^2 + x_1x_2} \rvert +
\lvert {\sin(x_1)} \rvert + \lvert {\cos(x_2)} \rvert
with :math:`x_i \in [-500, 500]` for :math:`i = 1, 2`.
*Global optimum*: :math:`f(x) = 1` for :math:`x = [0, 0]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-500.] * self.N, [500.] * self.N))
self.global_optimum = [[0 for _ in range(self.N)]]
self.fglob = 1.0
def fun(self, x, *args):
self.nfev += 1
return (abs(x[0] ** 2.0 + x[1] ** 2.0 + x[0] * x[1]) + abs(sin(x[0]))
+ abs(cos(x[1])))
class Beale(Benchmark):
r"""
Beale objective function.
The Beale [1]_ global optimization problem is a multimodal
minimization problem defined as follows:
.. math::
f_{\text{Beale}}(x) = \left(x_1 x_2 - x_1 + 1.5\right)^{2} +
\left(x_1 x_2^{2} - x_1 + 2.25\right)^{2} + \left(x_1 x_2^{3} - x_1 +
2.625\right)^{2}
with :math:`x_i \in [-4.5, 4.5]` for :math:`i = 1, 2`.
*Global optimum*: :math:`f(x) = 0` for :math:`x=[3, 0.5]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-4.5] * self.N, [4.5] * self.N))
self.global_optimum = [[3.0, 0.5]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
return ((1.5 - x[0] + x[0] * x[1]) ** 2
+ (2.25 - x[0] + x[0] * x[1] ** 2) ** 2
+ (2.625 - x[0] + x[0] * x[1] ** 3) ** 2)
class BiggsExp02(Benchmark):
r"""
BiggsExp02 objective function.
The BiggsExp02 [1]_ global optimization problem is a multimodal minimization
problem defined as follows
.. math::
\begin{matrix}
f_{\text{BiggsExp02}}(x) = \sum_{i=1}^{10} (e^{-t_i x_1}
- 5 e^{-t_i x_2} - y_i)^2 \\
t_i = 0.1 i\\
y_i = e^{-t_i} - 5 e^{-10t_i}\\
\end{matrix}
with :math:`x_i \in [0, 20]` for :math:`i = 1, 2`.
*Global optimum*: :math:`f(x) = 0` for :math:`x = [1, 10]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([0] * 2,
[20] * 2))
self.global_optimum = [[1., 10.]]
self.fglob = 0
def fun(self, x, *args):
self.nfev += 1
t = arange(1, 11.) * 0.1
y = exp(-t) - 5 * exp(-10 * t)
vec = (exp(-t * x[0]) - 5 * exp(-t * x[1]) - y) ** 2
return sum(vec)
class BiggsExp03(Benchmark):
r"""
BiggsExp03 objective function.
The BiggsExp03 [1]_ global optimization problem is a multimodal minimization
problem defined as follows
.. math::
\begin{matrix}\ f_{\text{BiggsExp03}}(x) = \sum_{i=1}^{10}
(e^{-t_i x_1} - x_3e^{-t_i x_2} - y_i)^2\\
t_i = 0.1i\\
y_i = e^{-t_i} - 5e^{-10 t_i}\\
\end{matrix}
with :math:`x_i \in [0, 20]` for :math:`i = 1, 2, 3`.
*Global optimum*: :math:`f(x) = 0` for :math:`x = [1, 10, 5]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=3):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([0] * 3,
[20] * 3))
self.global_optimum = [[1., 10., 5.]]
self.fglob = 0
def fun(self, x, *args):
self.nfev += 1
t = arange(1., 11.) * 0.1
y = exp(-t) - 5 * exp(-10 * t)
vec = (exp(-t * x[0]) - x[2] * exp(-t * x[1]) - y) ** 2
return sum(vec)
class BiggsExp04(Benchmark):
r"""
BiggsExp04 objective function.
The BiggsExp04 [1]_ global optimization problem is a multimodal
minimization problem defined as follows
.. math::
\begin{matrix}\ f_{\text{BiggsExp04}}(x) = \sum_{i=1}^{10}
(x_3 e^{-t_i x_1} - x_4 e^{-t_i x_2} - y_i)^2\\
t_i = 0.1i\\
y_i = e^{-t_i} - 5 e^{-10 t_i}\\
\end{matrix}
with :math:`x_i \in [0, 20]` for :math:`i = 1, ..., 4`.
*Global optimum*: :math:`f(x) = 0` for :math:`x = [1, 10, 1, 5]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=4):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([0.] * 4,
[20.] * 4))
self.global_optimum = [[1., 10., 1., 5.]]
self.fglob = 0
def fun(self, x, *args):
self.nfev += 1
t = arange(1, 11.) * 0.1
y = exp(-t) - 5 * exp(-10 * t)
vec = (x[2] * exp(-t * x[0]) - x[3] * exp(-t * x[1]) - y) ** 2
return sum(vec)
class BiggsExp05(Benchmark):
r"""
BiggsExp05 objective function.
The BiggsExp05 [1]_ global optimization problem is a multimodal minimization
problem defined as follows
.. math::
\begin{matrix}\ f_{\text{BiggsExp05}}(x) = \sum_{i=1}^{11}
(x_3 e^{-t_i x_1} - x_4 e^{-t_i x_2} + 3 e^{-t_i x_5} - y_i)^2\\
t_i = 0.1i\\
y_i = e^{-t_i} - 5e^{-10 t_i} + 3e^{-4 t_i}\\
\end{matrix}
with :math:`x_i \in [0, 20]` for :math:`i=1, ..., 5`.
*Global optimum*: :math:`f(x) = 0` for :math:`x = [1, 10, 1, 5, 4]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=5):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([0.] * 5,
[20.] * 5))
self.global_optimum = [[1., 10., 1., 5., 4.]]
self.fglob = 0
def fun(self, x, *args):
self.nfev += 1
t = arange(1, 12.) * 0.1
y = exp(-t) - 5 * exp(-10 * t) + 3 * exp(-4 * t)
vec = (x[2] * exp(-t * x[0]) - x[3] * exp(-t * x[1])
+ 3 * exp(-t * x[4]) - y) ** 2
return sum(vec)
class Bird(Benchmark):
r"""
Bird objective function.
The Bird global optimization problem is a multimodal minimization
problem defined as follows
.. math::
f_{\text{Bird}}(x) = \left(x_1 - x_2\right)^{2} + e^{\left[1 -
\sin\left(x_1\right) \right]^{2}} \cos\left(x_2\right) + e^{\left[1 -
\cos\left(x_2\right)\right]^{2}} \sin\left(x_1\right)
with :math:`x_i \in [-2\pi, 2\pi]`
*Global optimum*: :math:`f(x) = -106.7645367198034` for :math:`x
= [4.701055751981055, 3.152946019601391]` or :math:`x =
[-1.582142172055011, -3.130246799635430]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-2.0 * pi] * self.N,
[2.0 * pi] * self.N))
self.global_optimum = [[4.701055751981055, 3.152946019601391],
[-1.582142172055011, -3.130246799635430]]
self.fglob = -106.7645367198034
def fun(self, x, *args):
self.nfev += 1
return (sin(x[0]) * exp((1 - cos(x[1])) ** 2)
+ cos(x[1]) * exp((1 - sin(x[0])) ** 2) + (x[0] - x[1]) ** 2)
class Bohachevsky1(Benchmark):
r"""
Bohachevsky 1 objective function.
The Bohachevsky 1 [1]_ global optimization problem is a multimodal
minimization problem defined as follows
.. math::
f_{\text{Bohachevsky}}(x) = \sum_{i=1}^{n-1}\left[x_i^2 + 2 x_{i+1}^2 -
0.3 \cos(3 \pi x_i) - 0.4 \cos(4 \pi x_{i + 1}) + 0.7 \right]
Here, :math:`n` represents the number of dimensions and :math:`x_i \in
[-15, 15]` for :math:`i = 1, ..., n`.
*Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for :math:`i = 1,
..., n`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO: equation needs to be fixed up in the docstring. see Jamil#17
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-100.0] * self.N, [100.0] * self.N))
self.global_optimum = [[0 for _ in range(self.N)]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
return (x[0] ** 2 + 2 * x[1] ** 2 - 0.3 * cos(3 * pi * x[0])
- 0.4 * cos(4 * pi * x[1]) + 0.7)
class Bohachevsky2(Benchmark):
r"""
Bohachevsky 2 objective function.
The Bohachevsky 2 [1]_ global optimization problem is a multimodal
minimization problem defined as follows
.. math::
f_{\text{Bohachevsky}}(x) = \sum_{i=1}^{n-1}\left[x_i^2 + 2 x_{i+1}^2 -
0.3 \cos(3 \pi x_i) - 0.4 \cos(4 \pi x_{i + 1}) + 0.7 \right]
Here, :math:`n` represents the number of dimensions and :math:`x_i \in
[-15, 15]` for :math:`i = 1, ..., n`.
*Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for :math:`i = 1,
..., n`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO: equation needs to be fixed up in the docstring. Jamil is also wrong.
There should be no 0.4 factor in front of the cos term
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-100.0] * self.N, [100.0] * self.N))
self.global_optimum = [[0 for _ in range(self.N)]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
return (x[0] ** 2 + 2 * x[1] ** 2 - 0.3 * cos(3 * pi * x[0])
* cos(4 * pi * x[1]) + 0.3)
class Bohachevsky3(Benchmark):
r"""
Bohachevsky 3 objective function.
The Bohachevsky 3 [1]_ global optimization problem is a multimodal
minimization problem defined as follows
.. math::
f_{\text{Bohachevsky}}(x) = \sum_{i=1}^{n-1}\left[x_i^2 + 2 x_{i+1}^2 -
0.3 \cos(3 \pi x_i) - 0.4 \cos(4 \pi x_{i + 1}) + 0.7 \right]
Here, :math:`n` represents the number of dimensions and :math:`x_i \in
[-15, 15]` for :math:`i = 1, ..., n`.
*Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for :math:`i = 1,
..., n`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO: equation needs to be fixed up in the docstring. Jamil#19
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-100.0] * self.N, [100.0] * self.N))
self.global_optimum = [[0 for _ in range(self.N)]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
return (x[0] ** 2 + 2 * x[1] ** 2
- 0.3 * cos(3 * pi * x[0] + 4 * pi * x[1]) + 0.3)
class BoxBetts(Benchmark):
r"""
BoxBetts objective function.
The BoxBetts global optimization problem is a multimodal
minimization problem defined as follows
.. math::
f_{\text{BoxBetts}}(x) = \sum_{i=1}^k g(x_i)^2
Where, in this exercise:
.. math::
g(x) = e^{-0.1i x_1} - e^{-0.1i x_2} - x_3\left[e^{-0.1i}
- e^{-i}\right]
And :math:`k = 10`.
Here, :math:`x_1 \in [0.9, 1.2], x_2 \in [9, 11.2], x_3 \in [0.9, 1.2]`.
*Global optimum*: :math:`f(x) = 0` for :math:`x = [1, 10, 1]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=3):
Benchmark.__init__(self, dimensions)
self._bounds = ([0.9, 1.2], [9.0, 11.2], [0.9, 1.2])
self.global_optimum = [[1.0, 10.0, 1.0]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
i = arange(1, 11)
g = (exp(-0.1 * i * x[0]) - exp(-0.1 * i * x[1])
- (exp(-0.1 * i) - exp(-i)) * x[2])
return sum(g**2)
class Branin01(Benchmark):
r"""
Branin01 objective function.
The Branin01 global optimization problem is a multimodal minimization
problem defined as follows
.. math::
f_{\text{Branin01}}(x) = \left(- 1.275 \frac{x_1^{2}}{\pi^{2}} + 5
\frac{x_1}{\pi} + x_2 -6\right)^{2} + \left(10 -\frac{5}{4 \pi} \right)
\cos\left(x_1\right) + 10
with :math:`x_1 \in [-5, 10], x_2 \in [0, 15]`
*Global optimum*: :math:`f(x) = 0.39788735772973816` for :math:`x =
[-\pi, 12.275]` or :math:`x = [\pi, 2.275]` or :math:`x = [3\pi, 2.475]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO: Jamil#22, one of the solutions is different
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = [(-5., 10.), (0., 15.)]
self.global_optimum = [[-pi, 12.275], [pi, 2.275], [3 * pi, 2.475]]
self.fglob = 0.39788735772973816
def fun(self, x, *args):
self.nfev += 1
return ((x[1] - (5.1 / (4 * pi ** 2)) * x[0] ** 2
+ 5 * x[0] / pi - 6) ** 2
+ 10 * (1 - 1 / (8 * pi)) * cos(x[0]) + 10)
class Branin02(Benchmark):
r"""
Branin02 objective function.
The Branin02 global optimization problem is a multimodal minimization
problem defined as follows
.. math::
f_{\text{Branin02}}(x) = \left(- 1.275 \frac{x_1^{2}}{\pi^{2}}
+ 5 \frac{x_1}{\pi} + x_2 - 6 \right)^{2} + \left(10 - \frac{5}{4 \pi}
\right) \cos\left(x_1\right) \cos\left(x_2\right)
+ \log(x_1^2+x_2^2 + 1) + 10
with :math:`x_i \in [-5, 15]` for :math:`i = 1, 2`.
*Global optimum*: :math:`f(x) = 5.559037` for :math:`x = [-3.2, 12.53]`
.. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = [(-5.0, 15.0), (-5.0, 15.0)]
self.global_optimum = [[-3.1969884, 12.52625787]]
self.fglob = 5.5589144038938247
def fun(self, x, *args):
self.nfev += 1
return ((x[1] - (5.1 / (4 * pi ** 2)) * x[0] ** 2
+ 5 * x[0] / pi - 6) ** 2
+ 10 * (1 - 1 / (8 * pi)) * cos(x[0]) * cos(x[1])
+ log(x[0] ** 2.0 + x[1] ** 2.0 + 1.0) + 10)
class Brent(Benchmark):
r"""
Brent objective function.
The Brent [1]_ global optimization problem is a multimodal minimization
problem defined as follows:
.. math::
f_{\text{Brent}}(x) = (x_1 + 10)^2 + (x_2 + 10)^2 + e^{(-x_1^2 -x_2^2)}
with :math:`x_i \in [-10, 10]` for :math:`i = 1, 2`.
*Global optimum*: :math:`f(x) = 0` for :math:`x = [-10, -10]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO solution is different to Jamil#24
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N))
self.custom_bounds = ([-10, 2], [-10, 2])
self.global_optimum = [[-10.0, -10.0]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
return ((x[0] + 10.0) ** 2.0 + (x[1] + 10.0) ** 2.0
+ exp(-x[0] ** 2.0 - x[1] ** 2.0))
class Brown(Benchmark):
r"""
Brown objective function.
The Brown [1]_ global optimization problem is a multimodal minimization
problem defined as follows:
.. math::
f_{\text{Brown}}(x) = \sum_{i=1}^{n-1}\left[
\left(x_i^2\right)^{x_{i + 1}^2 + 1}
+ \left(x_{i + 1}^2\right)^{x_i^2 + 1}\right]
with :math:`x_i \in [-1, 4]` for :math:`i=1,...,n`.
*Global optimum*: :math:`f(x_i) = 0` for :math:`x_i = 0` for
:math:`i=1,...,n`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-1.0] * self.N, [4.0] * self.N))
self.custom_bounds = ([-1.0, 1.0], [-1.0, 1.0])
self.global_optimum = [[0 for _ in range(self.N)]]
self.fglob = 0.0
self.change_dimensionality = True
def fun(self, x, *args):
self.nfev += 1
x0 = x[:-1]
x1 = x[1:]
return sum((x0 ** 2.0) ** (x1 ** 2.0 + 1.0)
+ (x1 ** 2.0) ** (x0 ** 2.0 + 1.0))
class Bukin02(Benchmark):
r"""
Bukin02 objective function.
The Bukin02 [1]_ global optimization problem is a multimodal minimization
problem defined as follows:
.. math::
f_{\text{Bukin02}}(x) = 100 (x_2^2 - 0.01x_1^2 + 1)
+ 0.01(x_1 + 10)^2
with :math:`x_1 \in [-15, -5], x_2 \in [-3, 3]`
*Global optimum*: :math:`f(x) = -124.75` for :math:`x = [-15, 0]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO: I think that Gavana and Jamil are wrong on this function. In both
sources the x[1] term is not squared. As such there will be a minimum at
the smallest value of x[1].
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = [(-15.0, -5.0), (-3.0, 3.0)]
self.global_optimum = [[-15.0, 0.0]]
self.fglob = -124.75
def fun(self, x, *args):
self.nfev += 1
return (100 * (x[1] ** 2 - 0.01 * x[0] ** 2 + 1.0)
+ 0.01 * (x[0] + 10.0) ** 2.0)
class Bukin04(Benchmark):
r"""
Bukin04 objective function.
The Bukin04 [1]_ global optimization problem is a multimodal minimization
problem defined as follows:
.. math::
f_{\text{Bukin04}}(x) = 100 x_2^{2} + 0.01 \lvert{x_1 + 10}
\rvert
with :math:`x_1 \in [-15, -5], x_2 \in [-3, 3]`
*Global optimum*: :math:`f(x) = 0` for :math:`x = [-10, 0]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = [(-15.0, -5.0), (-3.0, 3.0)]
self.global_optimum = [[-10.0, 0.0]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
return 100 * x[1] ** 2 + 0.01 * abs(x[0] + 10)
class Bukin06(Benchmark):
r"""
Bukin06 objective function.
The Bukin06 [1]_ global optimization problem is a multimodal minimization
problem defined as follows:
.. math::
f_{\text{Bukin06}}(x) = 100 \sqrt{ \lvert{x_2 - 0.01 x_1^{2}}
\rvert} + 0.01 \lvert{x_1 + 10} \rvert
with :math:`x_1 \in [-15, -5], x_2 \in [-3, 3]`
*Global optimum*: :math:`f(x) = 0` for :math:`x = [-10, 1]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = [(-15.0, -5.0), (-3.0, 3.0)]
self.global_optimum = [[-10.0, 1.0]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
return 100 * sqrt(abs(x[1] - 0.01 * x[0] ** 2)) + 0.01 * abs(x[0] + 10)
| bsd-3-clause |
Emergya/icm-openedx-educamadrid-platform-basic | cms/djangoapps/contentstore/features/problem-editor.py | 22 | 12720 | # disable missing docstring
# pylint: disable=missing-docstring
import json
from lettuce import world, step
from nose.tools import assert_equal, assert_true
from common import type_in_codemirror, open_new_course
from advanced_settings import change_value, ADVANCED_MODULES_KEY
from course_import import import_file
DISPLAY_NAME = "Display Name"
MAXIMUM_ATTEMPTS = "Maximum Attempts"
PROBLEM_WEIGHT = "Problem Weight"
RANDOMIZATION = 'Randomization'
SHOW_ANSWER = "Show Answer"
SHOW_RESET_BUTTON = "Show Reset Button"
TIMER_BETWEEN_ATTEMPTS = "Timer Between Attempts"
MATLAB_API_KEY = "Matlab API key"
@step('I have created a Blank Common Problem$')
def i_created_blank_common_problem(step):
step.given('I am in Studio editing a new unit')
step.given("I have created another Blank Common Problem")
@step('I have created a unit with advanced module "(.*)"$')
def i_created_unit_with_advanced_module(step, advanced_module):
step.given('I am in Studio editing a new unit')
url = world.browser.url
step.given("I select the Advanced Settings")
change_value(step, ADVANCED_MODULES_KEY, '["{}"]'.format(advanced_module))
world.visit(url)
world.wait_for_xmodule()
@step('I have created an advanced component "(.*)" of type "(.*)"')
def i_create_new_advanced_component(step, component_type, advanced_component):
world.create_component_instance(
step=step,
category='advanced',
component_type=component_type,
advanced_component=advanced_component
)
@step('I have created another Blank Common Problem$')
def i_create_new_common_problem(step):
world.create_component_instance(
step=step,
category='problem',
component_type='Blank Common Problem'
)
@step('when I mouseover on "(.*)"')
def i_mouseover_on_html_component(step, element_class):
action_css = '.{}'.format(element_class)
world.trigger_event(action_css, event='mouseover')
@step(u'I can see Reply to Annotation link$')
def i_see_reply_to_annotation_link(_step):
css_selector = 'a.annotatable-reply'
world.wait_for_visible(css_selector)
@step(u'I see that page has scrolled "(.*)" when I click on "(.*)" link$')
def i_see_annotation_problem_page_scrolls(_step, scroll_direction, link_css):
scroll_js = "$(window).scrollTop();"
scroll_height_before = world.browser.evaluate_script(scroll_js)
world.css_click("a.{}".format(link_css))
scroll_height_after = world.browser.evaluate_script(scroll_js)
if scroll_direction == "up":
assert scroll_height_after < scroll_height_before
elif scroll_direction == "down":
assert scroll_height_after > scroll_height_before
@step('I have created an advanced problem of type "(.*)"$')
def i_create_new_advanced_problem(step, component_type):
world.create_component_instance(
step=step,
category='problem',
component_type=component_type,
is_advanced=True
)
@step('I edit and select Settings$')
def i_edit_and_select_settings(_step):
world.edit_component_and_select_settings()
@step('I see the advanced settings and their expected values$')
def i_see_advanced_settings_with_values(step):
world.verify_all_setting_entries(
[
[DISPLAY_NAME, "Blank Common Problem", True],
[MATLAB_API_KEY, "", False],
[MAXIMUM_ATTEMPTS, "", False],
[PROBLEM_WEIGHT, "", False],
[RANDOMIZATION, "Never", False],
[SHOW_ANSWER, "Finished", False],
[SHOW_RESET_BUTTON, "False", False],
[TIMER_BETWEEN_ATTEMPTS, "0", False],
])
@step('I can modify the display name')
def i_can_modify_the_display_name(_step):
# Verifying that the display name can be a string containing a floating point value
# (to confirm that we don't throw an error because it is of the wrong type).
index = world.get_setting_entry_index(DISPLAY_NAME)
world.set_field_value(index, '3.4')
verify_modified_display_name()
@step('my display name change is persisted on save')
def my_display_name_change_is_persisted_on_save(step):
world.save_component_and_reopen(step)
verify_modified_display_name()
@step('the problem display name is "(.*)"$')
def verify_problem_display_name(step, name):
assert_equal(name.upper(), world.browser.find_by_css('.problem-header').text)
@step('I can specify special characters in the display name')
def i_can_modify_the_display_name_with_special_chars(_step):
index = world.get_setting_entry_index(DISPLAY_NAME)
world.set_field_value(index, "updated ' \" &")
verify_modified_display_name_with_special_chars()
@step('I can specify html in the display name and save')
def i_can_modify_the_display_name_with_html(_step):
"""
If alert appear on save then UnexpectedAlertPresentException
will occur and test will fail.
"""
index = world.get_setting_entry_index(DISPLAY_NAME)
world.set_field_value(index, "<script>alert('test')</script>")
verify_modified_display_name_with_html()
world.save_component()
@step('my special characters and persisted on save')
def special_chars_persisted_on_save(step):
world.save_component_and_reopen(step)
verify_modified_display_name_with_special_chars()
@step('I can revert the display name to unset')
def can_revert_display_name_to_unset(_step):
world.revert_setting_entry(DISPLAY_NAME)
verify_unset_display_name()
@step('my display name is unset on save')
def my_display_name_is_persisted_on_save(step):
world.save_component_and_reopen(step)
verify_unset_display_name()
@step('I can select Per Student for Randomization')
def i_can_select_per_student_for_randomization(_step):
world.browser.select(RANDOMIZATION, "Per Student")
verify_modified_randomization()
@step('my change to randomization is persisted')
def my_change_to_randomization_is_persisted(step):
world.save_component_and_reopen(step)
verify_modified_randomization()
@step('I can revert to the default value for randomization')
def i_can_revert_to_default_for_randomization(step):
world.revert_setting_entry(RANDOMIZATION)
world.save_component_and_reopen(step)
world.verify_setting_entry(world.get_setting_entry(RANDOMIZATION), RANDOMIZATION, "Never", False)
@step('I can set the weight to "(.*)"?')
def i_can_set_weight(_step, weight):
set_weight(weight)
verify_modified_weight()
@step('my change to weight is persisted')
def my_change_to_weight_is_persisted(step):
world.save_component_and_reopen(step)
verify_modified_weight()
@step('I can revert to the default value of unset for weight')
def i_can_revert_to_default_for_unset_weight(step):
world.revert_setting_entry(PROBLEM_WEIGHT)
world.save_component_and_reopen(step)
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "", False)
@step('if I set the weight to "(.*)", it remains unset')
def set_the_weight_to_abc(step, bad_weight):
set_weight(bad_weight)
# We show the clear button immediately on type, hence the "True" here.
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "", True)
world.save_component_and_reopen(step)
# But no change was actually ever sent to the model, so on reopen, explicitly_set is False
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "", False)
@step('if I set the max attempts to "(.*)", it will persist as a valid integer$')
def set_the_max_attempts(step, max_attempts_set):
# on firefox with selenium, the behavior is different.
# eg 2.34 displays as 2.34 and is persisted as 2
index = world.get_setting_entry_index(MAXIMUM_ATTEMPTS)
world.set_field_value(index, max_attempts_set)
world.save_component_and_reopen(step)
value = world.css_value('input.setting-input', index=index)
assert value != "", "max attempts is blank"
assert int(value) >= 0
@step('Edit High Level Source is not visible')
def edit_high_level_source_not_visible(step):
verify_high_level_source_links(step, False)
@step('Edit High Level Source is visible')
def edit_high_level_source_links_visible(step):
verify_high_level_source_links(step, True)
@step('If I press Cancel my changes are not persisted')
def cancel_does_not_save_changes(step):
world.cancel_component(step)
step.given("I edit and select Settings")
step.given("I see the advanced settings and their expected values")
@step('I have enabled latex compiler')
def enable_latex_compiler(step):
url = world.browser.url
step.given("I select the Advanced Settings")
change_value(step, 'Enable LaTeX Compiler', 'true')
world.visit(url)
world.wait_for_xmodule()
@step('I have created a LaTeX Problem')
def create_latex_problem(step):
step.given('I am in Studio editing a new unit')
step.given('I have enabled latex compiler')
world.create_component_instance(
step=step,
category='problem',
component_type='Problem Written in LaTeX',
is_advanced=True
)
@step('I edit and compile the High Level Source')
def edit_latex_source(_step):
open_high_level_source()
type_in_codemirror(1, "hi")
world.css_click('.hls-compile')
@step('my change to the High Level Source is persisted')
def high_level_source_persisted(_step):
def verify_text(driver):
css_sel = '.problem div>span'
return world.css_text(css_sel) == 'hi'
world.wait_for(verify_text, timeout=10)
@step('I view the High Level Source I see my changes')
def high_level_source_in_editor(_step):
open_high_level_source()
assert_equal('hi', world.css_value('.source-edit-box'))
@step(u'I have an empty course')
def i_have_empty_course(step):
open_new_course()
@step(u'I import the file "([^"]*)"$')
def i_import_the_file(_step, filename):
import_file(filename)
@step(u'I go to the vertical "([^"]*)"$')
def i_go_to_vertical(_step, vertical):
world.css_click("span:contains('{0}')".format(vertical))
@step(u'I go to the unit "([^"]*)"$')
def i_go_to_unit(_step, unit):
loc = "window.location = $(\"span:contains('{0}')\").closest('a').attr('href')".format(unit)
world.browser.execute_script(loc)
@step(u'I see a message that says "([^"]*)"$')
def i_can_see_message(_step, msg):
msg = json.dumps(msg) # escape quotes
world.css_has_text("h2.title", msg)
@step(u'I can edit the problem$')
def i_can_edit_problem(_step):
world.edit_component()
@step(u'I edit first blank advanced problem for annotation response$')
def i_edit_blank_problem_for_annotation_response(_step):
world.edit_component(1)
text = """
<problem>
<annotationresponse>
<annotationinput><text>Text of annotation</text></annotationinput>
</annotationresponse>
</problem>"""
type_in_codemirror(0, text)
world.save_component()
@step(u'I can see cheatsheet$')
def verify_cheat_sheet_displaying(_step):
world.css_click("a.cheatsheet-toggle")
css_selector = 'article.simple-editor-cheatsheet'
world.wait_for_visible(css_selector)
def verify_high_level_source_links(step, visible):
if visible:
assert_true(world.is_css_present('.launch-latex-compiler'),
msg="Expected to find the latex button but it is not present.")
else:
assert_true(world.is_css_not_present('.launch-latex-compiler'),
msg="Expected not to find the latex button but it is present.")
world.cancel_component(step)
def verify_modified_weight():
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "3.5", True)
def verify_modified_randomization():
world.verify_setting_entry(world.get_setting_entry(RANDOMIZATION), RANDOMIZATION, "Per Student", True)
def verify_modified_display_name():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, '3.4', True)
def verify_modified_display_name_with_special_chars():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, "updated ' \" &", True)
def verify_modified_display_name_with_html():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, "<script>alert('test')</script>", True)
def verify_unset_display_name():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, 'Blank Advanced Problem', False)
def set_weight(weight):
index = world.get_setting_entry_index(PROBLEM_WEIGHT)
world.set_field_value(index, weight)
def open_high_level_source():
world.edit_component()
world.css_click('.launch-latex-compiler > a')
| agpl-3.0 |
alvarolopez/nova | nova/scheduler/caching_scheduler.py | 115 | 3339 | # Copyright (c) 2014 Rackspace Hosting
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.scheduler import filter_scheduler
class CachingScheduler(filter_scheduler.FilterScheduler):
"""Scheduler to test aggressive caching of the host list.
Please note, this is a very opinionated scheduler. Be sure to
review the caveats listed here before selecting this scheduler.
The aim of this scheduler is to reduce server build times when
you have large bursts of server builds, by reducing the time it
takes, from the users point of view, to service each schedule
request.
There are two main parts to scheduling a users request:
* getting the current state of the system
* using filters and weights to pick the best host
This scheduler tries its best to cache in memory the current
state of the system, so we don't need to make the expensive
call to get the current state of the system while processing
a user's request, we can do that query in a periodic task
before the user even issues their request.
To reduce races, cached info of the chosen host is updated using
the existing host state call: consume_from_instance
Please note, the way this works, each scheduler worker has its own
copy of the cache. So if you run multiple schedulers, you will get
more retries, because the data stored on any additional scheduler will
be more out of date, than if it was fetched from the database.
In a similar way, if you have a high number of server deletes, the
extra capacity from those deletes will not show up until the cache is
refreshed.
"""
def __init__(self, *args, **kwargs):
super(CachingScheduler, self).__init__(*args, **kwargs)
self.all_host_states = None
def run_periodic_tasks(self, context):
"""Called from a periodic tasks in the manager."""
elevated = context.elevated()
# NOTE(johngarbutt) Fetching the list of hosts before we get
# a user request, so no user requests have to wait while we
# fetch the list of hosts.
self.all_host_states = self._get_up_hosts(elevated)
def _get_all_host_states(self, context):
"""Called from the filter scheduler, in a template pattern."""
if self.all_host_states is None:
# NOTE(johngarbutt) We only get here when we a scheduler request
# comes in before the first run of the periodic task.
# Rather than raise an error, we fetch the list of hosts.
self.all_host_states = self._get_up_hosts(context)
return self.all_host_states
def _get_up_hosts(self, context):
all_hosts_iterator = self.host_manager.get_all_host_states(context)
return list(all_hosts_iterator)
| apache-2.0 |
leansoft/edx-platform | lms/djangoapps/courseware/testutils.py | 24 | 6991 | """
Common test utilities for courseware functionality
"""
from abc import ABCMeta, abstractmethod
from datetime import datetime
import ddt
from mock import patch
from lms.djangoapps.courseware.url_helpers import get_redirect_url
from student.tests.factories import AdminFactory, UserFactory, CourseEnrollmentFactory
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls
@ddt.ddt
class RenderXBlockTestMixin(object):
"""
Mixin for testing the courseware.render_xblock function.
It can be used for testing any higher-level endpoint that calls this method.
"""
__metaclass__ = ABCMeta
# DOM elements that appear in the LMS Courseware,
# but are excluded from the xBlock-only rendering.
COURSEWARE_CHROME_HTML_ELEMENTS = [
'<header id="open_close_accordion"',
'<ol class="course-tabs"',
'<footer id="footer-openedx"',
'<div class="window-wrap"',
'<div class="preview-menu"',
'<div class="container"'
]
# DOM elements that appear in an xBlock,
# but are excluded from the xBlock-only rendering.
XBLOCK_REMOVED_HTML_ELEMENTS = [
'<div class="wrap-instructor-info"',
]
@abstractmethod
def get_response(self):
"""
Abstract method to get the response from the endpoint that is being tested.
"""
pass # pragma: no cover
def login(self):
"""
Logs in the test user.
"""
self.client.login(username=self.user.username, password='test')
def setup_course(self, default_store=None):
"""
Helper method to create the course.
"""
if not default_store:
default_store = self.store.default_modulestore.get_modulestore_type()
with self.store.default_store(default_store):
self.course = CourseFactory.create() # pylint: disable=attribute-defined-outside-init
chapter = ItemFactory.create(parent=self.course, category='chapter')
self.html_block = ItemFactory.create( # pylint: disable=attribute-defined-outside-init
parent=chapter,
category='html',
data="<p>Test HTML Content<p>"
)
def setup_user(self, admin=False, enroll=False, login=False):
"""
Helper method to create the user.
"""
self.user = AdminFactory() if admin else UserFactory() # pylint: disable=attribute-defined-outside-init
if enroll:
CourseEnrollmentFactory(user=self.user, course_id=self.course.id)
if login:
self.login()
def verify_response(self, expected_response_code=200):
"""
Helper method that calls the endpoint, verifies the expected response code, and returns the response.
"""
response = self.get_response()
if expected_response_code == 200:
self.assertContains(response, self.html_block.data, status_code=expected_response_code)
for chrome_element in [self.COURSEWARE_CHROME_HTML_ELEMENTS + self.XBLOCK_REMOVED_HTML_ELEMENTS]:
self.assertNotContains(response, chrome_element)
else:
self.assertNotContains(response, self.html_block.data, status_code=expected_response_code)
return response
@ddt.data(
(ModuleStoreEnum.Type.mongo, 7),
(ModuleStoreEnum.Type.split, 5),
)
@ddt.unpack
def test_courseware_html(self, default_store, mongo_calls):
"""
To verify that the removal of courseware chrome elements is working,
we include this test here to make sure the chrome elements that should
be removed actually exist in the full courseware page.
If this test fails, it's probably because the HTML template for courseware
has changed and COURSEWARE_CHROME_HTML_ELEMENTS needs to be updated.
"""
with self.store.default_store(default_store):
self.setup_course(default_store)
self.setup_user(admin=True, enroll=True, login=True)
with check_mongo_calls(mongo_calls):
url = get_redirect_url(self.course.id, self.html_block.location)
response = self.client.get(url)
for chrome_element in self.COURSEWARE_CHROME_HTML_ELEMENTS:
self.assertContains(response, chrome_element)
@ddt.data(
(ModuleStoreEnum.Type.mongo, 5),
(ModuleStoreEnum.Type.split, 5),
)
@ddt.unpack
def test_success_enrolled_staff(self, default_store, mongo_calls):
with self.store.default_store(default_store):
self.setup_course(default_store)
self.setup_user(admin=True, enroll=True, login=True)
# The 5 mongoDB calls include calls for
# Old Mongo:
# (1) fill_in_run
# (2) get_course in get_course_with_access
# (3) get_item for HTML block in get_module_by_usage_id
# (4) get_parent when loading HTML block
# (5) edx_notes descriptor call to get_course
# Split:
# (1) course_index - bulk_operation call
# (2) structure - get_course_with_access
# (3) definition - get_course_with_access
# (4) definition - HTML block
# (5) definition - edx_notes decorator (original_get_html)
with check_mongo_calls(mongo_calls):
self.verify_response()
def test_success_unenrolled_staff(self):
self.setup_course()
self.setup_user(admin=True, enroll=False, login=True)
self.verify_response()
def test_success_enrolled_student(self):
self.setup_course()
self.setup_user(admin=False, enroll=True, login=True)
self.verify_response()
def test_unauthenticated(self):
self.setup_course()
self.setup_user(admin=False, enroll=True, login=False)
self.verify_response(expected_response_code=404)
def test_unenrolled_student(self):
self.setup_course()
self.setup_user(admin=False, enroll=False, login=True)
self.verify_response(expected_response_code=404)
@patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False})
def test_fail_block_unreleased(self):
self.setup_course()
self.setup_user(admin=False, enroll=True, login=True)
self.html_block.start = datetime.max
modulestore().update_item(self.html_block, self.user.id)
self.verify_response(expected_response_code=404)
def test_fail_block_nonvisible(self):
self.setup_course()
self.setup_user(admin=False, enroll=True, login=True)
self.html_block.visible_to_staff_only = True
modulestore().update_item(self.html_block, self.user.id)
self.verify_response(expected_response_code=404)
| agpl-3.0 |
maheshakya/scikit-learn | sklearn/cluster/tests/test_hierarchical.py | 3 | 18096 | """
Several basic tests for hierarchical clustering procedures
"""
# Authors: Vincent Michel, 2010, Gael Varoquaux 2012,
# Matteo Visconti di Oleggio Castello 2014
# License: BSD 3 clause
from tempfile import mkdtemp
from functools import partial
import numpy as np
from scipy import sparse
from scipy.cluster import hierarchy
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import ignore_warnings
from sklearn.cluster import Ward, WardAgglomeration, ward_tree
from sklearn.cluster import AgglomerativeClustering, FeatureAgglomeration
from sklearn.cluster.hierarchical import (_hc_cut, _TREE_BUILDERS,
linkage_tree)
from sklearn.feature_extraction.image import grid_to_graph
from sklearn.metrics.pairwise import PAIRED_DISTANCES, cosine_distances,\
manhattan_distances
from sklearn.metrics.cluster import normalized_mutual_info_score
from sklearn.neighbors.graph import kneighbors_graph
from sklearn.cluster._hierarchical import average_merge, max_merge
from sklearn.utils.fast_dict import IntFloatDict
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_warns
def test_linkage_misc():
# Misc tests on linkage
rng = np.random.RandomState(42)
X = rng.normal(size=(5, 5))
assert_raises(ValueError, AgglomerativeClustering(linkage='foo').fit, X)
assert_raises(ValueError, linkage_tree, X, linkage='foo')
assert_raises(ValueError, linkage_tree, X, connectivity=np.ones((4, 4)))
# Smoke test FeatureAgglomeration
FeatureAgglomeration().fit(X)
# Deprecation of Ward class
assert_warns(DeprecationWarning, Ward).fit(X)
# test hiearchical clustering on a precomputed distances matrix
dis = cosine_distances(X)
res = linkage_tree(dis, affinity="precomputed")
assert_array_equal(res[0], linkage_tree(X, affinity="cosine")[0])
# test hiearchical clustering on a precomputed distances matrix
res = linkage_tree(X, affinity=manhattan_distances)
assert_array_equal(res[0], linkage_tree(X, affinity="manhattan")[0])
def test_structured_linkage_tree():
"""
Check that we obtain the correct solution for structured linkage trees.
"""
rng = np.random.RandomState(0)
mask = np.ones([10, 10], dtype=np.bool)
# Avoiding a mask with only 'True' entries
mask[4:7, 4:7] = 0
X = rng.randn(50, 100)
connectivity = grid_to_graph(*mask.shape)
for tree_builder in _TREE_BUILDERS.values():
children, n_components, n_leaves, parent = \
tree_builder(X.T, connectivity)
n_nodes = 2 * X.shape[1] - 1
assert_true(len(children) + n_leaves == n_nodes)
# Check that ward_tree raises a ValueError with a connectivity matrix
# of the wrong shape
assert_raises(ValueError,
tree_builder, X.T, np.ones((4, 4)))
# Check that fitting with no samples raises an error
assert_raises(ValueError,
tree_builder, X.T[:0], connectivity)
def test_unstructured_linkage_tree():
"""
Check that we obtain the correct solution for unstructured linkage trees.
"""
rng = np.random.RandomState(0)
X = rng.randn(50, 100)
for this_X in (X, X[0]):
# With specified a number of clusters just for the sake of
# raising a warning and testing the warning code
with ignore_warnings():
children, n_nodes, n_leaves, parent = assert_warns(
UserWarning, ward_tree, this_X.T, n_clusters=10)
n_nodes = 2 * X.shape[1] - 1
assert_equal(len(children) + n_leaves, n_nodes)
for tree_builder in _TREE_BUILDERS.values():
for this_X in (X, X[0]):
with ignore_warnings():
children, n_nodes, n_leaves, parent = assert_warns(
UserWarning, tree_builder, this_X.T, n_clusters=10)
n_nodes = 2 * X.shape[1] - 1
assert_equal(len(children) + n_leaves, n_nodes)
def test_height_linkage_tree():
"""
Check that the height of the results of linkage tree is sorted.
"""
rng = np.random.RandomState(0)
mask = np.ones([10, 10], dtype=np.bool)
X = rng.randn(50, 100)
connectivity = grid_to_graph(*mask.shape)
for linkage_func in _TREE_BUILDERS.values():
children, n_nodes, n_leaves, parent = linkage_func(X.T, connectivity)
n_nodes = 2 * X.shape[1] - 1
assert_true(len(children) + n_leaves == n_nodes)
def test_agglomerative_clustering():
"""
Check that we obtain the correct number of clusters with
agglomerative clustering.
"""
rng = np.random.RandomState(0)
mask = np.ones([10, 10], dtype=np.bool)
n_samples = 100
X = rng.randn(n_samples, 50)
connectivity = grid_to_graph(*mask.shape)
for linkage in ("ward", "complete", "average"):
clustering = AgglomerativeClustering(n_clusters=10,
connectivity=connectivity,
linkage=linkage)
clustering.fit(X)
# test caching
clustering = AgglomerativeClustering(
n_clusters=10, connectivity=connectivity,
memory=mkdtemp(),
linkage=linkage)
clustering.fit(X)
labels = clustering.labels_
assert_true(np.size(np.unique(labels)) == 10)
# Turn caching off now
clustering = AgglomerativeClustering(
n_clusters=10, connectivity=connectivity, linkage=linkage)
# Check that we obtain the same solution with early-stopping of the
# tree building
clustering.compute_full_tree = False
clustering.fit(X)
assert_almost_equal(normalized_mutual_info_score(clustering.labels_,
labels), 1)
clustering.connectivity = None
clustering.fit(X)
assert_true(np.size(np.unique(clustering.labels_)) == 10)
# Check that we raise a TypeError on dense matrices
clustering = AgglomerativeClustering(
n_clusters=10,
connectivity=sparse.lil_matrix(
connectivity.toarray()[:10, :10]),
linkage=linkage)
assert_raises(ValueError, clustering.fit, X)
# Test that using ward with another metric than euclidean raises an
# exception
clustering = AgglomerativeClustering(
n_clusters=10,
connectivity=connectivity.toarray(),
affinity="manhattan",
linkage="ward")
assert_raises(ValueError, clustering.fit, X)
# Test using another metric than euclidean works with linkage complete
for affinity in PAIRED_DISTANCES.keys():
# Compare our (structured) implementation to scipy
clustering = AgglomerativeClustering(
n_clusters=10,
connectivity=np.ones((n_samples, n_samples)),
affinity=affinity,
linkage="complete")
clustering.fit(X)
clustering2 = AgglomerativeClustering(
n_clusters=10,
connectivity=None,
affinity=affinity,
linkage="complete")
clustering2.fit(X)
assert_almost_equal(normalized_mutual_info_score(clustering2.labels_,
clustering.labels_),
1)
def test_ward_agglomeration():
"""
Check that we obtain the correct solution in a simplistic case
"""
rng = np.random.RandomState(0)
mask = np.ones([10, 10], dtype=np.bool)
X = rng.randn(50, 100)
connectivity = grid_to_graph(*mask.shape)
assert_warns(DeprecationWarning, WardAgglomeration)
with ignore_warnings():
ward = WardAgglomeration(n_clusters=5, connectivity=connectivity)
ward.fit(X)
agglo = FeatureAgglomeration(n_clusters=5, connectivity=connectivity)
agglo.fit(X)
assert_array_equal(agglo.labels_, ward.labels_)
assert_true(np.size(np.unique(agglo.labels_)) == 5)
X_red = agglo.transform(X)
assert_true(X_red.shape[1] == 5)
X_full = agglo.inverse_transform(X_red)
assert_true(np.unique(X_full[0]).size == 5)
assert_array_almost_equal(agglo.transform(X_full), X_red)
# Check that fitting with no samples raises a ValueError
assert_raises(ValueError, agglo.fit, X[:0])
def assess_same_labelling(cut1, cut2):
"""Util for comparison with scipy"""
co_clust = []
for cut in [cut1, cut2]:
n = len(cut)
k = cut.max() + 1
ecut = np.zeros((n, k))
ecut[np.arange(n), cut] = 1
co_clust.append(np.dot(ecut, ecut.T))
assert_true((co_clust[0] == co_clust[1]).all())
def test_scikit_vs_scipy():
"""Test scikit linkage with full connectivity (i.e. unstructured) vs scipy
"""
n, p, k = 10, 5, 3
rng = np.random.RandomState(0)
# Not using a lil_matrix here, just to check that non sparse
# matrices are well handled
connectivity = np.ones((n, n))
for linkage in _TREE_BUILDERS.keys():
for i in range(5):
X = .1 * rng.normal(size=(n, p))
X -= 4. * np.arange(n)[:, np.newaxis]
X -= X.mean(axis=1)[:, np.newaxis]
out = hierarchy.linkage(X, method=linkage)
children_ = out[:, :2].astype(np.int)
children, _, n_leaves, _ = _TREE_BUILDERS[linkage](X, connectivity)
cut = _hc_cut(k, children, n_leaves)
cut_ = _hc_cut(k, children_, n_leaves)
assess_same_labelling(cut, cut_)
# Test error management in _hc_cut
assert_raises(ValueError, _hc_cut, n_leaves + 1, children, n_leaves)
def test_connectivity_propagation():
"""
Check that connectivity in the ward tree is propagated correctly during
merging.
"""
X = np.array([(.014, .120), (.014, .099), (.014, .097),
(.017, .153), (.017, .153), (.018, .153),
(.018, .153), (.018, .153), (.018, .153),
(.018, .153), (.018, .153), (.018, .153),
(.018, .152), (.018, .149), (.018, .144),
])
connectivity = kneighbors_graph(X, 10)
ward = AgglomerativeClustering(
n_clusters=4, connectivity=connectivity, linkage='ward')
# If changes are not propagated correctly, fit crashes with an
# IndexError
ward.fit(X)
def test_ward_tree_children_order():
"""
Check that children are ordered in the same way for both structured and
unstructured versions of ward_tree.
"""
# test on five random datasets
n, p = 10, 5
rng = np.random.RandomState(0)
connectivity = np.ones((n, n))
for i in range(5):
X = .1 * rng.normal(size=(n, p))
X -= 4. * np.arange(n)[:, np.newaxis]
X -= X.mean(axis=1)[:, np.newaxis]
out_unstructured = ward_tree(X)
out_structured = ward_tree(X, connectivity=connectivity)
assert_array_equal(out_unstructured[0], out_structured[0])
def test_ward_linkage_tree_return_distance():
"""Test return_distance option on linkage and ward trees"""
# test that return_distance when set true, gives same
# output on both structured and unstructured clustering.
n, p = 10, 5
rng = np.random.RandomState(0)
connectivity = np.ones((n, n))
for i in range(5):
X = .1 * rng.normal(size=(n, p))
X -= 4. * np.arange(n)[:, np.newaxis]
X -= X.mean(axis=1)[:, np.newaxis]
out_unstructured = ward_tree(X, return_distance=True)
out_structured = ward_tree(X, connectivity=connectivity,
return_distance=True)
# get children
children_unstructured = out_unstructured[0]
children_structured = out_structured[0]
# check if we got the same clusters
assert_array_equal(children_unstructured, children_structured)
# check if the distances are the same
dist_unstructured = out_unstructured[-1]
dist_structured = out_structured[-1]
assert_array_almost_equal(dist_unstructured, dist_structured)
for linkage in ['average', 'complete']:
structured_items = linkage_tree(
X, connectivity=connectivity, linkage=linkage,
return_distance=True)[-1]
unstructured_items = linkage_tree(
X, linkage=linkage, return_distance=True)[-1]
structured_dist = structured_items[-1]
unstructured_dist = unstructured_items[-1]
structured_children = structured_items[0]
unstructured_children = unstructured_items[0]
assert_array_almost_equal(structured_dist, unstructured_dist)
assert_array_almost_equal(
structured_children, unstructured_children)
# test on the following dataset where we know the truth
# taken from scipy/cluster/tests/hierarchy_test_data.py
X = np.array([[1.43054825, -7.5693489],
[6.95887839, 6.82293382],
[2.87137846, -9.68248579],
[7.87974764, -6.05485803],
[8.24018364, -6.09495602],
[7.39020262, 8.54004355]])
# truth
linkage_X_ward = np.array([[3., 4., 0.36265956, 2.],
[1., 5., 1.77045373, 2.],
[0., 2., 2.55760419, 2.],
[6., 8., 9.10208346, 4.],
[7., 9., 24.7784379, 6.]])
linkage_X_complete = np.array(
[[3., 4., 0.36265956, 2.],
[1., 5., 1.77045373, 2.],
[0., 2., 2.55760419, 2.],
[6., 8., 6.96742194, 4.],
[7., 9., 18.77445997, 6.]])
linkage_X_average = np.array(
[[3., 4., 0.36265956, 2.],
[1., 5., 1.77045373, 2.],
[0., 2., 2.55760419, 2.],
[6., 8., 6.55832839, 4.],
[7., 9., 15.44089605, 6.]])
n_samples, n_features = np.shape(X)
connectivity_X = np.ones((n_samples, n_samples))
out_X_unstructured = ward_tree(X, return_distance=True)
out_X_structured = ward_tree(X, connectivity=connectivity_X,
return_distance=True)
# check that the labels are the same
assert_array_equal(linkage_X_ward[:, :2], out_X_unstructured[0])
assert_array_equal(linkage_X_ward[:, :2], out_X_structured[0])
# check that the distances are correct
assert_array_almost_equal(linkage_X_ward[:, 2], out_X_unstructured[4])
assert_array_almost_equal(linkage_X_ward[:, 2], out_X_structured[4])
linkage_options = ['complete', 'average']
X_linkage_truth = [linkage_X_complete, linkage_X_average]
for (linkage, X_truth) in zip(linkage_options, X_linkage_truth):
out_X_unstructured = linkage_tree(
X, return_distance=True, linkage=linkage)
out_X_structured = linkage_tree(
X, connectivity=connectivity_X, linkage=linkage,
return_distance=True)
# check that the labels are the same
assert_array_equal(X_truth[:, :2], out_X_unstructured[0])
assert_array_equal(X_truth[:, :2], out_X_structured[0])
# check that the distances are correct
assert_array_almost_equal(X_truth[:, 2], out_X_unstructured[4])
assert_array_almost_equal(X_truth[:, 2], out_X_structured[4])
def test_connectivity_fixing_non_lil():
"""
Check non regression of a bug if a non item assignable connectivity is
provided with more than one component.
"""
# create dummy data
x = np.array([[0, 0], [1, 1]])
# create a mask with several components to force connectivity fixing
m = np.array([[True, False], [False, True]])
c = grid_to_graph(n_x=2, n_y=2, mask=m)
w = AgglomerativeClustering(connectivity=c, linkage='ward')
assert_warns(UserWarning, w.fit, x)
def test_int_float_dict():
rng = np.random.RandomState(0)
keys = np.unique(rng.randint(100, size=10).astype(np.intp))
values = rng.rand(len(keys))
d = IntFloatDict(keys, values)
for key, value in zip(keys, values):
assert d[key] == value
other_keys = np.arange(50).astype(np.intp)[::2]
other_values = 0.5 * np.ones(50)[::2]
other = IntFloatDict(other_keys, other_values)
# Complete smoke test
max_merge(d, other, mask=np.ones(100, dtype=np.intp), n_a=1, n_b=1)
average_merge(d, other, mask=np.ones(100, dtype=np.intp), n_a=1, n_b=1)
def test_connectivity_callable():
rng = np.random.RandomState(0)
X = rng.rand(20, 5)
connectivity = kneighbors_graph(X, 3)
aglc1 = AgglomerativeClustering(connectivity=connectivity)
aglc2 = AgglomerativeClustering(
connectivity=partial(kneighbors_graph, n_neighbors=3))
aglc1.fit(X)
aglc2.fit(X)
assert_array_equal(aglc1.labels_, aglc2.labels_)
def test_compute_full_tree():
"""Test that the full tree is computed if n_clusters is small"""
rng = np.random.RandomState(0)
X = rng.randn(10, 2)
connectivity = kneighbors_graph(X, 5)
# When n_clusters is less, the full tree should be built
# that is the number of merges should be n_samples - 1
agc = AgglomerativeClustering(n_clusters=2, connectivity=connectivity)
agc.fit(X)
n_samples = X.shape[0]
n_nodes = agc.children_.shape[0]
assert_equal(n_nodes, n_samples - 1)
# When n_clusters is large, greater than max of 100 and 0.02 * n_samples.
# we should stop when there are n_clusters.
n_clusters = 101
X = rng.randn(200, 2)
connectivity = kneighbors_graph(X, 10)
agc = AgglomerativeClustering(n_clusters=n_clusters,
connectivity=connectivity)
agc.fit(X)
n_samples = X.shape[0]
n_nodes = agc.children_.shape[0]
assert_equal(n_nodes, n_samples - n_clusters)
if __name__ == '__main__':
import nose
nose.run(argv=['', __file__])
| bsd-3-clause |
firebitsbr/raspberry_pwn | src/pentest/sqlmap/plugins/dbms/sqlite/__init__.py | 7 | 1039 | #!/usr/bin/env python
"""
Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.enums import DBMS
from lib.core.settings import SQLITE_SYSTEM_DBS
from lib.core.unescaper import unescaper
from plugins.dbms.sqlite.enumeration import Enumeration
from plugins.dbms.sqlite.filesystem import Filesystem
from plugins.dbms.sqlite.fingerprint import Fingerprint
from plugins.dbms.sqlite.syntax import Syntax
from plugins.dbms.sqlite.takeover import Takeover
from plugins.generic.misc import Miscellaneous
class SQLiteMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover):
"""
This class defines SQLite methods
"""
def __init__(self):
self.excludeDbsList = SQLITE_SYSTEM_DBS
Syntax.__init__(self)
Fingerprint.__init__(self)
Enumeration.__init__(self)
Filesystem.__init__(self)
Miscellaneous.__init__(self)
Takeover.__init__(self)
unescaper[DBMS.SQLITE] = Syntax.escape
| gpl-3.0 |
vikatory/kbengine | kbe/res/scripts/common/Lib/test/test_email/torture_test.py | 91 | 3657 | # Copyright (C) 2002-2004 Python Software Foundation
#
# A torture test of the email package. This should not be run as part of the
# standard Python test suite since it requires several meg of email messages
# collected in the wild. These source messages are not checked into the
# Python distro, but are available as part of the standalone email package at
# http://sf.net/projects/mimelib
import sys
import os
import unittest
from io import StringIO
from types import ListType
from email.test.test_email import TestEmailBase
from test.support import TestSkipped, run_unittest
import email
from email import __file__ as testfile
from email.iterators import _structure
def openfile(filename):
from os.path import join, dirname, abspath
path = abspath(join(dirname(testfile), os.pardir, 'moredata', filename))
return open(path, 'r')
# Prevent this test from running in the Python distro
try:
openfile('crispin-torture.txt')
except OSError:
raise TestSkipped
class TortureBase(TestEmailBase):
def _msgobj(self, filename):
fp = openfile(filename)
try:
msg = email.message_from_file(fp)
finally:
fp.close()
return msg
class TestCrispinTorture(TortureBase):
# Mark Crispin's torture test from the SquirrelMail project
def test_mondo_message(self):
eq = self.assertEqual
neq = self.ndiffAssertEqual
msg = self._msgobj('crispin-torture.txt')
payload = msg.get_payload()
eq(type(payload), ListType)
eq(len(payload), 12)
eq(msg.preamble, None)
eq(msg.epilogue, '\n')
# Probably the best way to verify the message is parsed correctly is to
# dump its structure and compare it against the known structure.
fp = StringIO()
_structure(msg, fp=fp)
neq(fp.getvalue(), """\
multipart/mixed
text/plain
message/rfc822
multipart/alternative
text/plain
multipart/mixed
text/richtext
application/andrew-inset
message/rfc822
audio/basic
audio/basic
image/pbm
message/rfc822
multipart/mixed
multipart/mixed
text/plain
audio/x-sun
multipart/mixed
image/gif
image/gif
application/x-be2
application/atomicmail
audio/x-sun
message/rfc822
multipart/mixed
text/plain
image/pgm
text/plain
message/rfc822
multipart/mixed
text/plain
image/pbm
message/rfc822
application/postscript
image/gif
message/rfc822
multipart/mixed
audio/basic
audio/basic
message/rfc822
multipart/mixed
application/postscript
text/plain
message/rfc822
multipart/mixed
text/plain
multipart/parallel
image/gif
audio/basic
application/atomicmail
message/rfc822
audio/x-sun
""")
def _testclasses():
mod = sys.modules[__name__]
return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
def suite():
suite = unittest.TestSuite()
for testclass in _testclasses():
suite.addTest(unittest.makeSuite(testclass))
return suite
def test_main():
for testclass in _testclasses():
run_unittest(testclass)
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| lgpl-3.0 |
jicruz/heroku-bot | lib/youtube_dl/extractor/ooyala.py | 21 | 8726 | from __future__ import unicode_literals
import re
import base64
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
determine_ext,
ExtractorError,
float_or_none,
int_or_none,
try_get,
unsmuggle_url,
)
from ..compat import compat_urllib_parse_urlencode
class OoyalaBaseIE(InfoExtractor):
_PLAYER_BASE = 'http://player.ooyala.com/'
_CONTENT_TREE_BASE = _PLAYER_BASE + 'player_api/v1/content_tree/'
_AUTHORIZATION_URL_TEMPLATE = _PLAYER_BASE + 'sas/player_api/v2/authorization/embed_code/%s/%s?'
def _extract(self, content_tree_url, video_id, domain='example.org', supportedformats=None, embed_token=None):
content_tree = self._download_json(content_tree_url, video_id)['content_tree']
metadata = content_tree[list(content_tree)[0]]
embed_code = metadata['embed_code']
pcode = metadata.get('asset_pcode') or embed_code
title = metadata['title']
auth_data = self._download_json(
self._AUTHORIZATION_URL_TEMPLATE % (pcode, embed_code) +
compat_urllib_parse_urlencode({
'domain': domain,
'supportedFormats': supportedformats or 'mp4,rtmp,m3u8,hds,dash,smooth',
'embedToken': embed_token,
}), video_id)
cur_auth_data = auth_data['authorization_data'][embed_code]
urls = []
formats = []
if cur_auth_data['authorized']:
for stream in cur_auth_data['streams']:
url_data = try_get(stream, lambda x: x['url']['data'], compat_str)
if not url_data:
continue
s_url = base64.b64decode(url_data.encode('ascii')).decode('utf-8')
if not s_url or s_url in urls:
continue
urls.append(s_url)
ext = determine_ext(s_url, None)
delivery_type = stream.get('delivery_type')
if delivery_type == 'hls' or ext == 'm3u8':
formats.extend(self._extract_m3u8_formats(
re.sub(r'/ip(?:ad|hone)/', '/all/', s_url), embed_code, 'mp4', 'm3u8_native',
m3u8_id='hls', fatal=False))
elif delivery_type == 'hds' or ext == 'f4m':
formats.extend(self._extract_f4m_formats(
s_url + '?hdcore=3.7.0', embed_code, f4m_id='hds', fatal=False))
elif delivery_type == 'dash' or ext == 'mpd':
formats.extend(self._extract_mpd_formats(
s_url, embed_code, mpd_id='dash', fatal=False))
elif delivery_type == 'smooth':
self._extract_ism_formats(
s_url, embed_code, ism_id='mss', fatal=False)
elif ext == 'smil':
formats.extend(self._extract_smil_formats(
s_url, embed_code, fatal=False))
else:
formats.append({
'url': s_url,
'ext': ext or delivery_type,
'vcodec': stream.get('video_codec'),
'format_id': delivery_type,
'width': int_or_none(stream.get('width')),
'height': int_or_none(stream.get('height')),
'abr': int_or_none(stream.get('audio_bitrate')),
'vbr': int_or_none(stream.get('video_bitrate')),
'fps': float_or_none(stream.get('framerate')),
})
else:
raise ExtractorError('%s said: %s' % (
self.IE_NAME, cur_auth_data['message']), expected=True)
self._sort_formats(formats)
subtitles = {}
for lang, sub in metadata.get('closed_captions_vtt', {}).get('captions', {}).items():
sub_url = sub.get('url')
if not sub_url:
continue
subtitles[lang] = [{
'url': sub_url,
}]
return {
'id': embed_code,
'title': title,
'description': metadata.get('description'),
'thumbnail': metadata.get('thumbnail_image') or metadata.get('promo_image'),
'duration': float_or_none(metadata.get('duration'), 1000),
'subtitles': subtitles,
'formats': formats,
}
class OoyalaIE(OoyalaBaseIE):
_VALID_URL = r'(?:ooyala:|https?://.+?\.ooyala\.com/.*?(?:embedCode|ec)=)(?P<id>.+?)(&|$)'
_TESTS = [
{
# From http://it.slashdot.org/story/13/04/25/178216/recovering-data-from-broken-hard-drives-and-ssds-video
'url': 'http://player.ooyala.com/player.js?embedCode=pxczE2YjpfHfn1f3M-ykG_AmJRRn0PD8',
'info_dict': {
'id': 'pxczE2YjpfHfn1f3M-ykG_AmJRRn0PD8',
'ext': 'mp4',
'title': 'Explaining Data Recovery from Hard Drives and SSDs',
'description': 'How badly damaged does a drive have to be to defeat Russell and his crew? Apparently, smashed to bits.',
'duration': 853.386,
},
# The video in the original webpage now uses PlayWire
'skip': 'Ooyala said: movie expired',
}, {
# Only available for ipad
'url': 'http://player.ooyala.com/player.js?embedCode=x1b3lqZDq9y_7kMyC2Op5qo-p077tXD0',
'info_dict': {
'id': 'x1b3lqZDq9y_7kMyC2Op5qo-p077tXD0',
'ext': 'mp4',
'title': 'Simulation Overview - Levels of Simulation',
'duration': 194.948,
},
},
{
# Information available only through SAS api
# From http://community.plm.automation.siemens.com/t5/News-NX-Manufacturing/Tool-Path-Divide/ba-p/4187
'url': 'http://player.ooyala.com/player.js?embedCode=FiOG81ZTrvckcchQxmalf4aQj590qTEx',
'md5': 'a84001441b35ea492bc03736e59e7935',
'info_dict': {
'id': 'FiOG81ZTrvckcchQxmalf4aQj590qTEx',
'ext': 'mp4',
'title': 'Divide Tool Path.mp4',
'duration': 204.405,
}
},
{
# empty stream['url']['data']
'url': 'http://player.ooyala.com/player.js?embedCode=w2bnZtYjE6axZ_dw1Cd0hQtXd_ige2Is',
'only_matching': True,
}
]
@staticmethod
def _url_for_embed_code(embed_code):
return 'http://player.ooyala.com/player.js?embedCode=%s' % embed_code
@classmethod
def _build_url_result(cls, embed_code):
return cls.url_result(cls._url_for_embed_code(embed_code),
ie=cls.ie_key())
def _real_extract(self, url):
url, smuggled_data = unsmuggle_url(url, {})
embed_code = self._match_id(url)
domain = smuggled_data.get('domain')
supportedformats = smuggled_data.get('supportedformats')
embed_token = smuggled_data.get('embed_token')
content_tree_url = self._CONTENT_TREE_BASE + 'embed_code/%s/%s' % (embed_code, embed_code)
return self._extract(content_tree_url, embed_code, domain, supportedformats, embed_token)
class OoyalaExternalIE(OoyalaBaseIE):
_VALID_URL = r'''(?x)
(?:
ooyalaexternal:|
https?://.+?\.ooyala\.com/.*?\bexternalId=
)
(?P<partner_id>[^:]+)
:
(?P<id>.+)
(?:
:|
.*?&pcode=
)
(?P<pcode>.+?)
(?:&|$)
'''
_TEST = {
'url': 'https://player.ooyala.com/player.js?externalId=espn:10365079&pcode=1kNG061cgaoolOncv54OAO1ceO-I&adSetCode=91cDU6NuXTGKz3OdjOxFdAgJVtQcKJnI&callback=handleEvents&hasModuleParams=1&height=968&playerBrandingId=7af3bd04449c444c964f347f11873075&targetReplaceId=videoPlayer&width=1656&wmode=opaque&allowScriptAccess=always',
'info_dict': {
'id': 'FkYWtmazr6Ed8xmvILvKLWjd4QvYZpzG',
'ext': 'mp4',
'title': 'dm_140128_30for30Shorts___JudgingJewellv2',
'duration': 1302.0,
},
'params': {
# m3u8 download
'skip_download': True,
},
}
def _real_extract(self, url):
partner_id, video_id, pcode = re.match(self._VALID_URL, url).groups()
content_tree_url = self._CONTENT_TREE_BASE + 'external_id/%s/%s:%s' % (pcode, partner_id, video_id)
return self._extract(content_tree_url, video_id)
| gpl-3.0 |
Gadal/sympy | sympy/strategies/branch/tests/test_traverse.py | 59 | 1158 | from sympy import Basic
from sympy.strategies.branch.traverse import top_down, sall
from sympy.strategies.branch.core import do_one, identity
def inc(x):
if isinstance(x, int):
yield x + 1
def test_top_down_easy():
expr = Basic(1, 2)
expected = Basic(2, 3)
brl = top_down(inc)
assert set(brl(expr)) == set([expected])
def test_top_down_big_tree():
expr = Basic(1, Basic(2), Basic(3, Basic(4), 5))
expected = Basic(2, Basic(3), Basic(4, Basic(5), 6))
brl = top_down(inc)
assert set(brl(expr)) == set([expected])
def test_top_down_harder_function():
def split5(x):
if x == 5:
yield x - 1
yield x + 1
expr = Basic(Basic(5, 6), 1)
expected = set([Basic(Basic(4, 6), 1), Basic(Basic(6, 6), 1)])
brl = top_down(split5)
assert set(brl(expr)) == expected
def test_sall():
expr = Basic(1, 2)
expected = Basic(2, 3)
brl = sall(inc)
assert list(brl(expr)) == [expected]
expr = Basic(1, 2, Basic(3, 4))
expected = Basic(2, 3, Basic(3, 4))
brl = sall(do_one(inc, identity))
assert list(brl(expr)) == [expected]
| bsd-3-clause |
pandeyop/tempest | tempest/api/identity/admin/v2/test_tenants.py | 11 | 6989 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from six import moves
from tempest_lib.common.utils import data_utils
from tempest.api.identity import base
from tempest import test
class TenantsTestJSON(base.BaseIdentityV2AdminTest):
@test.idempotent_id('16c6e05c-6112-4b0e-b83f-5e43f221b6b0')
def test_tenant_list_delete(self):
# Create several tenants and delete them
tenants = []
for _ in moves.xrange(3):
tenant_name = data_utils.rand_name(name='tenant-new')
tenant = self.client.create_tenant(tenant_name)
self.data.tenants.append(tenant)
tenants.append(tenant)
tenant_ids = map(lambda x: x['id'], tenants)
body = self.client.list_tenants()
found = [t for t in body if t['id'] in tenant_ids]
self.assertEqual(len(found), len(tenants), 'Tenants not created')
for tenant in tenants:
self.client.delete_tenant(tenant['id'])
self.data.tenants.remove(tenant)
body = self.client.list_tenants()
found = [tenant for tenant in body if tenant['id'] in tenant_ids]
self.assertFalse(any(found), 'Tenants failed to delete')
@test.idempotent_id('d25e9f24-1310-4d29-b61b-d91299c21d6d')
def test_tenant_create_with_description(self):
# Create tenant with a description
tenant_name = data_utils.rand_name(name='tenant')
tenant_desc = data_utils.rand_name(name='desc')
body = self.client.create_tenant(tenant_name,
description=tenant_desc)
tenant = body
self.data.tenants.append(tenant)
tenant_id = body['id']
desc1 = body['description']
self.assertEqual(desc1, tenant_desc, 'Description should have '
'been sent in response for create')
body = self.client.get_tenant(tenant_id)
desc2 = body['description']
self.assertEqual(desc2, tenant_desc, 'Description does not appear'
'to be set')
self.client.delete_tenant(tenant_id)
self.data.tenants.remove(tenant)
@test.idempotent_id('670bdddc-1cd7-41c7-b8e2-751cfb67df50')
def test_tenant_create_enabled(self):
# Create a tenant that is enabled
tenant_name = data_utils.rand_name(name='tenant')
body = self.client.create_tenant(tenant_name, enabled=True)
tenant = body
self.data.tenants.append(tenant)
tenant_id = body['id']
en1 = body['enabled']
self.assertTrue(en1, 'Enable should be True in response')
body = self.client.get_tenant(tenant_id)
en2 = body['enabled']
self.assertTrue(en2, 'Enable should be True in lookup')
self.client.delete_tenant(tenant_id)
self.data.tenants.remove(tenant)
@test.idempotent_id('3be22093-b30f-499d-b772-38340e5e16fb')
def test_tenant_create_not_enabled(self):
# Create a tenant that is not enabled
tenant_name = data_utils.rand_name(name='tenant')
body = self.client.create_tenant(tenant_name, enabled=False)
tenant = body
self.data.tenants.append(tenant)
tenant_id = body['id']
en1 = body['enabled']
self.assertEqual('false', str(en1).lower(),
'Enable should be False in response')
body = self.client.get_tenant(tenant_id)
en2 = body['enabled']
self.assertEqual('false', str(en2).lower(),
'Enable should be False in lookup')
self.client.delete_tenant(tenant_id)
self.data.tenants.remove(tenant)
@test.idempotent_id('781f2266-d128-47f3-8bdb-f70970add238')
def test_tenant_update_name(self):
# Update name attribute of a tenant
t_name1 = data_utils.rand_name(name='tenant')
body = self.client.create_tenant(t_name1)
tenant = body
self.data.tenants.append(tenant)
t_id = body['id']
resp1_name = body['name']
t_name2 = data_utils.rand_name(name='tenant2')
body = self.client.update_tenant(t_id, name=t_name2)
resp2_name = body['name']
self.assertNotEqual(resp1_name, resp2_name)
body = self.client.get_tenant(t_id)
resp3_name = body['name']
self.assertNotEqual(resp1_name, resp3_name)
self.assertEqual(t_name1, resp1_name)
self.assertEqual(resp2_name, resp3_name)
self.client.delete_tenant(t_id)
self.data.tenants.remove(tenant)
@test.idempotent_id('859fcfe1-3a03-41ef-86f9-b19a47d1cd87')
def test_tenant_update_desc(self):
# Update description attribute of a tenant
t_name = data_utils.rand_name(name='tenant')
t_desc = data_utils.rand_name(name='desc')
body = self.client.create_tenant(t_name, description=t_desc)
tenant = body
self.data.tenants.append(tenant)
t_id = body['id']
resp1_desc = body['description']
t_desc2 = data_utils.rand_name(name='desc2')
body = self.client.update_tenant(t_id, description=t_desc2)
resp2_desc = body['description']
self.assertNotEqual(resp1_desc, resp2_desc)
body = self.client.get_tenant(t_id)
resp3_desc = body['description']
self.assertNotEqual(resp1_desc, resp3_desc)
self.assertEqual(t_desc, resp1_desc)
self.assertEqual(resp2_desc, resp3_desc)
self.client.delete_tenant(t_id)
self.data.tenants.remove(tenant)
@test.idempotent_id('8fc8981f-f12d-4c66-9972-2bdcf2bc2e1a')
def test_tenant_update_enable(self):
# Update the enabled attribute of a tenant
t_name = data_utils.rand_name(name='tenant')
t_en = False
body = self.client.create_tenant(t_name, enabled=t_en)
tenant = body
self.data.tenants.append(tenant)
t_id = body['id']
resp1_en = body['enabled']
t_en2 = True
body = self.client.update_tenant(t_id, enabled=t_en2)
resp2_en = body['enabled']
self.assertNotEqual(resp1_en, resp2_en)
body = self.client.get_tenant(t_id)
resp3_en = body['enabled']
self.assertNotEqual(resp1_en, resp3_en)
self.assertEqual('false', str(resp1_en).lower())
self.assertEqual(resp2_en, resp3_en)
self.client.delete_tenant(t_id)
self.data.tenants.remove(tenant)
| apache-2.0 |
ghowland/schemaman | schemaman/schemaman.py | 2 | 2779 | #!/usr/bin/env python
"""
SchemaMan - Schema Manager. Cross database schema revision control, data migration and data access.
- Manage changes in the schema versions, allowing publication of schemas with your code that is not bound to a single database
software package or platform.
- Use as a cross-database method of interacting with data (insert/update/delete/get/filter).
- Migrate data between different databases (same or different database software), using rules to update schema, data, or a
combination.
- Version Management of all data put into the system (unless skipped)
- Change Management of Version Management commits (done through a series of Action scripts, so highly configurable)
Intended for use on smaller data sets, such as those found in System and Network Operational Configuration Management systems.
Copyright Geoff Howland, 2014. MIT License.
"""
import sys
import os
import getopt
import pprint
# SchemaMan modules
import utility
from utility.log import Log
from utility.error import *
from utility.path import *
import action
def Main(args=None):
if not args:
args = []
long_options = ['dir=', 'verbose', 'help', 'yes']
try:
(options, args) = getopt.getopt(args, '?hvyd:', long_options)
except getopt.GetoptError, e:
Usage(e)
# Dictionary of command options, with defaults
command_options = {}
command_options['verbose'] = False
command_options['always_yes'] = False
# Process out CLI options
for (option, value) in options:
# Help
if option in ('-h', '-?', '--help'):
Usage()
# Verbose output information
elif option in ('-v', '--verbose'):
command_options['verbose'] = True
# Always answer Yes to prompts
elif option in ('-y', '--yes'):
command_options['always_yes'] = True
# Invalid option
else:
Usage('Unknown option: %s' % option)
# Store the command options for our logging
utility.log.RUN_OPTIONS = command_options
# Ensure we at least have one spec file
if len(args) < 1:
Usage('No action specified')
#try:
if 1:
action.process.ProcessAction(args[0], args[1:], command_options)
#NOTE(g): Catch all exceptions, and return in properly formatted output
#TODO(g): Implement stack trace in Exception handling so we dont lose where this
# exception came from, and can then wrap all runs and still get useful
# debugging information
#except Exception, e:
else:
Error({'exception':str(e)}, command_options)
if __name__ == '__main__':
#NOTE(g): Fixing the path here. If you're calling this as a module, you have to
# fix the utility/handlers module import problem yourself.
sys.path.append(os.path.dirname(sys.argv[0]))
Main(sys.argv[1:])
| mit |
qtux/instmatcher | tests/test_core.py | 1 | 5464 | # Copyright 2016 Matthias Gazzari
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from instmatcher import core
import itertools
class test_core(unittest.TestCase):
def test_None_combinations(self):
combinations = [
['Fantasia', None],
['AQ', None],
[30, None],
[40, None],
[1, None],
]
expected = []
for arg in itertools.product(*combinations):
actual = list(core.query(*arg))
self.assertSequenceEqual(actual, expected)
def test_misspelled(self):
actual = core.query('Whasington', None, None, None, 1)
expectedNames = []
actualNames = [item[0]['name'] for item in actual]
self.assertSequenceEqual(actualNames, expectedNames)
def test_zero_search_radius(self):
actual = core.query('Pisa University', None, 0, 0, 0)
expectedNames = [
"University of Pisa",
"Pisa University System",
]
actualNames = [item[0]['name'] for item in actual]
self.assertSequenceEqual(actualNames, expectedNames)
def test_bad_coord_param(self):
actual = core.query('Pisa University', None, None, float('inf'), 1)
expectedNames = [
"University of Pisa",
"Pisa University System",
]
actualNames = [item[0]['name'] for item in actual]
self.assertSequenceEqual(actualNames, expectedNames)
def test_illegal_coord_param(self):
actual = core.query('Pisa University', None, '120', {'lon':0}, 1)
expectedNames = [
"University of Pisa",
"Pisa University System",
]
actualNames = [item[0]['name'] for item in actual]
self.assertSequenceEqual(actualNames, expectedNames)
def test_impossible_coord_param(self):
actual = core.query('Pisa University', None, 1000, 2000, 1)
expectedNames = [
"University of Pisa",
"Pisa University System",
]
actualNames = [item[0]['name'] for item in actual]
self.assertSequenceEqual(actualNames, expectedNames)
def test_TU_Berlin(self):
actual = core.query('TU Berlin', None, None, None, 1)
expectedNames = ["Technical University of Berlin",]
actualNames = [item[0]['name'] for item in actual]
self.assertSequenceEqual(actualNames, expectedNames)
def test_TU_Berlin_full(self):
actual = core.query('TU Berlin', None, None, None, 1)
expectedNames = ["Technical University of Berlin",]
actualNames = [item[0]['name'] for item in actual]
self.assertSequenceEqual(actualNames, expectedNames)
def test_TU_Berlin(self):
actual = core.query('TU Berlin', None, None, None, 1)
expected = [{
'alpha2': 'DE',
'country': 'Germany',
'isni': '0000 0001 2195 9817',
'lat': 52.511944444444,
'lon': 13.326388888889,
'name': 'Technical University of Berlin',
'source': 'http://www.wikidata.org/entity/Q51985',
'type': 'university',
},]
actualResults = [item[0] for item in actual]
self.assertSequenceEqual(actualResults, expected)
def test_London_CA(self):
actual = core.query('London', 'CA', None, None, 1)
expectedNames = [
"London Health Sciences Centre",
"University of Western Ontario",
]
actualNames = [item[0]['name'] for item in actual]
self.assertSequenceEqual(actualNames, expectedNames)
def test_abbreviation_expansion_considering_word_boundaries(self):
actual = core.expandAbbreviations('univ Univ univuniv univx xuniv UNIV')
expected = 'univ* univ* univuniv univx xuniv univ*'
self.assertEqual(actual, expected)
def test_some_abbreviations(self):
actual = core.expandAbbreviations('chem ACAD of sCI, INST of EngN.')
expected = 'chem* acad* of sci*, inst* of engineering.'
self.assertEqual(actual, expected)
def test_abbreviations_no_hits(self):
actual = core.expandAbbreviations('UNIV_univ chemacad')
expected = 'UNIV_univ chemacad'
self.assertEqual(actual, expected)
def test_find_TU_Berlin(self):
arg = 'TU Berlin'
expected = [
{
'name': 'Technical University of Berlin',
'alpha2': 'DE',
'country': 'Germany',
'lat': 52.511944444444,
'lon': 13.326388888889,
'isni': '0000 0001 2195 9817',
'source': 'http://www.wikidata.org/entity/Q51985',
'type': 'university',
}
]
first = expected[0]
self.assertSequenceEqual(list(core.findAll(arg)), expected)
self.assertEqual(core.find(arg), first)
def test_find_Univ_Louvain(self):
arg = 'Univ Louvain'
expected = [
{
# french part of the former Catholic University of Leuven
'name': 'Université catholique de Louvain',
'alpha2': 'BE',
'country': 'Belgium',
'lat': 50.669611111111,
'lon': 4.6122638888889,
'isni': '0000 0001 2294 713X',
'source': 'http://www.wikidata.org/entity/Q378134',
'type': 'university',
},
]
first = expected[0]
self.assertSequenceEqual(list(core.findAll(arg)), expected)
self.assertEqual(core.find(arg), first)
def test_institution_uniqeness(self):
return
visited = set()
for item in core.findAll('*'):
source = item['source']
if source in visited:
self.fail('The source column is not unique!')
return
else:
visited.add(source)
| apache-2.0 |
tpo/ansible | lib/ansible/playbook/handler.py | 71 | 2112 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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 Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.playbook.attribute import FieldAttribute
from ansible.playbook.task import Task
from ansible.module_utils.six import string_types
class Handler(Task):
_listen = FieldAttribute(isa='list', default=list, listof=string_types, static=True)
def __init__(self, block=None, role=None, task_include=None):
self.notified_hosts = []
self.cached_name = False
super(Handler, self).__init__(block=block, role=role, task_include=task_include)
def __repr__(self):
''' returns a human readable representation of the handler '''
return "HANDLER: %s" % self.get_name()
@staticmethod
def load(data, block=None, role=None, task_include=None, variable_manager=None, loader=None):
t = Handler(block=block, role=role, task_include=task_include)
return t.load_data(data, variable_manager=variable_manager, loader=loader)
def notify_host(self, host):
if not self.is_host_notified(host):
self.notified_hosts.append(host)
return True
return False
def is_host_notified(self, host):
return host in self.notified_hosts
def serialize(self):
result = super(Handler, self).serialize()
result['is_handler'] = True
return result
| gpl-3.0 |
jalavik/invenio | invenio/modules/jsonalchemy/jsonext/engines/sqlalchemy.py | 17 | 5159 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio 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 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""SQLAlchemy storage engine implementation."""
import six
from flask.helpers import locked_cached_property
from werkzeug import import_string
from invenio.modules.jsonalchemy.storage import Storage
class SQLAlchemyStorage(Storage):
"""Implement database backend for SQLAlchemy model storage."""
# FIXME: This storage engine should use transactions!
def __init__(self, model, **kwards):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.__init__`."""
self.__db = kwards.get('sqlalchemy_backend',
'invenio.ext.sqlalchemy:db')
self.__model = model
@locked_cached_property
def db(self):
"""Return SQLAlchemy database object."""
if isinstance(self.__db, six.string_types):
self.__db = import_string(self.__db)
if not self.__db.engine.dialect.has_table(self.__db.engine,
self.model.__tablename__):
self.model.__table__.create(bind=self.__db.engine)
self.__db.session.commit()
return self.__db
@locked_cached_property
def model(self):
"""Return SQLAchemy model."""
if isinstance(self.__model, six.string_types):
return import_string(self.__model)
return self.__model
def save_one(self, json, id=None):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.save_one`."""
if id is None:
id = json['_id']
self.db.session.add(self.model(id=id, json=json))
self.db.session.commit()
def save_many(self, jsons, ids=None):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.save_many`."""
if ids is None:
ids = map(lambda j: j['_id'], jsons)
self.db.session.add_all([self.model(id=id, json=json)
for id, json in zip(ids, jsons)])
self.db.session.commit()
def update_one(self, json, id=None):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.update_one`."""
#FIXME: what if we get only the fields that have change
if id is None:
id = json['_id']
self.db.session.merge(self.model(id=id, json=json))
self.db.session.commit()
def update_many(self, jsons, ids=None):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.update_many`."""
#FIXME: what if we get only the fields that have change
if ids is None:
ids = map(lambda j: j['_id'], jsons)
for id, json in zip(ids, jsons):
self.db.session.merge(self.model(id=id, json=json))
self.db.session.commit()
def get_one(self, id):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.get_one`."""
return self.db.session.query(self.model.json)\
.filter_by(id=id).one().json
def get_many(self, ids):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.get_many`."""
for json in self.db.session.query(self.model.json)\
.filter(self.model.id.in_(ids))\
.all():
yield json[0]
def get_field_values(self, recids, field, repetitive_values=True, count=False,
include_recid=False, split_by=0):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.get_field_values`."""
#TODO
raise NotImplementedError()
def get_fields_values(self, recids, fields, repetitive_values=True, count=False,
include_recid=False, split_by=0):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.get_fields_values`."""
#TODO
raise NotImplementedError()
def search(self, query):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.search`."""
raise NotImplementedError()
def create(self):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.create`."""
if self.db.engine.dialect.has_table(
self.db.engine.connect(),
self.model.__tablename__):
assert self.model.query.count() == 0
else:
self.model.__table__.create(bind=self.db.engine)
def drop(self):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.create`."""
self.model.__table__.drop(bind=self.db.engine)
| gpl-2.0 |
synasius/django | django/db/backends/sqlite3/base.py | 323 | 18115 | """
SQLite3 backend for django.
Works with either the pysqlite2 module or the sqlite3 module in the
standard library.
"""
from __future__ import unicode_literals
import datetime
import decimal
import re
import warnings
from django.conf import settings
from django.db import utils
from django.db.backends import utils as backend_utils
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.backends.base.validation import BaseDatabaseValidation
from django.utils import six, timezone
from django.utils.dateparse import (
parse_date, parse_datetime, parse_duration, parse_time,
)
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text
from django.utils.safestring import SafeBytes
try:
import pytz
except ImportError:
pytz = None
try:
try:
from pysqlite2 import dbapi2 as Database
except ImportError:
from sqlite3 import dbapi2 as Database
except ImportError as exc:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
# Some of these import sqlite3, so import them after checking if it's installed.
from .client import DatabaseClient # isort:skip
from .creation import DatabaseCreation # isort:skip
from .features import DatabaseFeatures # isort:skip
from .introspection import DatabaseIntrospection # isort:skip
from .operations import DatabaseOperations # isort:skip
from .schema import DatabaseSchemaEditor # isort:skip
DatabaseError = Database.DatabaseError
IntegrityError = Database.IntegrityError
def adapt_datetime_warn_on_aware_datetime(value):
# Remove this function and rely on the default adapter in Django 2.0.
if settings.USE_TZ and timezone.is_aware(value):
warnings.warn(
"The SQLite database adapter received an aware datetime (%s), "
"probably from cursor.execute(). Update your code to pass a "
"naive datetime in the database connection's time zone (UTC by "
"default).", RemovedInDjango20Warning)
# This doesn't account for the database connection's timezone,
# which isn't known. (That's why this adapter is deprecated.)
value = value.astimezone(timezone.utc).replace(tzinfo=None)
return value.isoformat(str(" "))
def decoder(conv_func):
""" The Python sqlite3 interface returns always byte strings.
This function converts the received value to a regular string before
passing it to the receiver function.
"""
return lambda s: conv_func(s.decode('utf-8'))
Database.register_converter(str("bool"), decoder(lambda s: s == '1'))
Database.register_converter(str("time"), decoder(parse_time))
Database.register_converter(str("date"), decoder(parse_date))
Database.register_converter(str("datetime"), decoder(parse_datetime))
Database.register_converter(str("timestamp"), decoder(parse_datetime))
Database.register_converter(str("TIMESTAMP"), decoder(parse_datetime))
Database.register_converter(str("decimal"), decoder(backend_utils.typecast_decimal))
Database.register_adapter(datetime.datetime, adapt_datetime_warn_on_aware_datetime)
Database.register_adapter(decimal.Decimal, backend_utils.rev_typecast_decimal)
if six.PY2:
Database.register_adapter(str, lambda s: s.decode('utf-8'))
Database.register_adapter(SafeBytes, lambda s: s.decode('utf-8'))
class DatabaseWrapper(BaseDatabaseWrapper):
vendor = 'sqlite'
# SQLite doesn't actually support most of these types, but it "does the right
# thing" given more verbose field definitions, so leave them as is so that
# schema inspection is more useful.
data_types = {
'AutoField': 'integer',
'BinaryField': 'BLOB',
'BooleanField': 'bool',
'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'date',
'DateTimeField': 'datetime',
'DecimalField': 'decimal',
'DurationField': 'bigint',
'FileField': 'varchar(%(max_length)s)',
'FilePathField': 'varchar(%(max_length)s)',
'FloatField': 'real',
'IntegerField': 'integer',
'BigIntegerField': 'bigint',
'IPAddressField': 'char(15)',
'GenericIPAddressField': 'char(39)',
'NullBooleanField': 'bool',
'OneToOneField': 'integer',
'PositiveIntegerField': 'integer unsigned',
'PositiveSmallIntegerField': 'smallint unsigned',
'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint',
'TextField': 'text',
'TimeField': 'time',
'UUIDField': 'char(32)',
}
data_types_suffix = {
'AutoField': 'AUTOINCREMENT',
}
# SQLite requires LIKE statements to include an ESCAPE clause if the value
# being escaped has a percent or underscore in it.
# See http://www.sqlite.org/lang_expr.html for an explanation.
operators = {
'exact': '= %s',
'iexact': "LIKE %s ESCAPE '\\'",
'contains': "LIKE %s ESCAPE '\\'",
'icontains': "LIKE %s ESCAPE '\\'",
'regex': 'REGEXP %s',
'iregex': "REGEXP '(?i)' || %s",
'gt': '> %s',
'gte': '>= %s',
'lt': '< %s',
'lte': '<= %s',
'startswith': "LIKE %s ESCAPE '\\'",
'endswith': "LIKE %s ESCAPE '\\'",
'istartswith': "LIKE %s ESCAPE '\\'",
'iendswith': "LIKE %s ESCAPE '\\'",
}
# The patterns below are used to generate SQL pattern lookup clauses when
# the right-hand side of the lookup isn't a raw string (it might be an expression
# or the result of a bilateral transformation).
# In those cases, special characters for LIKE operators (e.g. \, *, _) should be
# escaped on database side.
#
# Note: we use str.format() here for readability as '%' is used as a wildcard for
# the LIKE operator.
pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\', '\\'), '%%', '\%%'), '_', '\_')"
pattern_ops = {
'contains': r"LIKE '%%' || {} || '%%' ESCAPE '\'",
'icontains': r"LIKE '%%' || UPPER({}) || '%%' ESCAPE '\'",
'startswith': r"LIKE {} || '%%' ESCAPE '\'",
'istartswith': r"LIKE UPPER({}) || '%%' ESCAPE '\'",
'endswith': r"LIKE '%%' || {} ESCAPE '\'",
'iendswith': r"LIKE '%%' || UPPER({}) ESCAPE '\'",
}
Database = Database
SchemaEditorClass = DatabaseSchemaEditor
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.features = DatabaseFeatures(self)
self.ops = DatabaseOperations(self)
self.client = DatabaseClient(self)
self.creation = DatabaseCreation(self)
self.introspection = DatabaseIntrospection(self)
self.validation = BaseDatabaseValidation(self)
def get_connection_params(self):
settings_dict = self.settings_dict
if not settings_dict['NAME']:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured(
"settings.DATABASES is improperly configured. "
"Please supply the NAME value.")
kwargs = {
'database': settings_dict['NAME'],
'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,
}
kwargs.update(settings_dict['OPTIONS'])
# Always allow the underlying SQLite connection to be shareable
# between multiple threads. The safe-guarding will be handled at a
# higher level by the `BaseDatabaseWrapper.allow_thread_sharing`
# property. This is necessary as the shareability is disabled by
# default in pysqlite and it cannot be changed once a connection is
# opened.
if 'check_same_thread' in kwargs and kwargs['check_same_thread']:
warnings.warn(
'The `check_same_thread` option was provided and set to '
'True. It will be overridden with False. Use the '
'`DatabaseWrapper.allow_thread_sharing` property instead '
'for controlling thread shareability.',
RuntimeWarning
)
kwargs.update({'check_same_thread': False})
if self.features.can_share_in_memory_db:
kwargs.update({'uri': True})
return kwargs
def get_new_connection(self, conn_params):
conn = Database.connect(**conn_params)
conn.create_function("django_date_extract", 2, _sqlite_date_extract)
conn.create_function("django_date_trunc", 2, _sqlite_date_trunc)
conn.create_function("django_datetime_cast_date", 2, _sqlite_datetime_cast_date)
conn.create_function("django_datetime_extract", 3, _sqlite_datetime_extract)
conn.create_function("django_datetime_trunc", 3, _sqlite_datetime_trunc)
conn.create_function("django_time_extract", 2, _sqlite_time_extract)
conn.create_function("regexp", 2, _sqlite_regexp)
conn.create_function("django_format_dtdelta", 3, _sqlite_format_dtdelta)
conn.create_function("django_power", 2, _sqlite_power)
return conn
def init_connection_state(self):
pass
def create_cursor(self):
return self.connection.cursor(factory=SQLiteCursorWrapper)
def close(self):
self.validate_thread_sharing()
# If database is in memory, closing the connection destroys the
# database. To prevent accidental data loss, ignore close requests on
# an in-memory db.
if not self.is_in_memory_db(self.settings_dict['NAME']):
BaseDatabaseWrapper.close(self)
def _savepoint_allowed(self):
# Two conditions are required here:
# - A sufficiently recent version of SQLite to support savepoints,
# - Being in a transaction, which can only happen inside 'atomic'.
# When 'isolation_level' is not None, sqlite3 commits before each
# savepoint; it's a bug. When it is None, savepoints don't make sense
# because autocommit is enabled. The only exception is inside 'atomic'
# blocks. To work around that bug, on SQLite, 'atomic' starts a
# transaction explicitly rather than simply disable autocommit.
return self.features.uses_savepoints and self.in_atomic_block
def _set_autocommit(self, autocommit):
if autocommit:
level = None
else:
# sqlite3's internal default is ''. It's different from None.
# See Modules/_sqlite/connection.c.
level = ''
# 'isolation_level' is a misleading API.
# SQLite always runs at the SERIALIZABLE isolation level.
with self.wrap_database_errors:
self.connection.isolation_level = level
def check_constraints(self, table_names=None):
"""
Checks each table name in `table_names` for rows with invalid foreign
key references. This method is intended to be used in conjunction with
`disable_constraint_checking()` and `enable_constraint_checking()`, to
determine if rows with invalid references were entered while constraint
checks were off.
Raises an IntegrityError on the first invalid foreign key reference
encountered (if any) and provides detailed information about the
invalid reference in the error message.
Backends can override this method if they can more directly apply
constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
"""
cursor = self.cursor()
if table_names is None:
table_names = self.introspection.table_names(cursor)
for table_name in table_names:
primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
if not primary_key_column_name:
continue
key_columns = self.introspection.get_key_columns(cursor, table_name)
for column_name, referenced_table_name, referenced_column_name in key_columns:
cursor.execute("""
SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
LEFT JOIN `%s` as REFERRED
ON (REFERRING.`%s` = REFERRED.`%s`)
WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
% (primary_key_column_name, column_name, table_name, referenced_table_name,
column_name, referenced_column_name, column_name, referenced_column_name))
for bad_row in cursor.fetchall():
raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
"foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
% (table_name, bad_row[0], table_name, column_name, bad_row[1],
referenced_table_name, referenced_column_name))
def is_usable(self):
return True
def _start_transaction_under_autocommit(self):
"""
Start a transaction explicitly in autocommit mode.
Staying in autocommit mode works around a bug of sqlite3 that breaks
savepoints when autocommit is disabled.
"""
self.cursor().execute("BEGIN")
def is_in_memory_db(self, name):
return name == ":memory:" or "mode=memory" in force_text(name)
FORMAT_QMARK_REGEX = re.compile(r'(?<!%)%s')
class SQLiteCursorWrapper(Database.Cursor):
"""
Django uses "format" style placeholders, but pysqlite2 uses "qmark" style.
This fixes it -- but note that if you want to use a literal "%s" in a query,
you'll need to use "%%s".
"""
def execute(self, query, params=None):
if params is None:
return Database.Cursor.execute(self, query)
query = self.convert_query(query)
return Database.Cursor.execute(self, query, params)
def executemany(self, query, param_list):
query = self.convert_query(query)
return Database.Cursor.executemany(self, query, param_list)
def convert_query(self, query):
return FORMAT_QMARK_REGEX.sub('?', query).replace('%%', '%')
def _sqlite_date_extract(lookup_type, dt):
if dt is None:
return None
try:
dt = backend_utils.typecast_timestamp(dt)
except (ValueError, TypeError):
return None
if lookup_type == 'week_day':
return (dt.isoweekday() % 7) + 1
else:
return getattr(dt, lookup_type)
def _sqlite_date_trunc(lookup_type, dt):
try:
dt = backend_utils.typecast_timestamp(dt)
except (ValueError, TypeError):
return None
if lookup_type == 'year':
return "%i-01-01" % dt.year
elif lookup_type == 'month':
return "%i-%02i-01" % (dt.year, dt.month)
elif lookup_type == 'day':
return "%i-%02i-%02i" % (dt.year, dt.month, dt.day)
def _sqlite_datetime_parse(dt, tzname):
if dt is None:
return None
try:
dt = backend_utils.typecast_timestamp(dt)
except (ValueError, TypeError):
return None
if tzname is not None:
dt = timezone.localtime(dt, pytz.timezone(tzname))
return dt
def _sqlite_datetime_cast_date(dt, tzname):
dt = _sqlite_datetime_parse(dt, tzname)
if dt is None:
return None
return dt.date().isoformat()
def _sqlite_datetime_extract(lookup_type, dt, tzname):
dt = _sqlite_datetime_parse(dt, tzname)
if dt is None:
return None
if lookup_type == 'week_day':
return (dt.isoweekday() % 7) + 1
else:
return getattr(dt, lookup_type)
def _sqlite_datetime_trunc(lookup_type, dt, tzname):
dt = _sqlite_datetime_parse(dt, tzname)
if dt is None:
return None
if lookup_type == 'year':
return "%i-01-01 00:00:00" % dt.year
elif lookup_type == 'month':
return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
elif lookup_type == 'day':
return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
elif lookup_type == 'hour':
return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour)
elif lookup_type == 'minute':
return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute)
elif lookup_type == 'second':
return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
def _sqlite_time_extract(lookup_type, dt):
if dt is None:
return None
try:
dt = backend_utils.typecast_time(dt)
except (ValueError, TypeError):
return None
return getattr(dt, lookup_type)
def _sqlite_format_dtdelta(conn, lhs, rhs):
"""
LHS and RHS can be either:
- An integer number of microseconds
- A string representing a timedelta object
- A string representing a datetime
"""
try:
if isinstance(lhs, six.integer_types):
lhs = str(decimal.Decimal(lhs) / decimal.Decimal(1000000))
real_lhs = parse_duration(lhs)
if real_lhs is None:
real_lhs = backend_utils.typecast_timestamp(lhs)
if isinstance(rhs, six.integer_types):
rhs = str(decimal.Decimal(rhs) / decimal.Decimal(1000000))
real_rhs = parse_duration(rhs)
if real_rhs is None:
real_rhs = backend_utils.typecast_timestamp(rhs)
if conn.strip() == '+':
out = real_lhs + real_rhs
else:
out = real_lhs - real_rhs
except (ValueError, TypeError):
return None
# typecast_timestamp returns a date or a datetime without timezone.
# It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
return str(out)
def _sqlite_regexp(re_pattern, re_string):
return bool(re.search(re_pattern, force_text(re_string))) if re_string is not None else False
def _sqlite_power(x, y):
return x ** y
| bsd-3-clause |
drawks/ansible | lib/ansible/modules/network/system/net_user.py | 26 | 4550 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = """
---
module: net_user
version_added: "2.4"
author: "Trishna Guha (@trishnaguha)"
short_description: Manage the aggregate of local users on network device
description:
- This module provides declarative management of the local usernames
configured on network devices. It allows playbooks to manage
either individual usernames or the aggregate of usernames in the
current running config. It also supports purging usernames from the
configuration that are not explicitly defined.
extends_documentation_fragment: network_agnostic
options:
aggregate:
description:
- The set of username objects to be configured on the remote
network device. The list entries can either be the username
or a hash of username and properties. This argument is mutually
exclusive with the C(name) argument.
name:
description:
- The username to be configured on the remote network device.
This argument accepts a string value and is mutually exclusive
with the C(aggregate) argument.
Please note that this option is not same as C(provider username).
configured_password:
description:
- The password to be configured on the remote network device. The
password needs to be provided in clear and it will be encrypted
on the device.
Please note that this option is not same as C(provider password).
update_password:
description:
- Since passwords are encrypted in the device running config, this
argument will instruct the module when to change the password. When
set to C(always), the password will always be updated in the device
and when set to C(on_create) the password will be updated only if
the username is created.
default: always
choices: ['on_create', 'always']
privilege:
description:
- The C(privilege) argument configures the privilege level of the
user when logged into the system. This argument accepts integer
values in the range of 1 to 15.
role:
description:
- Configures the role for the username in the
device running configuration. The argument accepts a string value
defining the role name. This argument does not check if the role
has been configured on the device.
sshkey:
description:
- Specifies the SSH public key to configure
for the given username. This argument accepts a valid SSH key value.
nopassword:
description:
- Defines the username without assigning
a password. This will allow the user to login to the system
without being authenticated by a password.
type: bool
purge:
description:
- Instructs the module to consider the
resource definition absolute. It will remove any previously
configured usernames on the device with the exception of the
`admin` user (the current defined set of users).
type: bool
default: false
state:
description:
- Configures the state of the username definition
as it relates to the device operational configuration. When set
to I(present), the username(s) should be configured in the device active
configuration and when set to I(absent) the username(s) should not be
in the device active configuration
default: present
choices: ['present', 'absent']
"""
EXAMPLES = """
- name: create a new user
net_user:
name: ansible
sshkey: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
state: present
- name: remove all users except admin
net_user:
purge: yes
- name: set multiple users to privilege level 15
net_user:
aggregate:
- { name: netop }
- { name: netend }
privilege: 15
state: present
- name: Change Password for User netop
net_user:
name: netop
password: "{{ new_password }}"
update_password: always
state: present
"""
RETURN = """
commands:
description: The list of configuration mode commands to send to the device
returned: always
type: list
sample:
- username ansible secret password
- username admin secret admin
"""
| gpl-3.0 |
rhndg/openedx | lms/djangoapps/edxnotes/decorators.py | 75 | 1984 | """
Decorators related to edXNotes.
"""
from django.conf import settings
import json
from edxnotes.helpers import (
get_public_endpoint,
get_id_token,
get_token_url,
generate_uid,
is_feature_enabled,
)
from edxmako.shortcuts import render_to_string
def edxnotes(cls):
"""
Decorator that makes components annotatable.
"""
original_get_html = cls.get_html
def get_html(self, *args, **kwargs):
"""
Returns raw html for the component.
"""
is_studio = getattr(self.system, "is_author_mode", False)
course = self.descriptor.runtime.modulestore.get_course(self.runtime.course_id)
# Must be disabled:
# - in Studio;
# - when Harvard Annotation Tool is enabled for the course;
# - when the feature flag or `edxnotes` setting of the course is set to False.
if is_studio or not is_feature_enabled(course):
return original_get_html(self, *args, **kwargs)
else:
return render_to_string("edxnotes_wrapper.html", {
"content": original_get_html(self, *args, **kwargs),
"uid": generate_uid(),
"edxnotes_visibility": json.dumps(
getattr(self, 'edxnotes_visibility', course.edxnotes_visibility)
),
"params": {
# Use camelCase to name keys.
"usageId": unicode(self.scope_ids.usage_id).encode("utf-8"),
"courseId": unicode(self.runtime.course_id).encode("utf-8"),
"token": get_id_token(self.runtime.get_real_user(self.runtime.anonymous_student_id)),
"tokenUrl": get_token_url(self.runtime.course_id),
"endpoint": get_public_endpoint(),
"debug": settings.DEBUG,
"eventStringLimit": settings.TRACK_MAX_EVENT / 6,
},
})
cls.get_html = get_html
return cls
| agpl-3.0 |
bluevoda/BloggyBlog | lib/python3.4/site-packages/django/core/mail/backends/base.py | 577 | 1573 | """Base email backend class."""
class BaseEmailBackend(object):
"""
Base class for email backend implementations.
Subclasses must at least overwrite send_messages().
open() and close() can be called indirectly by using a backend object as a
context manager:
with backend as connection:
# do something with connection
pass
"""
def __init__(self, fail_silently=False, **kwargs):
self.fail_silently = fail_silently
def open(self):
"""Open a network connection.
This method can be overwritten by backend implementations to
open a network connection.
It's up to the backend implementation to track the status of
a network connection if it's needed by the backend.
This method can be called by applications to force a single
network connection to be used when sending mails. See the
send_messages() method of the SMTP backend for a reference
implementation.
The default implementation does nothing.
"""
pass
def close(self):
"""Close a network connection."""
pass
def __enter__(self):
self.open()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
raise NotImplementedError('subclasses of BaseEmailBackend must override send_messages() method')
| gpl-3.0 |
google-research/google-research | task_set/train_inner_test.py | 1 | 3992 | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# python3
"""Tests for task_set.train_inner."""
import json
import os
import tempfile
import numpy as np
from task_set import datasets
from task_set import train_inner
from task_set.tasks import base
import tensorflow.compat.v1 as tf
class DummyTask(base.BaseTask):
"""Dummy task used for tests."""
def call_split(self, params, split, with_metrics=False):
r = tf.random_normal(shape=[], dtype=tf.float32)
offset = {
datasets.Split.TRAIN: 1.0,
datasets.Split.VALID_INNER: 2.0,
datasets.Split.VALID_OUTER: 3.0,
datasets.Split.TEST: 4.0,
}
loss = offset[split] + r
if with_metrics:
return loss, {"metric": -1 * loss}
else:
return loss
def get_batch(self, split):
return None
def current_params(self):
return {}
def gradients(self, loss):
return {}
def initial_params(self):
return {}
def get_variables(self):
return []
class TrainInnerTest(tf.test.TestCase):
def test_compute_averaged_loss(self):
task = DummyTask()
params = task.initial_params()
losses, _ = train_inner.compute_averaged_loss(
task, params, num_batches=100, with_metrics=False)
with self.test_session() as sess:
all_np_losses = []
for _ in range(10):
all_np_losses.append(sess.run(losses))
tr, vai, vao, te = zip(*all_np_losses)
# We are averaging over 100 with 10 replications evaluatons.
# This means the std. error of the mean should be 1/sqrt(1000) or 0.03.
# We use a threshold of 0.15, corresponding to a 5-sigma test.
self.assertNear(np.mean(tr), 1.0, 0.15)
self.assertNear(np.mean(vai), 2.0, 0.15)
self.assertNear(np.mean(vao), 3.0, 0.15)
self.assertNear(np.mean(te), 4.0, 0.15)
# ensure that each sample is also different.
self.assertLess(1e-5, np.var(tr), 0.5)
self.assertLess(1e-5, np.var(vai), 0.5)
self.assertLess(1e-5, np.var(vao), 0.5)
self.assertLess(1e-5, np.var(te), 0.5)
losses, metrics = train_inner.compute_averaged_loss(
task, params, num_batches=100, with_metrics=True)
tr_metrics, vai_metrics, vao_metrics, te_metrics = metrics
with self.test_session() as sess:
# this std. error is 1/sqrt(100), or 0.1. 5 std out is 0.5
self.assertNear(sess.run(tr_metrics["metric"]), -1.0, 0.5)
self.assertNear(sess.run(vai_metrics["metric"]), -2.0, 0.5)
self.assertNear(sess.run(vao_metrics["metric"]), -3.0, 0.5)
self.assertNear(sess.run(te_metrics["metric"]), -4.0, 0.5)
def test_train(self):
tmp_dir = tempfile.mkdtemp()
# TODO(lmetz) when toy tasks are done, switch this away from an mlp.
train_inner.train(
tmp_dir,
task_name="mlp_family_seed12",
optimizer_name="adam8p_wide_grid_seed21",
training_steps=10,
eval_every_n=5)
with tf.gfile.Open(os.path.join(tmp_dir, "result")) as f:
result_data = json.loads(f.read())
self.assertEqual(len(result_data), 3)
# 4 losses logged out per timestep
self.assertEqual(len(result_data["5"]), 4)
with tf.gfile.Open(os.path.join(tmp_dir, "time_per_step")) as f:
time_per_step_data = json.loads(f.read())
self.assertIn("mean_last_half", time_per_step_data)
self.assertIn("mean_time", time_per_step_data)
self.assertIn("median_time", time_per_step_data)
if __name__ == "__main__":
tf.test.main()
| apache-2.0 |
nemesisdesign/django | django/db/backends/oracle/schema.py | 58 | 5290 | import binascii
import copy
import datetime
import re
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.utils import DatabaseError
from django.utils import six
from django.utils.text import force_text
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
sql_create_column = "ALTER TABLE %(table)s ADD %(column)s %(definition)s"
sql_alter_column_type = "MODIFY %(column)s %(type)s"
sql_alter_column_null = "MODIFY %(column)s NULL"
sql_alter_column_not_null = "MODIFY %(column)s NOT NULL"
sql_alter_column_default = "MODIFY %(column)s DEFAULT %(default)s"
sql_alter_column_no_default = "MODIFY %(column)s DEFAULT NULL"
sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s"
sql_delete_table = "DROP TABLE %(table)s CASCADE CONSTRAINTS"
def quote_value(self, value):
if isinstance(value, (datetime.date, datetime.time, datetime.datetime)):
return "'%s'" % value
elif isinstance(value, six.string_types):
return "'%s'" % six.text_type(value).replace("\'", "\'\'")
elif isinstance(value, six.buffer_types):
return "'%s'" % force_text(binascii.hexlify(value))
elif isinstance(value, bool):
return "1" if value else "0"
else:
return str(value)
def delete_model(self, model):
# Run superclass action
super(DatabaseSchemaEditor, self).delete_model(model)
# Clean up any autoincrement trigger
self.execute("""
DECLARE
i INTEGER;
BEGIN
SELECT COUNT(1) INTO i FROM USER_SEQUENCES
WHERE SEQUENCE_NAME = '%(sq_name)s';
IF i = 1 THEN
EXECUTE IMMEDIATE 'DROP SEQUENCE "%(sq_name)s"';
END IF;
END;
/""" % {'sq_name': self.connection.ops._get_sequence_name(model._meta.db_table)})
def alter_field(self, model, old_field, new_field, strict=False):
try:
super(DatabaseSchemaEditor, self).alter_field(model, old_field, new_field, strict)
except DatabaseError as e:
description = str(e)
# If we're changing type to an unsupported type we need a
# SQLite-ish workaround
if 'ORA-22858' in description or 'ORA-22859' in description:
self._alter_field_type_workaround(model, old_field, new_field)
else:
raise
def _alter_field_type_workaround(self, model, old_field, new_field):
"""
Oracle refuses to change from some type to other type.
What we need to do instead is:
- Add a nullable version of the desired field with a temporary name
- Update the table to transfer values from old to new
- Drop old column
- Rename the new column and possibly drop the nullable property
"""
# Make a new field that's like the new one but with a temporary
# column name.
new_temp_field = copy.deepcopy(new_field)
new_temp_field.null = True
new_temp_field.column = self._generate_temp_name(new_field.column)
# Add it
self.add_field(model, new_temp_field)
# Explicit data type conversion
# https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements002.htm#sthref340
new_value = self.quote_name(old_field.column)
old_type = old_field.db_type(self.connection)
if re.match('^N?CLOB', old_type):
new_value = "TO_CHAR(%s)" % new_value
old_type = 'VARCHAR2'
if re.match('^N?VARCHAR2', old_type):
new_internal_type = new_field.get_internal_type()
if new_internal_type == 'DateField':
new_value = "TO_DATE(%s, 'YYYY-MM-DD')" % new_value
elif new_internal_type == 'DateTimeField':
new_value = "TO_TIMESTAMP(%s, 'YYYY-MM-DD HH24:MI:SS.FF')" % new_value
elif new_internal_type == 'TimeField':
# TimeField are stored as TIMESTAMP with a 1900-01-01 date part.
new_value = "TO_TIMESTAMP(CONCAT('1900-01-01 ', %s), 'YYYY-MM-DD HH24:MI:SS.FF')" % new_value
# Transfer values across
self.execute("UPDATE %s set %s=%s" % (
self.quote_name(model._meta.db_table),
self.quote_name(new_temp_field.column),
new_value,
))
# Drop the old field
self.remove_field(model, old_field)
# Rename and possibly make the new field NOT NULL
super(DatabaseSchemaEditor, self).alter_field(model, new_temp_field, new_field)
def normalize_name(self, name):
"""
Get the properly shortened and uppercased identifier as returned by
quote_name(), but without the actual quotes.
"""
nn = self.quote_name(name)
if nn[0] == '"' and nn[-1] == '"':
nn = nn[1:-1]
return nn
def _generate_temp_name(self, for_name):
"""
Generates temporary names for workarounds that need temp columns
"""
suffix = hex(hash(for_name)).upper()[1:]
return self.normalize_name(for_name + "_" + suffix)
def prepare_default(self, value):
return self.quote_value(value)
| bsd-3-clause |
pdubroy/kurt | build/MacOS/PyInstaller/pyinstaller-svn-r812/iu.py | 1 | 25840 | #
# Copyright (C) 2005, Giovanni Bajo
#
# Based on previous work under copyright (c) 2002 McMillan Enterprises, 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 2
# of the License, or (at your option) any later version.
#
# In addition to the permissions in the GNU General Public License, the
# authors give you unlimited permission to link or embed the compiled
# version of this file into combinations with other programs, and to
# distribute those combinations without any restriction coming from the
# use of this file. (The General Public License restrictions do apply in
# other respects; for example, they cover modification of the file, and
# distribution when not linked into a combine executable.)
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#
#
# **NOTE** This module is used during bootstrap. Import *ONLY* builtin modules.
#
import sys
import imp
import marshal
try:
py_version = sys.version_info
except AttributeError:
py_version = (1,5)
try:
# zipimport is supported starting with Python 2.3
import zipimport
except ImportError:
zipimport = None
try:
STRINGTYPE = basestring
except NameError:
STRINGTYPE = type("")
def debug(msg):
if 0:
sys.stderr.write(msg+"\n")
#=======================Owners==========================#
# An Owner does imports from a particular piece of turf
# That is, there's an Owner for each thing on sys.path
# There are owners for directories and .pyz files.
# There could be owners for zip files, or even URLs.
# A shadowpath (a dictionary mapping the names in
# sys.path to their owners) is used so that sys.path
# (or a package's __path__) is still a bunch of strings,
class OwnerError(IOError):
def __str__(self):
return "<OwnerError %s>" % self.message
class Owner:
def __init__(self, path):
self.path = path
def __str__(self):
return self.path
def getmod(self, nm):
return None
class DirOwner(Owner):
def __init__(self, path):
if path == '':
path = _os_getcwd()
if not pathisdir(path):
raise OwnerError("%s is not a directory" % path)
Owner.__init__(self, path)
def getmod(self, nm, getsuffixes=imp.get_suffixes,
loadco=marshal.loads, newmod=imp.new_module):
pth = _os_path_join(self.path, nm)
possibles = [(pth, 0, None)]
if pathisdir(pth) and caseOk(pth):
possibles.insert(0, (_os_path_join(pth, '__init__'), 1, pth))
py = pyc = None
for pth, ispkg, pkgpth in possibles:
for ext, mode, typ in getsuffixes():
attempt = pth+ext
try:
st = _os_stat(attempt)
except OSError, e:
assert e.errno == 2 #[Errno 2] No such file or directory
else:
# Check case
if not caseOk(attempt):
continue
if typ == imp.C_EXTENSION:
fp = open(attempt, 'rb')
mod = imp.load_module(nm, fp, attempt, (ext, mode, typ))
mod.__file__ = attempt
return mod
elif typ == imp.PY_SOURCE:
py = (attempt, st)
else:
pyc = (attempt, st)
if py or pyc:
break
if py is None and pyc is None:
return None
while 1:
if pyc is None or py and pyc[1][8] < py[1][8]:
try:
co = compile(open(py[0], 'r').read()+'\n', py[0], 'exec')
break
except SyntaxError, e:
print "Invalid syntax in %s" % py[0]
print e.args
raise
elif pyc:
stuff = open(pyc[0], 'rb').read()
try:
co = loadco(stuff[8:])
break
except (ValueError, EOFError):
pyc = None
else:
return None
mod = newmod(nm)
mod.__file__ = co.co_filename
if ispkg:
mod.__path__ = [pkgpth]
subimporter = PathImportDirector(mod.__path__)
mod.__importsub__ = subimporter.getmod
mod.__co__ = co
return mod
ZipOwner = None
if zipimport:
class ZipOwner(Owner):
def __init__(self, path):
try:
self.__zip = zipimport.zipimporter(path)
except zipimport.ZipImportError, e:
raise OwnerError('%s: %s' % (str(e), path))
Owner.__init__(self, path)
def getmod(self, nm, newmod=imp.new_module):
# We cannot simply use zipimport.load_module here
# because it both loads (= create module object)
# and imports (= execute bytecode). Instead, our
# getmod() functions are supposed to only load the modules.
# Note that imp.load_module() does the right thing, instead.
debug('zipimport try: %s within %s' % (nm, self.__zip))
try:
co = self.__zip.get_code(nm)
mod = newmod(nm)
mod.__file__ = co.co_filename
if self.__zip.is_package(nm):
mod.__path__ = [_os_path_join(self.path, nm)]
subimporter = PathImportDirector(mod.__path__)
mod.__importsub__ = subimporter.getmod
if self.path.endswith(".egg"):
# Fixup some additional special attribute so that
# pkg_resources works correctly.
# TODO: couldn't we fix these attributes always,
# for all zip files?
mod.__file__ = _os_path_join(
_os_path_join(self.path, nm), "__init__.py")
mod.__loader__ = self.__zip
mod.__co__ = co
return mod
except zipimport.ZipImportError:
debug('zipimport not found %s' % nm)
return None
# _mountzlib.py will insert archive.PYZOwner in front later
_globalownertypes = filter(None, [
ZipOwner,
DirOwner,
Owner,
])
#===================Import Directors====================================#
# ImportDirectors live on the metapath
# There's one for builtins, one for frozen modules, and one for sys.path
# Windows gets one for modules gotten from the Registry
# Mac would have them for PY_RESOURCE modules etc.
# A generalization of Owner - their concept of "turf" is broader
class ImportDirector(Owner):
pass
class BuiltinImportDirector(ImportDirector):
def __init__(self):
self.path = 'Builtins'
def getmod(self, nm, isbuiltin=imp.is_builtin):
if isbuiltin(nm):
mod = imp.load_module(nm, None, nm, ('','',imp.C_BUILTIN))
return mod
return None
class FrozenImportDirector(ImportDirector):
def __init__(self):
self.path = 'FrozenModules'
def getmod(self, nm, isfrozen=imp.is_frozen):
if isfrozen(nm):
mod = imp.load_module(nm, None, nm, ('','',imp.PY_FROZEN))
if hasattr(mod, '__path__'):
mod.__importsub__ = lambda name, pname=nm, owner=self: owner.getmod(pname+'.'+name)
return mod
return None
class RegistryImportDirector(ImportDirector):
# for Windows only
def __init__(self):
self.path = "WindowsRegistry"
self.map = {}
try:
import win32api
## import win32con
except ImportError:
pass
else:
HKEY_CURRENT_USER = -2147483647
HKEY_LOCAL_MACHINE = -2147483646
KEY_ALL_ACCESS = 983103
KEY_READ = 131097
subkey = r"Software\Python\PythonCore\%s\Modules" % sys.winver
for root in (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE):
try:
#hkey = win32api.RegOpenKeyEx(root, subkey, 0, KEY_ALL_ACCESS)
hkey = win32api.RegOpenKeyEx(root, subkey, 0, KEY_READ)
except Exception:
# If the key does not exist, simply try the next one.
pass
else:
numsubkeys, numvalues, lastmodified = win32api.RegQueryInfoKey(hkey)
for i in range(numsubkeys):
subkeyname = win32api.RegEnumKey(hkey, i)
#hskey = win32api.RegOpenKeyEx(hkey, subkeyname, 0, KEY_ALL_ACCESS)
hskey = win32api.RegOpenKeyEx(hkey, subkeyname, 0, KEY_READ)
val = win32api.RegQueryValueEx(hskey, '')
desc = getDescr(val[0])
self.map[subkeyname] = (val[0], desc)
hskey.Close()
hkey.Close()
break
def getmod(self, nm):
stuff = self.map.get(nm)
if stuff:
fnm, desc = stuff
fp = open(fnm, 'rb')
mod = imp.load_module(nm, fp, fnm, desc)
mod.__file__ = fnm
return mod
return None
class PathImportDirector(ImportDirector):
def __init__(self, pathlist=None, importers=None, ownertypes=None):
self.path = pathlist
if ownertypes == None:
self.ownertypes = _globalownertypes
else:
self.ownertypes = ownertypes
if importers:
self.shadowpath = importers
else:
self.shadowpath = {}
self.inMakeOwner = 0
self.building = {}
def __str__(self):
return str(self.path or sys.path)
def getmod(self, nm):
mod = None
for thing in (self.path or sys.path):
if isinstance(thing, STRINGTYPE):
owner = self.shadowpath.get(thing, -1)
if owner == -1:
owner = self.shadowpath[thing] = self.makeOwner(thing)
if owner:
mod = owner.getmod(nm)
else:
mod = thing.getmod(nm)
if mod:
break
return mod
def makeOwner(self, path):
if self.building.get(path):
return None
self.building[path] = 1
owner = None
for klass in self.ownertypes:
try:
# this may cause an import, which may cause recursion
# hence the protection
owner = klass(path)
except OwnerError, e:
pass
else:
break
del self.building[path]
return owner
def getDescr(fnm):
ext = getpathext(fnm)
for (suffix, mode, typ) in imp.get_suffixes():
if suffix == ext:
return (suffix, mode, typ)
#=================ImportManager============================#
# The one-and-only ImportManager
# ie, the builtin import
UNTRIED = -1
class ImportManagerException(Exception):
def __init__(self, args):
self.args = args
def __repr__(self):
return "<%s: %s>" % (self.__name__, self.args)
class ImportManager:
# really the equivalent of builtin import
def __init__(self):
self.metapath = [
BuiltinImportDirector(),
FrozenImportDirector(),
RegistryImportDirector(),
PathImportDirector()
]
self.threaded = 0
self.rlock = None
self.locker = None
self.setThreaded()
def setThreaded(self):
thread = sys.modules.get('thread', None)
if thread and not self.threaded:
#debug("iu setting threaded")
self.threaded = 1
self.rlock = thread.allocate_lock()
self._get_ident = thread.get_ident
def install(self):
import __builtin__
__builtin__.__import__ = self.importHook
__builtin__.reload = self.reloadHook
def importHook(self, name, globals=None, locals=None, fromlist=None, level=-1):
__globals_name = None
if globals:
__globals_name = globals.get('__name__')
# first see if we could be importing a relative name
debug("importHook(%s, %s, locals, %s, %s)" % (name, __globals_name, fromlist, level))
_sys_modules_get = sys.modules.get
_self_doimport = self.doimport
threaded = self.threaded
# break the name being imported up so we get:
# a.b.c -> [a, b, c]
nmparts = namesplit(name)
if not globals:
contexts = [None]
if level > 0:
raise RuntimeError("Relative import requires 'globals'")
elif level == 0:
# absolute import, do not try relative
contexts = [None]
else: # level != 0
importernm = globals.get('__name__', '')
ispkg = hasattr(_sys_modules_get(importernm), '__path__')
debug('importernm %s' % importernm)
if level < 0:
# behaviour up to Python 2.4 (and default in Python 2.5)
# add the package to searched contexts
contexts = [None]
else:
# relative import, do not try absolute
if not importernm:
raise RuntimeError("Relative import requires package")
# level=1 => current package
# level=2 => previous package => drop 1 level
if level > 1:
importernm = _string_split(importernm, '.')[:-level+1]
importernm = _string_join('.', importernm)
contexts = [None]
if importernm:
if ispkg:
# If you use the "from __init__ import" syntax, the package
# name will have a __init__ in it. We want to strip it.
if importernm[-len(".__init__"):] == ".__init__":
importernm = importernm[:-len(".__init__")]
contexts.insert(0,importernm)
else:
pkgnm = packagename(importernm)
if pkgnm:
contexts.insert(0, pkgnm)
# so contexts is [pkgnm, None], [pkgnm] or just [None]
for context in contexts:
ctx = context
i = 0
for i in range(len(nmparts)):
nm = nmparts[i]
debug(" importHook trying %s in %s" % (nm, ctx))
if ctx:
fqname = ctx + '.' + nm
else:
fqname = nm
if threaded:
self._acquire()
try:
mod = _sys_modules_get(fqname, UNTRIED)
if mod is UNTRIED:
debug('trying %s %s %s' % (nm, ctx, fqname))
mod = _self_doimport(nm, ctx, fqname)
finally:
if threaded:
self._release()
if mod:
ctx = fqname
else:
break
else:
# no break, point i beyond end
i = i + 1
if i:
break
if i<len(nmparts):
if ctx and hasattr(sys.modules[ctx], nmparts[i]):
debug("importHook done with %s %s %s (case 1)" % (name, __globals_name, fromlist))
return sys.modules[nmparts[0]]
del sys.modules[fqname]
raise ImportError, "No module named %s" % fqname
if fromlist is None:
debug("importHook done with %s %s %s (case 2)" % (name, __globals_name, fromlist))
if context:
return sys.modules[context+'.'+nmparts[0]]
return sys.modules[nmparts[0]]
bottommod = sys.modules[ctx]
if hasattr(bottommod, '__path__'):
fromlist = list(fromlist)
i = 0
while i < len(fromlist):
nm = fromlist[i]
if nm == '*':
fromlist[i:i+1] = list(getattr(bottommod, '__all__', []))
if i >= len(fromlist):
break
nm = fromlist[i]
i = i + 1
if not hasattr(bottommod, nm):
if threaded:
self._acquire()
try:
mod = self.doimport(nm, ctx, ctx+'.'+nm)
finally:
if threaded:
self._release()
debug("importHook done with %s %s %s (case 3)" % (name, __globals_name, fromlist))
return bottommod
def doimport(self, nm, parentnm, fqname, reload=0):
# Not that nm is NEVER a dotted name at this point
debug("doimport(%s, %s, %s)" % (nm, parentnm, fqname))
if parentnm:
parent = sys.modules[parentnm]
if hasattr(parent, '__path__'):
importfunc = getattr(parent, '__importsub__', None)
if not importfunc:
subimporter = PathImportDirector(parent.__path__)
importfunc = parent.__importsub__ = subimporter.getmod
debug("using parent's importfunc: %s" % importfunc)
mod = importfunc(nm)
if mod and not reload:
setattr(parent, nm, mod)
else:
debug("..parent not a package")
return None
else:
parent = None
# now we're dealing with an absolute import
for director in self.metapath:
mod = director.getmod(nm)
if mod:
break
if mod:
mod.__name__ = fqname
if reload:
sys.modules[fqname].__dict__.update(mod.__dict__)
else:
sys.modules[fqname] = mod
if hasattr(mod, '__co__'):
co = mod.__co__
del mod.__co__
try:
if reload:
exec co in sys.modules[fqname].__dict__
else:
exec co in mod.__dict__
except:
# In Python 2.4 and above, sys.modules is left clean
# after a broken import. We need to do the same to
# achieve perfect compatibility (see ticket #32).
if py_version >= (2,4,0):
# FIXME: how can we recover from a broken reload()?
# Should we save the mod dict and restore it in case
# of failure?
if not reload:
del sys.modules[fqname]
if hasattr(parent, nm):
delattr(parent, nm)
raise
if fqname == 'thread' and not self.threaded:
#debug("thread detected!")
self.setThreaded()
else:
sys.modules[fqname] = None
debug("..found %s when looking for %s" % (mod, fqname))
return mod
def reloadHook(self, mod):
fqnm = mod.__name__
nm = namesplit(fqnm)[-1]
parentnm = packagename(fqnm)
newmod = self.doimport(nm, parentnm, fqnm, reload=1)
#mod.__dict__.update(newmod.__dict__)
return newmod
def _acquire(self):
if self.rlock.locked():
if self.locker == self._get_ident():
self.lockcount = self.lockcount + 1
#debug("_acquire incrementing lockcount to %s" % self.lockcount)
return
self.rlock.acquire()
self.locker = self._get_ident()
self.lockcount = 0
#debug("_acquire first time!")
def _release(self):
if self.lockcount:
self.lockcount = self.lockcount - 1
#debug("_release decrementing lockcount to %s" % self.lockcount)
else:
self.locker = None
self.rlock.release()
#debug("_release releasing lock!")
#========= some helper functions =============================#
def packagename(s):
for i in range(len(s)-1, -1, -1):
if s[i] == '.':
break
else:
return ''
return s[:i]
def namesplit(s):
rslt = []
i = j = 0
for j in range(len(s)):
if s[j] == '.':
rslt.append(s[i:j])
i = j+1
if i < len(s):
rslt.append(s[i:])
return rslt
def getpathext(fnm):
for i in range(len(fnm)-1, -1, -1):
if fnm[i] == '.':
return fnm[i:]
return ''
def pathisdir(pathname):
"Local replacement for os.path.isdir()."
try:
s = _os_stat(pathname)
except OSError:
return None
return (s[0] & 0170000) == 0040000
_os_stat = _os_path_join = _os_getcwd = _os_path_dirname = _os_environ = _os_listdir = _os_path_basename = None
def _os_bootstrap():
"Set up 'os' module replacement functions for use during import bootstrap."
global _os_stat, _os_path_join, _os_path_dirname, _os_getcwd, _os_environ, _os_listdir, _os_path_basename
names = sys.builtin_module_names
join = dirname = environ = listdir = basename = None
mindirlen = 0
if 'posix' in names:
from posix import stat, getcwd, environ, listdir
sep = '/'
mindirlen = 1
elif 'nt' in names:
from nt import stat, getcwd, environ, listdir
sep = '\\'
mindirlen = 3
elif 'dos' in names:
from dos import stat, getcwd, environ, listdir
sep = '\\'
mindirlen = 3
elif 'os2' in names:
from os2 import stat, getcwd, environ, listdir
sep = '\\'
elif 'mac' in names:
from mac import stat, getcwd, environ, listdir
def join(a, b):
if a == '':
return b
path = s
if ':' not in a:
a = ':' + a
if a[-1:] != ':':
a = a + ':'
return a + b
else:
raise ImportError, 'no os specific module found'
if join is None:
def join(a, b, sep=sep):
if a == '':
return b
lastchar = a[-1:]
if lastchar == '/' or lastchar == sep:
return a + b
return a + sep + b
if dirname is None:
def dirname(a, sep=sep, mindirlen=mindirlen):
for i in range(len(a)-1, -1, -1):
c = a[i]
if c == '/' or c == sep:
if i < mindirlen:
return a[:i+1]
return a[:i]
return ''
if basename is None:
def basename(p):
i = p.rfind(sep)
if i == -1:
return p
else:
return p[i + len(sep):]
def _listdir(dir, cache={}):
# since this function is only used by caseOk, it's fine to cache the
# results and avoid reading the whole contents of a directory each time
# we just want to check the case of a filename.
if not dir in cache:
cache[dir] = listdir(dir)
return cache[dir]
_os_stat = stat
_os_getcwd = getcwd
_os_path_join = join
_os_path_dirname = dirname
_os_environ = environ
_os_listdir = _listdir
_os_path_basename = basename
_string_replace = _string_join = _string_split = None
def _string_bootstrap():
"""
Set up 'string' module replacement functions for use during import bootstrap.
During bootstrap, we can use only builtin modules since import does not work
yet. For Python 2.0+, we can use string methods so this is not a problem.
For Python 1.5, we would need the string module, so we need replacements.
"""
global _string_replace, _string_join, _string_split
def join(sep, words):
res = ''
for w in words:
res = res + (sep + w)
return res[len(sep):]
def split(s, sep, maxsplit=0):
res = []
nsep = len(sep)
if nsep == 0:
return [s]
ns = len(s)
if maxsplit <= 0: maxsplit = ns
i = j = 0
count = 0
while j+nsep <= ns:
if s[j:j+nsep] == sep:
count = count + 1
res.append(s[i:j])
i = j = j + nsep
if count >= maxsplit: break
else:
j = j + 1
res.append(s[i:])
return res
def replace(str, old, new):
return _string_join(new, _string_split(str, old))
_string_join = getattr(STRINGTYPE, "join", join)
_string_split = getattr(STRINGTYPE, "split", split)
_string_replace = getattr(STRINGTYPE, "replace", replace)
_os_bootstrap()
if not _os_environ.has_key('PYTHONCASEOK') and sys.version_info >= (2, 1):
def caseOk(filename):
files = _os_listdir(_os_path_dirname(filename))
return _os_path_basename(filename) in files
else:
def caseOk(filename):
return True
_string_bootstrap()
| gpl-2.0 |
ShownX/incubator-mxnet | example/profiler/profiler_ndarray.py | 25 | 11382 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import mxnet as mx
import numpy as np
import pickle as pkl
def _np_reduce(dat, axis, keepdims, numpy_reduce_func):
if isinstance(axis, int):
axis = [axis]
else:
axis = list(axis) if axis is not None else range(len(dat.shape))
ret = dat
for i in reversed(sorted(axis)):
ret = numpy_reduce_func(ret, axis=i)
if keepdims:
keepdims_shape = list(dat.shape)
for i in axis:
keepdims_shape[i] = 1
ret = ret.reshape(tuple(keepdims_shape))
return ret
def reldiff(a, b):
diff = np.abs(a - b)
norm = np.abs(a)
reldiff = np.max(diff / (norm + 1e-7))
return reldiff
def same(a, b):
return np.sum(a != b) == 0
def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]):
"""check function consistency with uniform random numbers"""
if isinstance(arg_shapes, int):
assert dim
shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim))
arg_shapes = [shape] * arg_shapes
for dtype in type_list:
ndarray_arg = []
numpy_arg = []
for s in arg_shapes:
npy = np.random.uniform(rmin, 10, s).astype(dtype)
narr = mx.nd.array(npy, dtype=dtype)
ndarray_arg.append(narr)
numpy_arg.append(npy)
out1 = uf(*ndarray_arg)
if npuf is None:
out2 = uf(*numpy_arg).astype(dtype)
else:
out2 = npuf(*numpy_arg).astype(dtype)
assert out1.shape == out2.shape
if isinstance(out1, mx.nd.NDArray):
out1 = out1.asnumpy()
if dtype == np.float16:
assert reldiff(out1, out2) < 2e-3
else:
assert reldiff(out1, out2) < 1e-6
def random_ndarray(dim):
shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim))
data = mx.nd.array(np.random.uniform(-10, 10, shape))
return data
def test_ndarray_elementwise():
np.random.seed(0)
nrepeat = 10
maxdim = 4
all_type = [np.float32, np.float64, np.float16, np.uint8, np.int32]
real_type = [np.float32, np.float64, np.float16]
for repeat in range(nrepeat):
for dim in range(1, maxdim):
check_with_uniform(lambda x, y: x + y, 2, dim, type_list=all_type)
check_with_uniform(lambda x, y: x - y, 2, dim, type_list=all_type)
check_with_uniform(lambda x, y: x * y, 2, dim, type_list=all_type)
check_with_uniform(lambda x, y: x / y, 2, dim, type_list=real_type)
check_with_uniform(lambda x, y: x / y, 2, dim, rmin=1, type_list=all_type)
check_with_uniform(mx.nd.sqrt, 1, dim, np.sqrt, rmin=0)
check_with_uniform(mx.nd.square, 1, dim, np.square, rmin=0)
check_with_uniform(lambda x: mx.nd.norm(x).asscalar(), 1, dim, np.linalg.norm)
def test_ndarray_negate():
npy = np.random.uniform(-10, 10, (2,3,4))
arr = mx.nd.array(npy)
assert reldiff(npy, arr.asnumpy()) < 1e-6
assert reldiff(-npy, (-arr).asnumpy()) < 1e-6
# a final check to make sure the negation (-) is not implemented
# as inplace operation, so the contents of arr does not change after
# we compute (-arr)
assert reldiff(npy, arr.asnumpy()) < 1e-6
def test_ndarray_choose():
shape = (100, 20)
npy = np.arange(np.prod(shape)).reshape(shape)
arr = mx.nd.array(npy)
nrepeat = 3
for repeat in range(nrepeat):
indices = np.random.randint(shape[1], size=shape[0])
assert same(npy[np.arange(shape[0]), indices],
mx.nd.choose_element_0index(arr, mx.nd.array(indices)).asnumpy())
def test_ndarray_fill():
shape = (100, 20)
npy = np.arange(np.prod(shape)).reshape(shape)
arr = mx.nd.array(npy)
new_npy = npy.copy()
nrepeat = 3
for repeat in range(nrepeat):
indices = np.random.randint(shape[1], size=shape[0])
val = np.random.randint(shape[1], size=shape[0])
new_npy[:] = npy
new_npy[np.arange(shape[0]), indices] = val
assert same(new_npy,
mx.nd.fill_element_0index(arr, mx.nd.array(val), mx.nd.array(indices)).asnumpy())
def test_ndarray_onehot():
shape = (100, 20)
npy = np.arange(np.prod(shape)).reshape(shape)
arr = mx.nd.array(npy)
nrepeat = 3
for repeat in range(nrepeat):
indices = np.random.randint(shape[1], size=shape[0])
npy[:] = 0.0
npy[np.arange(shape[0]), indices] = 1.0
mx.nd.onehot_encode(mx.nd.array(indices), out=arr)
assert same(npy, arr.asnumpy())
def test_ndarray_copy():
c = mx.nd.array(np.random.uniform(-10, 10, (10, 10)))
d = c.copyto(mx.Context('cpu', 0))
assert np.sum(np.abs(c.asnumpy() != d.asnumpy())) == 0.0
def test_ndarray_scalar():
c = mx.nd.empty((10,10))
d = mx.nd.empty((10,10))
c[:] = 0.5
d[:] = 1.0
d -= c * 2 / 3 * 6.0
c += 0.5
assert(np.sum(c.asnumpy()) - 100 < 1e-5)
assert(np.sum(d.asnumpy()) + 100 < 1e-5)
c[:] = 2
assert(np.sum(c.asnumpy()) - 200 < 1e-5)
d = -c + 2
assert(np.sum(d.asnumpy()) < 1e-5)
def test_ndarray_pickle():
np.random.seed(0)
maxdim = 5
nrepeat = 10
for repeat in range(nrepeat):
for dim in range(1, maxdim):
a = random_ndarray(dim)
b = mx.nd.empty(a.shape)
a[:] = np.random.uniform(-10, 10, a.shape)
b[:] = np.random.uniform(-10, 10, a.shape)
a = a + b
data = pkl.dumps(a)
a2 = pkl.loads(data)
assert np.sum(a.asnumpy() != a2.asnumpy()) == 0
def test_ndarray_saveload():
np.random.seed(0)
maxdim = 5
nrepeat = 10
fname = 'tmp_list.bin'
for repeat in range(nrepeat):
data = []
for i in range(10):
data.append(random_ndarray(np.random.randint(1, 5)))
mx.nd.save(fname, data)
data2 = mx.nd.load(fname)
assert len(data) == len(data2)
for x, y in zip(data, data2):
assert np.sum(x.asnumpy() != y.asnumpy()) == 0
dmap = {'ndarray xx %s' % i : x for i, x in enumerate(data)}
mx.nd.save(fname, dmap)
dmap2 = mx.nd.load(fname)
assert len(dmap2) == len(dmap)
for k, x in dmap.items():
y = dmap2[k]
assert np.sum(x.asnumpy() != y.asnumpy()) == 0
os.remove(fname)
def test_ndarray_slice():
shape = (10,)
A = mx.nd.array(np.random.uniform(-10, 10, shape))
A2 = A.asnumpy()
assert same(A[3:8].asnumpy(), A2[3:8])
A2[3:8] *= 10;
A[3:8] = A2[3:8]
assert same(A[3:8].asnumpy(), A2[3:8])
def test_ndarray_slice_along_axis():
arr = mx.nd.array(np.random.uniform(-10, 10, (3, 4, 2, 3)))
sub_arr = mx.nd.zeros((3, 2, 2, 3))
arr._copy_slice_to(1, 1, 3, sub_arr)
# test we sliced correctly
assert same(arr.asnumpy()[:, 1:3, :, :], sub_arr.asnumpy())
# test that slice is copy, instead of shared memory
sub_arr[:] = 0
assert not same(arr.asnumpy()[:, 1:3, :, :], sub_arr.asnumpy())
def test_clip():
shape = (10,)
A = mx.random.uniform(-10, 10, shape)
B = mx.nd.clip(A, -2, 2)
B1 = B.asnumpy()
for i in range(shape[0]):
assert B1[i] >= -2
assert B1[i] <= 2
def test_dot():
a = np.random.uniform(-3, 3, (3, 4))
b = np.random.uniform(-3, 3, (4, 5))
c = np.dot(a, b)
A = mx.nd.array(a)
B = mx.nd.array(b)
C = mx.nd.dot(A, B)
assert reldiff(c, C.asnumpy()) < 1e-5
def test_reduce():
sample_num = 200
def test_reduce_inner(numpy_reduce_func, nd_reduce_func):
for i in range(sample_num):
ndim = np.random.randint(1, 6)
shape = np.random.randint(1, 11, size=ndim)
axis_flags = np.random.randint(0, 2, size=ndim)
axes = []
for (axis, flag) in enumerate(axis_flags):
if flag:
axes.append(axis)
keepdims = np.random.randint(0, 2)
dat = np.random.rand(*shape) - 0.5
if 0 == len(axes):
axes = tuple(range(ndim))
else:
axes = tuple(axes)
numpy_ret = numpy_reduce_func(dat, axis=axes, keepdims=keepdims)
ndarray_ret = nd_reduce_func(mx.nd.array(dat), axis=axes, keepdims=keepdims)
if type(ndarray_ret) is mx.ndarray.NDArray:
ndarray_ret = ndarray_ret.asnumpy()
assert (ndarray_ret.shape == numpy_ret.shape) or \
(ndarray_ret.shape == (1,) and numpy_ret.shape == ()), "nd:%s, numpy:%s" \
%(ndarray_ret.shape, numpy_ret.shape)
err = np.square(ndarray_ret - numpy_ret).mean()
assert err < 1E-4
test_reduce_inner(lambda data, axis, keepdims:_np_reduce(data, axis, keepdims, np.sum),
mx.nd.sum)
test_reduce_inner(lambda data, axis, keepdims:_np_reduce(data, axis, keepdims, np.max),
mx.nd.max)
test_reduce_inner(lambda data, axis, keepdims:_np_reduce(data, axis, keepdims, np.min),
mx.nd.min)
def test_broadcast():
sample_num = 1000
def test_broadcast_to():
for i in range(sample_num):
ndim = np.random.randint(1, 6)
target_shape = np.random.randint(1, 11, size=ndim)
shape = target_shape.copy()
axis_flags = np.random.randint(0, 2, size=ndim)
axes = []
for (axis, flag) in enumerate(axis_flags):
if flag:
shape[axis] = 1
dat = np.random.rand(*shape) - 0.5
numpy_ret = dat
ndarray_ret = mx.nd.array(dat).broadcast_to(shape=target_shape)
if type(ndarray_ret) is mx.ndarray.NDArray:
ndarray_ret = ndarray_ret.asnumpy()
assert (ndarray_ret.shape == target_shape).all()
err = np.square(ndarray_ret - numpy_ret).mean()
assert err < 1E-8
test_broadcast_to()
if __name__ == '__main__':
mx.profiler.profiler_set_config(mode='all', filename='profile_ndarray.json')
mx.profiler.profiler_set_state('run')
test_ndarray_slice_along_axis()
test_broadcast()
test_ndarray_elementwise()
test_ndarray_slice()
test_ndarray_pickle()
test_ndarray_saveload()
test_ndarray_copy()
test_ndarray_negate()
test_ndarray_scalar()
test_clip()
test_dot()
test_ndarray_choose()
test_ndarray_onehot()
test_ndarray_fill()
test_reduce()
mx.profiler.profiler_set_state('stop')
| apache-2.0 |
surligas/cs436-gnuradio | gr-wxgui/python/wxgui/scopesink2.py | 92 | 1447 | #
# Copyright 2008,2009 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr
p = gr.prefs()
style = p.get_string('wxgui', 'style', 'auto')
if style == 'auto' or style == 'gl':
try:
import wx.glcanvas
from OpenGL.GL import *
from scopesink_gl import scope_sink_f, scope_sink_c
except ImportError:
if style == 'gl':
raise RuntimeError("Unable to import OpenGL. Are Python wrappers for OpenGL installed?")
else:
# Fall backto non-gl sinks
from scopesink_nongl import scope_sink_f, scope_sink_c
elif style == 'nongl':
from scopesink_nongl import scope_sink_f, scope_sink_c
else:
raise RuntimeError("Unknown wxgui style")
| gpl-3.0 |
kvar/ansible | lib/ansible/modules/network/aci/mso_schema_template_contract_filter.py | 11 | 11535 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: mso_schema_template_contract_filter
short_description: Manage contract filters in schema templates
description:
- Manage contract filters in schema templates on Cisco ACI Multi-Site.
author:
- Dag Wieers (@dagwieers)
version_added: '2.8'
options:
schema:
description:
- The name of the schema.
type: str
required: yes
template:
description:
- The name of the template.
type: str
required: yes
contract:
description:
- The name of the contract to manage.
type: str
required: yes
contract_display_name:
description:
- The name as displayed on the MSO web interface.
- This defaults to the contract name when unset on creation.
type: str
contract_filter_type:
description:
- The type of filters defined in this contract.
- This defaults to C(both-way) when unset on creation.
type: str
choices: [ both-way, one-way ]
contract_scope:
description:
- The scope of the contract.
- This defaults to C(vrf) when unset on creation.
type: str
choices: [ application-profile, global, tenant, vrf ]
filter:
description:
- The filter to associate with this contract.
type: str
aliases: [ name ]
filter_template:
description:
- The template name in which the filter is located.
type: str
filter_schema:
description:
- The schema name in which the filter is located.
type: str
filter_type:
description:
- The type of filter to manage.
type: str
choices: [ both-way, consumer-to-provider, provider-to-consumer ]
default: both-way
aliases: [ type ]
filter_directives:
description:
- A list of filter directives.
type: list
choices: [ log, none ]
state:
description:
- Use C(present) or C(absent) for adding or removing.
- Use C(query) for listing an object or multiple objects.
type: str
choices: [ absent, present, query ]
default: present
seealso:
- module: mso_schema_template_filter_entry
notes:
- Due to restrictions of the MSO REST API this module creates contracts when needed, and removes them when the last filter has been removed.
- Due to restrictions of the MSO REST API concurrent modifications to contract filters can be dangerous and corrupt data.
extends_documentation_fragment: mso
'''
EXAMPLES = r'''
- name: Add a new contract filter
mso_schema_template_contract_filter:
host: mso_host
username: admin
password: SomeSecretPassword
schema: Schema 1
template: Template 1
contract: Contract 1
contract_scope: global
filter: Filter 1
state: present
delegate_to: localhost
- name: Remove a contract filter
mso_schema_template_contract_filter:
host: mso_host
username: admin
password: SomeSecretPassword
schema: Schema 1
template: Template 1
contract: Contract 1
filter: Filter 1
state: absent
delegate_to: localhost
- name: Query a specific contract filter
mso_schema_template_contract_filter:
host: mso_host
username: admin
password: SomeSecretPassword
schema: Schema 1
template: Template 1
contract: Contract 1
filter: Filter 1
state: query
delegate_to: localhost
register: query_result
- name: Query all contract filters
mso_schema_template_contract_filter:
host: mso_host
username: admin
password: SomeSecretPassword
schema: Schema 1
template: Template 1
contract: Contract 1
state: query
delegate_to: localhost
register: query_result
'''
RETURN = r'''
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.aci.mso import MSOModule, mso_argument_spec, mso_reference_spec, issubset
FILTER_KEYS = {
'both-way': 'filterRelationships',
'consumer-to-provider': 'filterRelationshipsConsumerToProvider',
'provider-to-consumer': 'filterRelationshipsProviderToConsumer',
}
def main():
argument_spec = mso_argument_spec()
argument_spec.update(
schema=dict(type='str', required=True),
template=dict(type='str', required=True),
contract=dict(type='str', required=True),
contract_display_name=dict(type='str'),
contract_scope=dict(type='str', choices=['application-profile', 'global', 'tenant', 'vrf']),
contract_filter_type=dict(type='str', choices=['both-way', 'one-way']),
filter=dict(type='str', aliases=['name']), # This parameter is not required for querying all objects
filter_directives=dict(type='list', choices=['log', 'none']),
filter_template=dict(type='str'),
filter_schema=dict(type='str'),
filter_type=dict(type='str', default='both-way', choices=FILTER_KEYS.keys(), aliases=['type']),
state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_if=[
['state', 'absent', ['filter']],
['state', 'present', ['filter']],
],
)
schema = module.params['schema']
template = module.params['template']
contract = module.params['contract']
contract_display_name = module.params['contract_display_name']
contract_filter_type = module.params['contract_filter_type']
contract_scope = module.params['contract_scope']
filter_name = module.params['filter']
filter_directives = module.params['filter_directives']
filter_template = module.params['filter_template']
filter_schema = module.params['filter_schema']
filter_type = module.params['filter_type']
state = module.params['state']
contract_ftype = 'bothWay' if contract_filter_type == 'both-way' else 'oneWay'
if contract_filter_type == 'both-way' and filter_type != 'both-way':
module.warn("You are adding 'one-way' filters to a 'both-way' contract")
elif contract_filter_type != 'both-way' and filter_type == 'both-way':
module.warn("You are adding 'both-way' filters to a 'one-way' contract")
if filter_template is None:
filter_template = template
if filter_schema is None:
filter_schema = schema
filter_key = FILTER_KEYS[filter_type]
mso = MSOModule(module)
filter_schema_id = mso.lookup_schema(filter_schema)
# Get schema object
schema_obj = mso.get_obj('schemas', displayName=schema)
if schema_obj:
schema_id = schema_obj['id']
else:
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template
templates = [t['name'] for t in schema_obj['templates']]
if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template)
# Get contracts
mso.existing = {}
contract_idx = None
filter_idx = None
contracts = [c['name'] for c in schema_obj['templates'][template_idx]['contracts']]
if contract in contracts:
contract_idx = contracts.index(contract)
filters = [f['filterRef'] for f in schema_obj['templates'][template_idx]['contracts'][contract_idx][filter_key]]
filter_ref = mso.filter_ref(schema_id=filter_schema_id, template=filter_template, filter=filter_name)
if filter_ref in filters:
filter_idx = filters.index(filter_ref)
filter_path = '/templates/{0}/contracts/{1}/{2}/{3}'.format(template, contract, filter_key, filter_name)
mso.existing = schema_obj['templates'][template_idx]['contracts'][contract_idx][filter_key][filter_idx]
if state == 'query':
if contract_idx is None:
mso.fail_json(msg="Provided contract '{0}' does not exist. Existing contracts: {1}".format(contract, ', '.join(contracts)))
if filter_name is None:
mso.existing = schema_obj['templates'][template_idx]['contracts'][contract_idx][filter_key]
elif not mso.existing:
mso.fail_json(msg="FilterRef '{filter_ref}' not found".format(filter_ref=filter_ref))
mso.exit_json()
ops = []
contract_path = '/templates/{0}/contracts/{1}'.format(template, contract)
filters_path = '/templates/{0}/contracts/{1}/{2}'.format(template, contract, filter_key)
mso.previous = mso.existing
if state == 'absent':
mso.proposed = mso.sent = {}
if contract_idx is None:
# There was no contract to begin with
pass
elif filter_idx is None:
# There was no filter to begin with
pass
elif len(filters) == 1:
# There is only one filter, remove contract
mso.existing = {}
ops.append(dict(op='remove', path=contract_path))
else:
# Remove filter
mso.existing = {}
ops.append(dict(op='remove', path=filter_path))
elif state == 'present':
if filter_directives is None:
filter_directives = ['none']
payload = dict(
filterRef=dict(
filterName=filter_name,
templateName=filter_template,
schemaId=filter_schema_id,
),
directives=filter_directives,
)
mso.sanitize(payload, collate=True)
mso.existing = mso.sent
if contract_idx is None:
# Contract does not exist, so we have to create it
if contract_display_name is None:
contract_display_name = contract
if contract_filter_type is None:
contract_ftype = 'bothWay'
if contract_scope is None:
contract_scope = 'context'
payload = {
'name': contract,
'displayName': contract_display_name,
'filterType': contract_ftype,
'scope': contract_scope,
}
ops.append(dict(op='add', path='/templates/{0}/contracts/-'.format(template), value=payload))
else:
# Contract exists, but may require an update
if contract_display_name is not None:
ops.append(dict(op='replace', path=contract_path + '/displayName', value=contract_display_name))
if contract_filter_type is not None:
ops.append(dict(op='replace', path=contract_path + '/filterType', value=contract_ftype))
if contract_scope is not None:
ops.append(dict(op='replace', path=contract_path + '/scope', value=contract_scope))
if filter_idx is None:
# Filter does not exist, so we have to add it
ops.append(dict(op='add', path=filters_path + '/-', value=mso.sent))
else:
# Filter exists, we have to update it
ops.append(dict(op='replace', path=filter_path, value=mso.sent))
if not module.check_mode:
mso.request(schema_path, method='PATCH', data=ops)
mso.exit_json()
if __name__ == "__main__":
main()
| gpl-3.0 |
mlyundin/scikit-learn | examples/bicluster/bicluster_newsgroups.py | 142 | 7183 | """
================================================================
Biclustering documents with the Spectral Co-clustering algorithm
================================================================
This example demonstrates the Spectral Co-clustering algorithm on the
twenty newsgroups dataset. The 'comp.os.ms-windows.misc' category is
excluded because it contains many posts containing nothing but data.
The TF-IDF vectorized posts form a word frequency matrix, which is
then biclustered using Dhillon's Spectral Co-Clustering algorithm. The
resulting document-word biclusters indicate subsets words used more
often in those subsets documents.
For a few of the best biclusters, its most common document categories
and its ten most important words get printed. The best biclusters are
determined by their normalized cut. The best words are determined by
comparing their sums inside and outside the bicluster.
For comparison, the documents are also clustered using
MiniBatchKMeans. The document clusters derived from the biclusters
achieve a better V-measure than clusters found by MiniBatchKMeans.
Output::
Vectorizing...
Coclustering...
Done in 9.53s. V-measure: 0.4455
MiniBatchKMeans...
Done in 12.00s. V-measure: 0.3309
Best biclusters:
----------------
bicluster 0 : 1951 documents, 4373 words
categories : 23% talk.politics.guns, 19% talk.politics.misc, 14% sci.med
words : gun, guns, geb, banks, firearms, drugs, gordon, clinton, cdt, amendment
bicluster 1 : 1165 documents, 3304 words
categories : 29% talk.politics.mideast, 26% soc.religion.christian, 25% alt.atheism
words : god, jesus, christians, atheists, kent, sin, morality, belief, resurrection, marriage
bicluster 2 : 2219 documents, 2830 words
categories : 18% comp.sys.mac.hardware, 16% comp.sys.ibm.pc.hardware, 16% comp.graphics
words : voltage, dsp, board, receiver, circuit, shipping, packages, stereo, compression, package
bicluster 3 : 1860 documents, 2745 words
categories : 26% rec.motorcycles, 23% rec.autos, 13% misc.forsale
words : bike, car, dod, engine, motorcycle, ride, honda, cars, bmw, bikes
bicluster 4 : 12 documents, 155 words
categories : 100% rec.sport.hockey
words : scorer, unassisted, reichel, semak, sweeney, kovalenko, ricci, audette, momesso, nedved
"""
from __future__ import print_function
print(__doc__)
from collections import defaultdict
import operator
import re
from time import time
import numpy as np
from sklearn.cluster.bicluster import SpectralCoclustering
from sklearn.cluster import MiniBatchKMeans
from sklearn.externals.six import iteritems
from sklearn.datasets.twenty_newsgroups import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.cluster import v_measure_score
def number_aware_tokenizer(doc):
""" Tokenizer that maps all numeric tokens to a placeholder.
For many applications, tokens that begin with a number are not directly
useful, but the fact that such a token exists can be relevant. By applying
this form of dimensionality reduction, some methods may perform better.
"""
token_pattern = re.compile(u'(?u)\\b\\w\\w+\\b')
tokens = token_pattern.findall(doc)
tokens = ["#NUMBER" if token[0] in "0123456789_" else token
for token in tokens]
return tokens
# exclude 'comp.os.ms-windows.misc'
categories = ['alt.atheism', 'comp.graphics',
'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware',
'comp.windows.x', 'misc.forsale', 'rec.autos',
'rec.motorcycles', 'rec.sport.baseball',
'rec.sport.hockey', 'sci.crypt', 'sci.electronics',
'sci.med', 'sci.space', 'soc.religion.christian',
'talk.politics.guns', 'talk.politics.mideast',
'talk.politics.misc', 'talk.religion.misc']
newsgroups = fetch_20newsgroups(categories=categories)
y_true = newsgroups.target
vectorizer = TfidfVectorizer(stop_words='english', min_df=5,
tokenizer=number_aware_tokenizer)
cocluster = SpectralCoclustering(n_clusters=len(categories),
svd_method='arpack', random_state=0)
kmeans = MiniBatchKMeans(n_clusters=len(categories), batch_size=20000,
random_state=0)
print("Vectorizing...")
X = vectorizer.fit_transform(newsgroups.data)
print("Coclustering...")
start_time = time()
cocluster.fit(X)
y_cocluster = cocluster.row_labels_
print("Done in {:.2f}s. V-measure: {:.4f}".format(
time() - start_time,
v_measure_score(y_cocluster, y_true)))
print("MiniBatchKMeans...")
start_time = time()
y_kmeans = kmeans.fit_predict(X)
print("Done in {:.2f}s. V-measure: {:.4f}".format(
time() - start_time,
v_measure_score(y_kmeans, y_true)))
feature_names = vectorizer.get_feature_names()
document_names = list(newsgroups.target_names[i] for i in newsgroups.target)
def bicluster_ncut(i):
rows, cols = cocluster.get_indices(i)
if not (np.any(rows) and np.any(cols)):
import sys
return sys.float_info.max
row_complement = np.nonzero(np.logical_not(cocluster.rows_[i]))[0]
col_complement = np.nonzero(np.logical_not(cocluster.columns_[i]))[0]
# Note: the following is identical to X[rows[:, np.newaxis], cols].sum() but
# much faster in scipy <= 0.16
weight = X[rows][:, cols].sum()
cut = (X[row_complement][:, cols].sum() +
X[rows][:, col_complement].sum())
return cut / weight
def most_common(d):
"""Items of a defaultdict(int) with the highest values.
Like Counter.most_common in Python >=2.7.
"""
return sorted(iteritems(d), key=operator.itemgetter(1), reverse=True)
bicluster_ncuts = list(bicluster_ncut(i)
for i in range(len(newsgroups.target_names)))
best_idx = np.argsort(bicluster_ncuts)[:5]
print()
print("Best biclusters:")
print("----------------")
for idx, cluster in enumerate(best_idx):
n_rows, n_cols = cocluster.get_shape(cluster)
cluster_docs, cluster_words = cocluster.get_indices(cluster)
if not len(cluster_docs) or not len(cluster_words):
continue
# categories
counter = defaultdict(int)
for i in cluster_docs:
counter[document_names[i]] += 1
cat_string = ", ".join("{:.0f}% {}".format(float(c) / n_rows * 100, name)
for name, c in most_common(counter)[:3])
# words
out_of_cluster_docs = cocluster.row_labels_ != cluster
out_of_cluster_docs = np.where(out_of_cluster_docs)[0]
word_col = X[:, cluster_words]
word_scores = np.array(word_col[cluster_docs, :].sum(axis=0) -
word_col[out_of_cluster_docs, :].sum(axis=0))
word_scores = word_scores.ravel()
important_words = list(feature_names[cluster_words[i]]
for i in word_scores.argsort()[:-11:-1])
print("bicluster {} : {} documents, {} words".format(
idx, n_rows, n_cols))
print("categories : {}".format(cat_string))
print("words : {}\n".format(', '.join(important_words)))
| bsd-3-clause |
abhisg/scikit-learn | sklearn/datasets/tests/test_samples_generator.py | 181 | 15664 | from __future__ import division
from collections import defaultdict
from functools import partial
import numpy as np
import scipy.sparse as sp
from sklearn.externals.six.moves import zip
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_raises
from sklearn.datasets import make_classification
from sklearn.datasets import make_multilabel_classification
from sklearn.datasets import make_hastie_10_2
from sklearn.datasets import make_regression
from sklearn.datasets import make_blobs
from sklearn.datasets import make_friedman1
from sklearn.datasets import make_friedman2
from sklearn.datasets import make_friedman3
from sklearn.datasets import make_low_rank_matrix
from sklearn.datasets import make_sparse_coded_signal
from sklearn.datasets import make_sparse_uncorrelated
from sklearn.datasets import make_spd_matrix
from sklearn.datasets import make_swiss_roll
from sklearn.datasets import make_s_curve
from sklearn.datasets import make_biclusters
from sklearn.datasets import make_checkerboard
from sklearn.utils.validation import assert_all_finite
def test_make_classification():
X, y = make_classification(n_samples=100, n_features=20, n_informative=5,
n_redundant=1, n_repeated=1, n_classes=3,
n_clusters_per_class=1, hypercube=False,
shift=None, scale=None, weights=[0.1, 0.25],
random_state=0)
assert_equal(X.shape, (100, 20), "X shape mismatch")
assert_equal(y.shape, (100,), "y shape mismatch")
assert_equal(np.unique(y).shape, (3,), "Unexpected number of classes")
assert_equal(sum(y == 0), 10, "Unexpected number of samples in class #0")
assert_equal(sum(y == 1), 25, "Unexpected number of samples in class #1")
assert_equal(sum(y == 2), 65, "Unexpected number of samples in class #2")
def test_make_classification_informative_features():
"""Test the construction of informative features in make_classification
Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and
fully-specified `weights`.
"""
# Create very separate clusters; check that vertices are unique and
# correspond to classes
class_sep = 1e6
make = partial(make_classification, class_sep=class_sep, n_redundant=0,
n_repeated=0, flip_y=0, shift=0, scale=1, shuffle=False)
for n_informative, weights, n_clusters_per_class in [(2, [1], 1),
(2, [1/3] * 3, 1),
(2, [1/4] * 4, 1),
(2, [1/2] * 2, 2),
(2, [3/4, 1/4], 2),
(10, [1/3] * 3, 10)
]:
n_classes = len(weights)
n_clusters = n_classes * n_clusters_per_class
n_samples = n_clusters * 50
for hypercube in (False, True):
X, y = make(n_samples=n_samples, n_classes=n_classes,
weights=weights, n_features=n_informative,
n_informative=n_informative,
n_clusters_per_class=n_clusters_per_class,
hypercube=hypercube, random_state=0)
assert_equal(X.shape, (n_samples, n_informative))
assert_equal(y.shape, (n_samples,))
# Cluster by sign, viewed as strings to allow uniquing
signs = np.sign(X)
signs = signs.view(dtype='|S{0}'.format(signs.strides[0]))
unique_signs, cluster_index = np.unique(signs,
return_inverse=True)
assert_equal(len(unique_signs), n_clusters,
"Wrong number of clusters, or not in distinct "
"quadrants")
clusters_by_class = defaultdict(set)
for cluster, cls in zip(cluster_index, y):
clusters_by_class[cls].add(cluster)
for clusters in clusters_by_class.values():
assert_equal(len(clusters), n_clusters_per_class,
"Wrong number of clusters per class")
assert_equal(len(clusters_by_class), n_classes,
"Wrong number of classes")
assert_array_almost_equal(np.bincount(y) / len(y) // weights,
[1] * n_classes,
err_msg="Wrong number of samples "
"per class")
# Ensure on vertices of hypercube
for cluster in range(len(unique_signs)):
centroid = X[cluster_index == cluster].mean(axis=0)
if hypercube:
assert_array_almost_equal(np.abs(centroid),
[class_sep] * n_informative,
decimal=0,
err_msg="Clusters are not "
"centered on hypercube "
"vertices")
else:
assert_raises(AssertionError,
assert_array_almost_equal,
np.abs(centroid),
[class_sep] * n_informative,
decimal=0,
err_msg="Clusters should not be cenetered "
"on hypercube vertices")
assert_raises(ValueError, make, n_features=2, n_informative=2, n_classes=5,
n_clusters_per_class=1)
assert_raises(ValueError, make, n_features=2, n_informative=2, n_classes=3,
n_clusters_per_class=2)
def test_make_multilabel_classification_return_sequences():
for allow_unlabeled, min_length in zip((True, False), (0, 1)):
X, Y = make_multilabel_classification(n_samples=100, n_features=20,
n_classes=3, random_state=0,
return_indicator=False,
allow_unlabeled=allow_unlabeled)
assert_equal(X.shape, (100, 20), "X shape mismatch")
if not allow_unlabeled:
assert_equal(max([max(y) for y in Y]), 2)
assert_equal(min([len(y) for y in Y]), min_length)
assert_true(max([len(y) for y in Y]) <= 3)
def test_make_multilabel_classification_return_indicator():
for allow_unlabeled, min_length in zip((True, False), (0, 1)):
X, Y = make_multilabel_classification(n_samples=25, n_features=20,
n_classes=3, random_state=0,
allow_unlabeled=allow_unlabeled)
assert_equal(X.shape, (25, 20), "X shape mismatch")
assert_equal(Y.shape, (25, 3), "Y shape mismatch")
assert_true(np.all(np.sum(Y, axis=0) > min_length))
# Also test return_distributions and return_indicator with True
X2, Y2, p_c, p_w_c = make_multilabel_classification(
n_samples=25, n_features=20, n_classes=3, random_state=0,
allow_unlabeled=allow_unlabeled, return_distributions=True)
assert_array_equal(X, X2)
assert_array_equal(Y, Y2)
assert_equal(p_c.shape, (3,))
assert_almost_equal(p_c.sum(), 1)
assert_equal(p_w_c.shape, (20, 3))
assert_almost_equal(p_w_c.sum(axis=0), [1] * 3)
def test_make_multilabel_classification_return_indicator_sparse():
for allow_unlabeled, min_length in zip((True, False), (0, 1)):
X, Y = make_multilabel_classification(n_samples=25, n_features=20,
n_classes=3, random_state=0,
return_indicator='sparse',
allow_unlabeled=allow_unlabeled)
assert_equal(X.shape, (25, 20), "X shape mismatch")
assert_equal(Y.shape, (25, 3), "Y shape mismatch")
assert_true(sp.issparse(Y))
def test_make_hastie_10_2():
X, y = make_hastie_10_2(n_samples=100, random_state=0)
assert_equal(X.shape, (100, 10), "X shape mismatch")
assert_equal(y.shape, (100,), "y shape mismatch")
assert_equal(np.unique(y).shape, (2,), "Unexpected number of classes")
def test_make_regression():
X, y, c = make_regression(n_samples=100, n_features=10, n_informative=3,
effective_rank=5, coef=True, bias=0.0,
noise=1.0, random_state=0)
assert_equal(X.shape, (100, 10), "X shape mismatch")
assert_equal(y.shape, (100,), "y shape mismatch")
assert_equal(c.shape, (10,), "coef shape mismatch")
assert_equal(sum(c != 0.0), 3, "Unexpected number of informative features")
# Test that y ~= np.dot(X, c) + bias + N(0, 1.0).
assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1)
# Test with small number of features.
X, y = make_regression(n_samples=100, n_features=1) # n_informative=3
assert_equal(X.shape, (100, 1))
def test_make_regression_multitarget():
X, y, c = make_regression(n_samples=100, n_features=10, n_informative=3,
n_targets=3, coef=True, noise=1., random_state=0)
assert_equal(X.shape, (100, 10), "X shape mismatch")
assert_equal(y.shape, (100, 3), "y shape mismatch")
assert_equal(c.shape, (10, 3), "coef shape mismatch")
assert_array_equal(sum(c != 0.0), 3,
"Unexpected number of informative features")
# Test that y ~= np.dot(X, c) + bias + N(0, 1.0)
assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1)
def test_make_blobs():
cluster_stds = np.array([0.05, 0.2, 0.4])
cluster_centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]])
X, y = make_blobs(random_state=0, n_samples=50, n_features=2,
centers=cluster_centers, cluster_std=cluster_stds)
assert_equal(X.shape, (50, 2), "X shape mismatch")
assert_equal(y.shape, (50,), "y shape mismatch")
assert_equal(np.unique(y).shape, (3,), "Unexpected number of blobs")
for i, (ctr, std) in enumerate(zip(cluster_centers, cluster_stds)):
assert_almost_equal((X[y == i] - ctr).std(), std, 1, "Unexpected std")
def test_make_friedman1():
X, y = make_friedman1(n_samples=5, n_features=10, noise=0.0,
random_state=0)
assert_equal(X.shape, (5, 10), "X shape mismatch")
assert_equal(y.shape, (5,), "y shape mismatch")
assert_array_almost_equal(y,
10 * np.sin(np.pi * X[:, 0] * X[:, 1])
+ 20 * (X[:, 2] - 0.5) ** 2
+ 10 * X[:, 3] + 5 * X[:, 4])
def test_make_friedman2():
X, y = make_friedman2(n_samples=5, noise=0.0, random_state=0)
assert_equal(X.shape, (5, 4), "X shape mismatch")
assert_equal(y.shape, (5,), "y shape mismatch")
assert_array_almost_equal(y,
(X[:, 0] ** 2
+ (X[:, 1] * X[:, 2] - 1
/ (X[:, 1] * X[:, 3])) ** 2) ** 0.5)
def test_make_friedman3():
X, y = make_friedman3(n_samples=5, noise=0.0, random_state=0)
assert_equal(X.shape, (5, 4), "X shape mismatch")
assert_equal(y.shape, (5,), "y shape mismatch")
assert_array_almost_equal(y, np.arctan((X[:, 1] * X[:, 2]
- 1 / (X[:, 1] * X[:, 3]))
/ X[:, 0]))
def test_make_low_rank_matrix():
X = make_low_rank_matrix(n_samples=50, n_features=25, effective_rank=5,
tail_strength=0.01, random_state=0)
assert_equal(X.shape, (50, 25), "X shape mismatch")
from numpy.linalg import svd
u, s, v = svd(X)
assert_less(sum(s) - 5, 0.1, "X rank is not approximately 5")
def test_make_sparse_coded_signal():
Y, D, X = make_sparse_coded_signal(n_samples=5, n_components=8,
n_features=10, n_nonzero_coefs=3,
random_state=0)
assert_equal(Y.shape, (10, 5), "Y shape mismatch")
assert_equal(D.shape, (10, 8), "D shape mismatch")
assert_equal(X.shape, (8, 5), "X shape mismatch")
for col in X.T:
assert_equal(len(np.flatnonzero(col)), 3, 'Non-zero coefs mismatch')
assert_array_almost_equal(np.dot(D, X), Y)
assert_array_almost_equal(np.sqrt((D ** 2).sum(axis=0)),
np.ones(D.shape[1]))
def test_make_sparse_uncorrelated():
X, y = make_sparse_uncorrelated(n_samples=5, n_features=10, random_state=0)
assert_equal(X.shape, (5, 10), "X shape mismatch")
assert_equal(y.shape, (5,), "y shape mismatch")
def test_make_spd_matrix():
X = make_spd_matrix(n_dim=5, random_state=0)
assert_equal(X.shape, (5, 5), "X shape mismatch")
assert_array_almost_equal(X, X.T)
from numpy.linalg import eig
eigenvalues, _ = eig(X)
assert_array_equal(eigenvalues > 0, np.array([True] * 5),
"X is not positive-definite")
def test_make_swiss_roll():
X, t = make_swiss_roll(n_samples=5, noise=0.0, random_state=0)
assert_equal(X.shape, (5, 3), "X shape mismatch")
assert_equal(t.shape, (5,), "t shape mismatch")
assert_array_almost_equal(X[:, 0], t * np.cos(t))
assert_array_almost_equal(X[:, 2], t * np.sin(t))
def test_make_s_curve():
X, t = make_s_curve(n_samples=5, noise=0.0, random_state=0)
assert_equal(X.shape, (5, 3), "X shape mismatch")
assert_equal(t.shape, (5,), "t shape mismatch")
assert_array_almost_equal(X[:, 0], np.sin(t))
assert_array_almost_equal(X[:, 2], np.sign(t) * (np.cos(t) - 1))
def test_make_biclusters():
X, rows, cols = make_biclusters(
shape=(100, 100), n_clusters=4, shuffle=True, random_state=0)
assert_equal(X.shape, (100, 100), "X shape mismatch")
assert_equal(rows.shape, (4, 100), "rows shape mismatch")
assert_equal(cols.shape, (4, 100,), "columns shape mismatch")
assert_all_finite(X)
assert_all_finite(rows)
assert_all_finite(cols)
X2, _, _ = make_biclusters(shape=(100, 100), n_clusters=4,
shuffle=True, random_state=0)
assert_array_almost_equal(X, X2)
def test_make_checkerboard():
X, rows, cols = make_checkerboard(
shape=(100, 100), n_clusters=(20, 5),
shuffle=True, random_state=0)
assert_equal(X.shape, (100, 100), "X shape mismatch")
assert_equal(rows.shape, (100, 100), "rows shape mismatch")
assert_equal(cols.shape, (100, 100,), "columns shape mismatch")
X, rows, cols = make_checkerboard(
shape=(100, 100), n_clusters=2, shuffle=True, random_state=0)
assert_all_finite(X)
assert_all_finite(rows)
assert_all_finite(cols)
X1, _, _ = make_checkerboard(shape=(100, 100), n_clusters=2,
shuffle=True, random_state=0)
X2, _, _ = make_checkerboard(shape=(100, 100), n_clusters=2,
shuffle=True, random_state=0)
assert_array_equal(X1, X2)
| bsd-3-clause |
leedm777/ansible | lib/ansible/utils/module_docs_fragments/validate.py | 366 | 1146 | # Copyright (c) 2015 Ansible, Inc
#
# 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 Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
class ModuleDocFragment(object):
# Standard documentation fragment
DOCUMENTATION = '''
options:
validate:
required: false
description:
- The validation command to run before copying into place. The path to the file to
validate is passed in via '%s' which must be present as in the example below.
The command is passed securely so shell features like expansion and pipes won't work.
default: None
'''
| gpl-3.0 |
campbe13/openhatch | vendor/packages/twisted/twisted/test/stdio_test_halfclose.py | 19 | 1894 | # -*- test-case-name: twisted.test.test_stdio.StandardInputOutputTestCase.test_readConnectionLost -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Main program for the child process run by
L{twisted.test.test_stdio.StandardInputOutputTestCase.test_readConnectionLost}
to test that IHalfCloseableProtocol.readConnectionLost works for process
transports.
"""
import sys
from zope.interface import implements
from twisted.internet.interfaces import IHalfCloseableProtocol
from twisted.internet import stdio, protocol
from twisted.python import reflect, log
class HalfCloseProtocol(protocol.Protocol):
"""
A protocol to hook up to stdio and observe its transport being
half-closed. If all goes as expected, C{exitCode} will be set to C{0};
otherwise it will be set to C{1} to indicate failure.
"""
implements(IHalfCloseableProtocol)
exitCode = None
def connectionMade(self):
"""
Signal the parent process that we're ready.
"""
self.transport.write("x")
def readConnectionLost(self):
"""
This is the desired event. Once it has happened, stop the reactor so
the process will exit.
"""
self.exitCode = 0
reactor.stop()
def connectionLost(self, reason):
"""
This may only be invoked after C{readConnectionLost}. If it happens
otherwise, mark it as an error and shut down.
"""
if self.exitCode is None:
self.exitCode = 1
log.err(reason, "Unexpected call to connectionLost")
reactor.stop()
if __name__ == '__main__':
reflect.namedAny(sys.argv[1]).install()
log.startLogging(file(sys.argv[2], 'w'))
from twisted.internet import reactor
protocol = HalfCloseProtocol()
stdio.StandardIO(protocol)
reactor.run()
sys.exit(protocol.exitCode)
| agpl-3.0 |
thewangcj/MyFlasky | config.py | 1 | 1760 | # 存储配置
import os
basedir = os.path.abspath(os.path.dirname(__file__)) # 获取当前文件所在绝对路径
# 通用配置
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.163.com'
MAIL_PORT = 25
MAIL_USE_TLS = True
MAIL_USERNAME = 15243686281
MAIL_PASSWORD = 'wcj1996827'
FLASKY_MAIL_SUBJECT_PREFIX = '[Flasky]' # 邮件前缀配置
FLASKY_MAIL_SENDER = '15243686281@163.com'
FLASKY_ADMIN = os.environ.get('FLASKY_ADMIN') or '15243686281@163.com' # 管理员邮件地址,用于判断是否是管理员
FLASKY_MODERATOR = 'moderator@qq.com'
FLASKY_POSTS_PER_PAGE = 15 # 每一页显示的文章数量
FLASKY_FOLLOWERS_PER_PAGE = 10 # 每一页显示的关注者数量
FLASKY_COMMENTS_PER_PAGE = 10 # 枚一页显示的评论
@staticmethod
# 执行对当前环境的初始化
def init_app(app):
pass
# 定义不同的开发环境
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
# 注册不同的开发环境
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig # 默认开发环境
}
| mit |
googleapis/googleapis-gen | google/cloud/gaming/v1/gaming-v1-py/google/cloud/gaming_v1/services/game_server_deployments_service/transports/grpc.py | 1 | 23880 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import warnings
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import operations_v1 # type: ignore
from google.api_core import gapic_v1 # type: ignore
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
from google.cloud.gaming_v1.types import game_server_deployments
from google.longrunning import operations_pb2 # type: ignore
from .base import GameServerDeploymentsServiceTransport, DEFAULT_CLIENT_INFO
class GameServerDeploymentsServiceGrpcTransport(GameServerDeploymentsServiceTransport):
"""gRPC backend transport for GameServerDeploymentsService.
The game server deployment is used to control the deployment
of Agones fleets.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends protocol buffers over the wire using gRPC (which is built on
top of HTTP/2); the ``grpcio`` package must be installed.
"""
_stubs: Dict[str, Callable]
def __init__(self, *,
host: str = 'gameservices.googleapis.com',
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or applicatin default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
A callback to provide client certificate bytes and private key bytes,
both in PEM format. It is used to configure mutual TLS channel. It is
ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
self._operations_client = None
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
# Ignore credentials if a channel was passed.
credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
else:
if api_mtls_endpoint:
host = api_mtls_endpoint
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
self._ssl_channel_credentials = SslCredentials().ssl_credentials
else:
if client_cert_source_for_mtls and not ssl_channel_credentials:
cert, key = client_cert_source_for_mtls()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
# The base transport sets the host, credentials and scopes
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
)
if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
self._host,
credentials=self._credentials,
credentials_file=credentials_file,
scopes=self._scopes,
ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
# Wrap messages. This must be done after self._grpc_channel exists
self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(cls,
host: str = 'gameservices.googleapis.com',
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
Raises:
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
default_scopes=cls.AUTH_SCOPES,
scopes=scopes,
default_host=cls.DEFAULT_HOST,
**kwargs
)
@property
def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service.
"""
return self._grpc_channel
@property
def operations_client(self) -> operations_v1.OperationsClient:
"""Create the client designed to process long-running operations.
This property caches on the instance; repeated calls return the same
client.
"""
# Sanity check: Only create a new client if we do not already have one.
if self._operations_client is None:
self._operations_client = operations_v1.OperationsClient(
self.grpc_channel
)
# Return the client from cache.
return self._operations_client
@property
def list_game_server_deployments(self) -> Callable[
[game_server_deployments.ListGameServerDeploymentsRequest],
game_server_deployments.ListGameServerDeploymentsResponse]:
r"""Return a callable for the list game server deployments method over gRPC.
Lists game server deployments in a given project and
location.
Returns:
Callable[[~.ListGameServerDeploymentsRequest],
~.ListGameServerDeploymentsResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'list_game_server_deployments' not in self._stubs:
self._stubs['list_game_server_deployments'] = self.grpc_channel.unary_unary(
'/google.cloud.gaming.v1.GameServerDeploymentsService/ListGameServerDeployments',
request_serializer=game_server_deployments.ListGameServerDeploymentsRequest.serialize,
response_deserializer=game_server_deployments.ListGameServerDeploymentsResponse.deserialize,
)
return self._stubs['list_game_server_deployments']
@property
def get_game_server_deployment(self) -> Callable[
[game_server_deployments.GetGameServerDeploymentRequest],
game_server_deployments.GameServerDeployment]:
r"""Return a callable for the get game server deployment method over gRPC.
Gets details of a single game server deployment.
Returns:
Callable[[~.GetGameServerDeploymentRequest],
~.GameServerDeployment]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'get_game_server_deployment' not in self._stubs:
self._stubs['get_game_server_deployment'] = self.grpc_channel.unary_unary(
'/google.cloud.gaming.v1.GameServerDeploymentsService/GetGameServerDeployment',
request_serializer=game_server_deployments.GetGameServerDeploymentRequest.serialize,
response_deserializer=game_server_deployments.GameServerDeployment.deserialize,
)
return self._stubs['get_game_server_deployment']
@property
def create_game_server_deployment(self) -> Callable[
[game_server_deployments.CreateGameServerDeploymentRequest],
operations_pb2.Operation]:
r"""Return a callable for the create game server deployment method over gRPC.
Creates a new game server deployment in a given
project and location.
Returns:
Callable[[~.CreateGameServerDeploymentRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'create_game_server_deployment' not in self._stubs:
self._stubs['create_game_server_deployment'] = self.grpc_channel.unary_unary(
'/google.cloud.gaming.v1.GameServerDeploymentsService/CreateGameServerDeployment',
request_serializer=game_server_deployments.CreateGameServerDeploymentRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs['create_game_server_deployment']
@property
def delete_game_server_deployment(self) -> Callable[
[game_server_deployments.DeleteGameServerDeploymentRequest],
operations_pb2.Operation]:
r"""Return a callable for the delete game server deployment method over gRPC.
Deletes a single game server deployment.
Returns:
Callable[[~.DeleteGameServerDeploymentRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'delete_game_server_deployment' not in self._stubs:
self._stubs['delete_game_server_deployment'] = self.grpc_channel.unary_unary(
'/google.cloud.gaming.v1.GameServerDeploymentsService/DeleteGameServerDeployment',
request_serializer=game_server_deployments.DeleteGameServerDeploymentRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs['delete_game_server_deployment']
@property
def update_game_server_deployment(self) -> Callable[
[game_server_deployments.UpdateGameServerDeploymentRequest],
operations_pb2.Operation]:
r"""Return a callable for the update game server deployment method over gRPC.
Patches a game server deployment.
Returns:
Callable[[~.UpdateGameServerDeploymentRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'update_game_server_deployment' not in self._stubs:
self._stubs['update_game_server_deployment'] = self.grpc_channel.unary_unary(
'/google.cloud.gaming.v1.GameServerDeploymentsService/UpdateGameServerDeployment',
request_serializer=game_server_deployments.UpdateGameServerDeploymentRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs['update_game_server_deployment']
@property
def get_game_server_deployment_rollout(self) -> Callable[
[game_server_deployments.GetGameServerDeploymentRolloutRequest],
game_server_deployments.GameServerDeploymentRollout]:
r"""Return a callable for the get game server deployment
rollout method over gRPC.
Gets details a single game server deployment rollout.
Returns:
Callable[[~.GetGameServerDeploymentRolloutRequest],
~.GameServerDeploymentRollout]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'get_game_server_deployment_rollout' not in self._stubs:
self._stubs['get_game_server_deployment_rollout'] = self.grpc_channel.unary_unary(
'/google.cloud.gaming.v1.GameServerDeploymentsService/GetGameServerDeploymentRollout',
request_serializer=game_server_deployments.GetGameServerDeploymentRolloutRequest.serialize,
response_deserializer=game_server_deployments.GameServerDeploymentRollout.deserialize,
)
return self._stubs['get_game_server_deployment_rollout']
@property
def update_game_server_deployment_rollout(self) -> Callable[
[game_server_deployments.UpdateGameServerDeploymentRolloutRequest],
operations_pb2.Operation]:
r"""Return a callable for the update game server deployment
rollout method over gRPC.
Patches a single game server deployment rollout. The method will
not return an error if the update does not affect any existing
realms. For example - if the default_game_server_config is
changed but all existing realms use the override, that is valid.
Similarly, if a non existing realm is explicitly called out in
game_server_config_overrides field, that will also not result in
an error.
Returns:
Callable[[~.UpdateGameServerDeploymentRolloutRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'update_game_server_deployment_rollout' not in self._stubs:
self._stubs['update_game_server_deployment_rollout'] = self.grpc_channel.unary_unary(
'/google.cloud.gaming.v1.GameServerDeploymentsService/UpdateGameServerDeploymentRollout',
request_serializer=game_server_deployments.UpdateGameServerDeploymentRolloutRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs['update_game_server_deployment_rollout']
@property
def preview_game_server_deployment_rollout(self) -> Callable[
[game_server_deployments.PreviewGameServerDeploymentRolloutRequest],
game_server_deployments.PreviewGameServerDeploymentRolloutResponse]:
r"""Return a callable for the preview game server deployment
rollout method over gRPC.
Previews the game server deployment rollout. This API
does not mutate the rollout resource.
Returns:
Callable[[~.PreviewGameServerDeploymentRolloutRequest],
~.PreviewGameServerDeploymentRolloutResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'preview_game_server_deployment_rollout' not in self._stubs:
self._stubs['preview_game_server_deployment_rollout'] = self.grpc_channel.unary_unary(
'/google.cloud.gaming.v1.GameServerDeploymentsService/PreviewGameServerDeploymentRollout',
request_serializer=game_server_deployments.PreviewGameServerDeploymentRolloutRequest.serialize,
response_deserializer=game_server_deployments.PreviewGameServerDeploymentRolloutResponse.deserialize,
)
return self._stubs['preview_game_server_deployment_rollout']
@property
def fetch_deployment_state(self) -> Callable[
[game_server_deployments.FetchDeploymentStateRequest],
game_server_deployments.FetchDeploymentStateResponse]:
r"""Return a callable for the fetch deployment state method over gRPC.
Retrieves information about the current state of the
game server deployment. Gathers all the Agones fleets
and Agones autoscalers, including fleets running an
older version of the game server deployment.
Returns:
Callable[[~.FetchDeploymentStateRequest],
~.FetchDeploymentStateResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'fetch_deployment_state' not in self._stubs:
self._stubs['fetch_deployment_state'] = self.grpc_channel.unary_unary(
'/google.cloud.gaming.v1.GameServerDeploymentsService/FetchDeploymentState',
request_serializer=game_server_deployments.FetchDeploymentStateRequest.serialize,
response_deserializer=game_server_deployments.FetchDeploymentStateResponse.deserialize,
)
return self._stubs['fetch_deployment_state']
__all__ = (
'GameServerDeploymentsServiceGrpcTransport',
)
| apache-2.0 |
kevinmora94/proyectoDrupal | web/themes/custom/proyectofinal/node_modules/node-gyp/gyp/tools/graphviz.py | 2679 | 2878 | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Using the JSON dumped by the dump-dependency-json generator,
generate input suitable for graphviz to render a dependency graph of
targets."""
import collections
import json
import sys
def ParseTarget(target):
target, _, suffix = target.partition('#')
filename, _, target = target.partition(':')
return filename, target, suffix
def LoadEdges(filename, targets):
"""Load the edges map from the dump file, and filter it to only
show targets in |targets| and their depedendents."""
file = open('dump.json')
edges = json.load(file)
file.close()
# Copy out only the edges we're interested in from the full edge list.
target_edges = {}
to_visit = targets[:]
while to_visit:
src = to_visit.pop()
if src in target_edges:
continue
target_edges[src] = edges[src]
to_visit.extend(edges[src])
return target_edges
def WriteGraph(edges):
"""Print a graphviz graph to stdout.
|edges| is a map of target to a list of other targets it depends on."""
# Bucket targets by file.
files = collections.defaultdict(list)
for src, dst in edges.items():
build_file, target_name, toolset = ParseTarget(src)
files[build_file].append(src)
print 'digraph D {'
print ' fontsize=8' # Used by subgraphs.
print ' node [fontsize=8]'
# Output nodes by file. We must first write out each node within
# its file grouping before writing out any edges that may refer
# to those nodes.
for filename, targets in files.items():
if len(targets) == 1:
# If there's only one node for this file, simplify
# the display by making it a box without an internal node.
target = targets[0]
build_file, target_name, toolset = ParseTarget(target)
print ' "%s" [shape=box, label="%s\\n%s"]' % (target, filename,
target_name)
else:
# Group multiple nodes together in a subgraph.
print ' subgraph "cluster_%s" {' % filename
print ' label = "%s"' % filename
for target in targets:
build_file, target_name, toolset = ParseTarget(target)
print ' "%s" [label="%s"]' % (target, target_name)
print ' }'
# Now that we've placed all the nodes within subgraphs, output all
# the edges between nodes.
for src, dsts in edges.items():
for dst in dsts:
print ' "%s" -> "%s"' % (src, dst)
print '}'
def main():
if len(sys.argv) < 2:
print >>sys.stderr, __doc__
print >>sys.stderr
print >>sys.stderr, 'usage: %s target1 target2...' % (sys.argv[0])
return 1
edges = LoadEdges('dump.json', sys.argv[1:])
WriteGraph(edges)
return 0
if __name__ == '__main__':
sys.exit(main())
| gpl-2.0 |
bijandhakal/pattern | pattern/web/pdf/pdfdevice.py | 56 | 5319 | #!/usr/bin/env python2
import sys
from utils import mult_matrix, translate_matrix
from utils import enc, bbox2str
from pdffont import PDFUnicodeNotDefined
## PDFDevice
##
class PDFDevice(object):
debug = 0
def __init__(self, rsrcmgr):
self.rsrcmgr = rsrcmgr
self.ctm = None
return
def __repr__(self):
return '<PDFDevice>'
def close(self):
return
def set_ctm(self, ctm):
self.ctm = ctm
return
def begin_tag(self, tag, props=None):
return
def end_tag(self):
return
def do_tag(self, tag, props=None):
return
def begin_page(self, page, ctm):
return
def end_page(self, page):
return
def begin_figure(self, name, bbox, matrix):
return
def end_figure(self, name):
return
def paint_path(self, graphicstate, stroke, fill, evenodd, path):
return
def render_image(self, name, stream):
return
def render_string(self, textstate, seq):
return
## PDFTextDevice
##
class PDFTextDevice(PDFDevice):
def render_string(self, textstate, seq):
matrix = mult_matrix(textstate.matrix, self.ctm)
font = textstate.font
fontsize = textstate.fontsize
scaling = textstate.scaling * .01
charspace = textstate.charspace * scaling
wordspace = textstate.wordspace * scaling
rise = textstate.rise
if font.is_multibyte():
wordspace = 0
dxscale = .001 * fontsize * scaling
if font.is_vertical():
textstate.linematrix = self.render_string_vertical(
seq, matrix, textstate.linematrix, font, fontsize,
scaling, charspace, wordspace, rise, dxscale)
else:
textstate.linematrix = self.render_string_horizontal(
seq, matrix, textstate.linematrix, font, fontsize,
scaling, charspace, wordspace, rise, dxscale)
return
def render_string_horizontal(self, seq, matrix, (x,y),
font, fontsize, scaling, charspace, wordspace, rise, dxscale):
needcharspace = False
for obj in seq:
if isinstance(obj, int) or isinstance(obj, float):
x -= obj*dxscale
needcharspace = True
else:
for cid in font.decode(obj):
if needcharspace:
x += charspace
x += self.render_char(translate_matrix(matrix, (x,y)),
font, fontsize, scaling, rise, cid)
if cid == 32 and wordspace:
x += wordspace
needcharspace = True
return (x, y)
def render_string_vertical(self, seq, matrix, (x,y),
font, fontsize, scaling, charspace, wordspace, rise, dxscale):
needcharspace = False
for obj in seq:
if isinstance(obj, int) or isinstance(obj, float):
y -= obj*dxscale
needcharspace = True
else:
for cid in font.decode(obj):
if needcharspace:
y += charspace
y += self.render_char(translate_matrix(matrix, (x,y)),
font, fontsize, scaling, rise, cid)
if cid == 32 and wordspace:
y += wordspace
needcharspace = True
return (x, y)
def render_char(self, matrix, font, fontsize, scaling, rise, cid):
return 0
## TagExtractor
##
class TagExtractor(PDFDevice):
def __init__(self, rsrcmgr, outfp, codec='utf-8', debug=0):
PDFDevice.__init__(self, rsrcmgr)
self.outfp = outfp
self.codec = codec
self.debug = debug
self.pageno = 0
self._stack = []
return
def render_string(self, textstate, seq):
font = textstate.font
text = ''
for obj in seq:
if not isinstance(obj, str): continue
chars = font.decode(obj)
for cid in chars:
try:
char = font.to_unichr(cid)
text += char
except PDFUnicodeNotDefined:
pass
self.outfp.write(enc(text, self.codec))
return
def begin_page(self, page, ctm):
self.outfp.write('<page id="%s" bbox="%s" rotate="%d">' %
(self.pageno, bbox2str(page.mediabox), page.rotate))
return
def end_page(self, page):
self.outfp.write('</page>\n')
self.pageno += 1
return
def begin_tag(self, tag, props=None):
s = ''
if isinstance(props, dict):
s = ''.join( ' %s="%s"' % (enc(k), enc(str(v))) for (k,v)
in sorted(props.iteritems()) )
self.outfp.write('<%s%s>' % (enc(tag.name), s))
self._stack.append(tag)
return
def end_tag(self):
assert self._stack
tag = self._stack.pop(-1)
self.outfp.write('</%s>' % enc(tag.name))
return
def do_tag(self, tag, props=None):
self.begin_tag(tag, props)
self._stack.pop(-1)
return
| bsd-3-clause |
ubic135/odoo-design | addons/point_of_sale/report/pos_receipt.py | 380 | 3100 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.osv import osv
from openerp.report import report_sxw
def titlize(journal_name):
words = journal_name.split()
while words.pop() != 'journal':
continue
return ' '.join(words)
class order(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(order, self).__init__(cr, uid, name, context=context)
user = self.pool['res.users'].browse(cr, uid, uid, context=context)
partner = user.company_id.partner_id
self.localcontext.update({
'time': time,
'disc': self.discount,
'net': self.netamount,
'get_journal_amt': self._get_journal_amt,
'address': partner or False,
'titlize': titlize
})
def netamount(self, order_line_id):
sql = 'select (qty*price_unit) as net_price from pos_order_line where id = %s'
self.cr.execute(sql, (order_line_id,))
res = self.cr.fetchone()
return res[0]
def discount(self, order_id):
sql = 'select discount, price_unit, qty from pos_order_line where order_id = %s '
self.cr.execute(sql, (order_id,))
res = self.cr.fetchall()
dsum = 0
for line in res:
if line[0] != 0:
dsum = dsum +(line[2] * (line[0]*line[1]/100))
return dsum
def _get_journal_amt(self, order_id):
data={}
sql = """ select aj.name,absl.amount as amt from account_bank_statement as abs
LEFT JOIN account_bank_statement_line as absl ON abs.id = absl.statement_id
LEFT JOIN account_journal as aj ON aj.id = abs.journal_id
WHERE absl.pos_statement_id =%d"""%(order_id)
self.cr.execute(sql)
data = self.cr.dictfetchall()
return data
class report_order_receipt(osv.AbstractModel):
_name = 'report.point_of_sale.report_receipt'
_inherit = 'report.abstract_report'
_template = 'point_of_sale.report_receipt'
_wrapped_report_class = order
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
gonicus/gosa | backend/src/gosa/backend/plugins/cups/main.py | 1 | 20132 | # This file is part of the GOsa project.
#
# http://gosa-project.org
#
# Copyright:
# (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.
import functools
import hashlib
import logging
import cups
import multiprocessing
import os
import tempfile
import time
import requests
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
from zope.interface import implementer
from gosa.backend.components.httpd import get_server_url
from gosa.backend.exceptions import EntryNotFound
from gosa.backend.objects import ObjectProxy
from gosa.common.error import GosaErrorHandler as C
from gosa.common import Environment
from gosa.common.components import Plugin, Command, PluginRegistry
from gosa.common.gjson import loads
from gosa.common.handler import IInterfaceHandler
from gosa.common.utils import N_
C.register_codes(dict(
ERROR_GETTING_SERVER_PPD=N_("Server PPD file could not be retrieved: '%(type)s'"),
PPD_NOT_FOUND=N_("PPD file '%(ppd)s' not found"),
OPTION_CONFLICT=N_("Setting option '%(option)s' to '%(value)s' caused %(conflicts)s"),
OPTION_NOT_FOUND=N_("Option '%(option)s' not found in PPD"),
COULD_NOT_READ_SOURCE_PPD=N_("Could not read source PPD file"),
USER_NOT_FOUND=N_("User '%(user)s' not found"),
PPD_DIFF_TO_LARGE=N_("Cannot find new ppd file per diff, because to many new printers where found"),
PPD_ALREADY_EXISTS=N_("Cannot find new ppd file per diff, because if already exists"),
PPD_NOT_EXACTLY_ONE=N_(
"Cannot find cups ppd - there should be exactly one for the manufacturer but there are %(number_ppds)s"),
))
@implementer(IInterfaceHandler)
class CupsClient(Plugin):
_priority_ = 99
_target_ = "cups"
client = None
__printer_list = None
def __init__(self):
self.env = Environment.getInstance()
self.log = logging.getLogger(__name__)
self.lock = multiprocessing.Lock()
def serve(self):
try:
server = self.env.config.get("cups.server")
port = self.env.config.get("cups.port")
user = self.env.config.get("cups.user")
password = self.env.config.get("cups.password")
encryption_policy = getattr(cups, "HTTP_ENCRYPT_%s" % self.env.config.get("cups.encryption-policy",
default="IF_REQUESTED").upper())
if server is not None:
cups.setServer(server)
if port is not None:
cups.setPort(int(port))
if user is not None:
cups.setUser(user)
if encryption_policy is not None:
cups.setEncryption(encryption_policy)
if password is not None:
def pw_callback(prompt):
return password
cups.setPasswordCB(pw_callback)
self.client = cups.Connection()
sched = PluginRegistry.getInstance("SchedulerService").getScheduler()
sched.add_interval_job(self.__gc, minutes=60, tag='_internal', jobstore="ram")
sched.add_interval_job(self.__update_printer_list, minutes=30, tag='_internal', jobstore="ram")
except RuntimeError as e:
self.log.error(str(e))
self.client = None
def __get_printer_list(self):
if self.__printer_list is None:
self.__update_printer_list()
return self.__printer_list
def __update_printer_list(self):
res = {}
with self.lock:
for name, ppd in self.client.getPPDs().items():
if ppd["ppd-make"] not in res:
res[ppd["ppd-make"]] = []
res[ppd["ppd-make"]].append({"model": ppd["ppd-make-and-model"], "ppd": name})
self.__printer_list = res
def __gc(self):
""" garbage collection for unused temporary PPD files in spool directory """
index = PluginRegistry.getInstance("ObjectIndex")
dir = self.env.config.get("cups.spool", default="/tmp/spool")
if not os.path.exists(dir):
return
for file in os.listdir(dir):
if os.path.isfile(os.path.join(dir, file)) and file.split(".")[-1:][0].lower() == "ppd":
ppd_file = os.path.join(dir, file)
res = index.search({"_type": "GotoPrinter", "gotoPrinterPPD": ppd_file}, {"dn": 1})
if len(res) == 0 and os.path.getmtime(ppd_file) < time.time()-3600:
# no entry -> delete file if it has not been changed in the last hour
self.log.debug("deleting obsolete PPD file: %s" % ppd_file)
os.unlink(ppd_file)
@Command(__help__=N_("Write a general PPD file to the cups pool"))
def uploadPPD(self, obj, data):
directory = self.env.config.get('cups.pool', default='/usr/share/ppd')
if not os.path.exists(directory):
os.makedirs(directory)
# write temporary ppd file and read it to extract manufacturer and model name
temp_file = tempfile.NamedTemporaryFile()
with open(temp_file.name, 'w') as tf:
tf.write(data)
printer_infos = self.get_attributes_from_ppd(temp_file.name, ['Manufacturer', 'NickName', 'PCFileName'])
maker = printer_infos['Manufacturer']
directory = os.path.join(directory, maker)
if not os.path.exists(directory):
os.makedirs(directory)
new_file = os.path.join(directory, printer_infos['PCFileName'].lower())
with open(new_file, 'w') as f:
f.write(data)
model_name = ''
# find cups ppd of new printer
if maker in self.__printer_list:
# find via diff on printer list
old_printer_list = self.__printer_list[maker]
self.__update_printer_list()
printer_list = self.__printer_list[maker]
# if there are no new items, we are screwed...
if len(printer_list) == len(old_printer_list):
raise AssertionError(C.make_error('PPD_ALREADY_EXISTS'))
elif len(printer_list) > len(old_printer_list) + 1:
raise AssertionError(C.make_error('PPD_DIFF_TO_LARGE'))
old_set = set(map(lambda x: x['ppd'], old_printer_list))
new_set = set(map(lambda x: x['ppd'], printer_list))
diff = list(new_set - old_set)
found = diff[0]
# find model name
for items in printer_list:
if items['ppd'] == found:
model_name = items['model']
else:
# ppd is the only one for the manufacturer
self.__update_printer_list()
printer_list = self.__printer_list[maker]
if len(printer_list) != 1:
raise AssertionError(C.make_error('PPD_NOT_EXACTLY_ONE', number_ppds=len(printer_list)))
found = printer_list[0]['ppd']
model_name = printer_list[0]['model']
obj.repopulate_attribute_values('maker')
return {
'manufacturer': maker,
'model_name': model_name,
'file_name': found,
}
@Command(__help__=N_("Write settings to PPD file"))
def writePPD(self, printer_cn, server_ppd_file, custom_ppd_file, data):
if self.client is None:
return
server_ppd = None
dir = self.env.config.get("cups.spool", default="/tmp/spool")
if not os.path.exists(dir):
os.makedirs(dir)
try:
server_ppd = self.client.getServerPPD(server_ppd_file)
is_server_ppd = True
ppd = cups.PPD(server_ppd)
except Exception as e:
self.log.error(str(e))
is_server_ppd = False
if custom_ppd_file is not None:
ppd = cups.PPD(os.path.join(dir, custom_ppd_file))
else:
raise PPDException(C.make_error('COULD_NOT_READ_SOURCE_PPD'))
if isinstance(data, str):
data = loads(data)
# apply options
for option_name, value in data.items():
option = ppd.findOption(option_name)
if option is not None:
conflicts = ppd.markOption(option_name, value)
if conflicts > 0:
raise PPDException(C.make_error('OPTION_CONFLICT', option=option_name, value=value, conflicts=conflicts))
else:
raise PPDException(C.make_error('OPTION_NOT_FOUND', option=option_name))
# calculate hash value for new PPD
temp_file = tempfile.NamedTemporaryFile(delete=False)
try:
with open(temp_file.name, "w") as tf:
ppd.writeFd(tf.fileno())
with open(temp_file.name, "r") as tf:
result = tf.read()
hash = hashlib.md5(repr(result).encode('utf-8')).hexdigest()
index = PluginRegistry.getInstance("ObjectIndex")
new_file = os.path.join(dir, "%s.ppd" % hash)
if new_file == custom_ppd_file:
# nothing to to
return {}
if not is_server_ppd:
# check if anyone else is using a file with this hash value and delete the old file if not
query = {"_type": "GotoPrinter", "gotoPrinterPPD": "%s.ppd" % hash}
if printer_cn is not None:
query["not_"] = {"cn": printer_cn}
res = index.search(query, {"dn": 1})
if len(res) == 0:
# delete file
os.unlink(custom_ppd_file)
with open(new_file, "w") as f:
f.write(result)
return {
"gotoPrinterPPD": ["%s/ppd/modified/%s.ppd" % (get_server_url(), hash)],
"configured": [True]
}
except Exception as e:
self.log.error(str(e))
return {}
finally:
os.unlink(temp_file.name)
if server_ppd is not None:
os.unlink(server_ppd)
@Command(__help__=N_("Get a list of all available printer manufacturers"))
def getPrinterManufacturers(self, *args):
if self.client is None:
return []
return list(self.__get_printer_list().keys())
@Command(__help__=N_("Get a list of all available printer models for one manufacturer"))
def getPrinterModels(self, *args):
if self.client is None:
return {}
printers = self.__get_printer_list()
res = {}
manufacturer = None
if len(args):
if isinstance(args[0], dict):
manufacturer = args[0]["maker"]
elif isinstance(args[0], str):
manufacturer = args[0]
if manufacturer is not None:
if manufacturer in printers:
for entry in printers[manufacturer]:
res[entry["ppd"]] = {"value": entry["model"]}
return res
@Command(__help__=N_("Return all printer PPD files associated to a user"))
def getUserPPDs(self, user):
index = PluginRegistry.getInstance("ObjectIndex")
res = index.search({"_type": "User", "uid": user}, {"dn": 1})
if len(res) == 0:
raise EntryNotFound(C.make_error("USER_NOT_FOUND", topic=user))
object = ObjectProxy(res[0]["dn"])
printer_cns = []
if object.is_extended_by("GotoEnvironment"):
printer_cns.append(object.gotoPrinters)
if object.is_extended_by("PosixUser"):
for group_cn in object.groupMembership:
group = ObjectProxy(group_cn)
if group.is_extended_by("GotoEnvironment"):
printer_cns.append(group.gotoPrinters)
# collect all PPDs
res = index.search({"_type": "GotoPrinter", "cn": {"in_": printer_cns}}, {"gotoPrinterPPD": 1})
ppds = []
for r in res:
ppds.append(r["gotoPrinterPPD"])
return ppds
@Command(__help__=N_("Get a GUI template from a PPD file"))
def getConfigurePrinterTemplate(self, data):
"""
Generates a GUI template from a PPD file.
"""
if self.client is None:
return
ppd_file = None
name = None
delete = True
# extract name from data
if isinstance(data, str):
name = data
elif isinstance(data, dict):
if "gotoPrinterPPD" in data and data["gotoPrinterPPD"] is not None:
ppd_file = data["gotoPrinterPPD"]
if get_local_ppd_path(ppd_file) is not None:
ppd_file = get_local_ppd_path(ppd_file)
delete = False
else:
r = requests.get(requests.utils.quote(ppd_file, safe=":/"))
temp_file = tempfile.NamedTemporaryFile(delete=False)
with open(temp_file.name, "w") as tf:
tf.write(r.content.decode("utf-8"))
ppd_file = temp_file.name
else:
name = data["serverPPD"]
else:
name = str(data)
template = {
"type": "widget",
"class": "gosa.ui.tabview.TabView",
"addOptions": {
"flex": 1
},
"properties": {
"width": 800,
"height": 600,
"windowTitle": "tr('Configure printer')",
"dialogName": "configurePrinter",
"cancelable": True
},
"extensions": {
"validator": {
"target": "form",
"name": "Constraints",
"properties": {}
}
},
"children": []
}
try:
if ppd_file is None:
ppd_file = self.client.getServerPPD(name)
if not os.path.exists(ppd_file):
raise CupsException(C.make_error('PPD_NOT_FOUND', ppd=ppd_file))
ppd = cups.PPD(ppd_file)
ppd.localize()
model_attr = ppd.findAttr("ModelName")
if model_attr:
template["properties"]["windowTitle"] = N_("Configure printer: %s" % model_attr.value)
constraints = {}
for constraint in ppd.constraints:
if constraint.option1 not in constraints:
constraints[constraint.option1] = {}
choice1 = constraint.choice1 if constraint.choice1 is not None else "__choice__"
if choice1 not in constraints[constraint.option1]:
constraints[constraint.option1][choice1] = []
option2 = ppd.findOption(constraint.option2)
# find choice
choice_title = constraint.choice2
for choice in option2.choices:
if choice["choice"] == constraint.choice2:
choice_title = choice["text"]
constraints[constraint.option1][choice1].append({
"option": constraint.option2,
"optionTitle": option2.text,
"choice": constraint.choice2,
"choiceTitle": choice_title
})
template["extensions"]["validator"]["properties"]["constraints"] = constraints
for group in sorted(ppd.optionGroups, key=functools.cmp_to_key(self.__compare_group)):
template["children"].append(self.__read_group(group))
return template
except cups.IPPError as e:
raise CupsException(C.make_error('ERROR_GETTING_SERVER_PPD', str(e)))
finally:
if delete is True and ppd_file and os.access(ppd_file, os.F_OK):
os.unlink(ppd_file)
def __compare_group(self, group1, group2):
if group1.name == "General":
return -1
elif group2.name == "General":
return 1
elif group1.text < group2.text:
return -1
elif group1.text > group2.text:
return 1
else:
return 0
def __read_group(self, group):
row = 0
col = 0
tab = 1
template = {
"class": "qx.ui.tabview.Page",
"layout": "qx.ui.layout.Grow",
"properties": {
"label": group.text
},
"children": [{
"class": "qx.ui.container.Scroll",
"children": []
}]
}
scroll_container = {
"class": "qx.ui.container.Composite",
"layout": "qx.ui.layout.Grid",
"layoutConfig": {
"spacingX": "CONST_SPACING_X",
"spacingY": "CONST_SPACING_Y"
},
"extensions": {
"layoutOptions": {
"columnFlex": {
"column": 1,
"flex": 1
}
}
},
"children": []
}
template["children"][0]["children"].append(scroll_container)
for option in group.options:
label = {
"addOptions": {
"row": row,
"column": col
},
"properties": {
"text": option.text
},
"class": "gosa.ui.widgets.QLabelWidget"
}
scroll_container["children"].append(label)
widget = {
"widgetName": option.keyword,
"addOptions": {
"row": row,
"column": col+1
},
"properties": {
"tabIndex": tab,
"sortBy": "value",
"values": {},
"value": [option.defchoice],
"multivalue": option.ui == cups.PPD_UI_PICKMANY
},
"class": "gosa.ui.widgets.QComboBoxWidget"
}
for choice in option.choices:
widget["properties"]["values"][choice["choice"]] = {"value": choice["text"]}
scroll_container["children"].append(widget)
row += 1
tab += 1
return template
def get_attributes_from_ppd(self, ppd_file, attributes):
res = {}
temp_file = tempfile.NamedTemporaryFile(delete=False)
try:
if ppd_file[0:4] == "http":
if get_local_ppd_path(ppd_file) is not None:
# no need to make an HTTP request
local_file = get_local_ppd_path(ppd_file)
else:
# fetch remote file and copy it to a temporary local one
r = requests.get(requests.utils.quote(ppd_file, safe=":/"))
with open(temp_file.name, "w") as tf:
tf.write(r.content.decode("utf-8"))
local_file = temp_file.name
else:
local_file = ppd_file
ppd = cups.PPD(local_file)
ppd.localize()
for name in attributes:
attr = ppd.findAttr(name)
if attr is not None:
res[name] = attr.value
except Exception as e:
self.log.error("Error reading PPD file %s: %s" % (ppd_file, str(e)))
finally:
os.unlink(temp_file.name)
return res
def get_local_ppd_path(url):
server_url = get_server_url()
if url[0:len(server_url)] == server_url:
http_part = "%s/ppd/modified/" % get_server_url()
dir = Environment.getInstance().config.get("cups.spool", default="/tmp/spool")
return "%s/%s" % (dir, url[len(http_part):])
elif url[0:1] == "/":
# is already a local path
return url
return None
class CupsException(Exception):
pass
class PPDException(Exception):
pass
| lgpl-2.1 |
nordri/check_domains | lib/python2.7/site-packages/django/utils/text.py | 25 | 15103 | from __future__ import unicode_literals
import re
import unicodedata
from gzip import GzipFile
from io import BytesIO
import warnings
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding import force_text
from django.utils.functional import allow_lazy, SimpleLazyObject
from django.utils import six
from django.utils.six.moves import html_entities
from django.utils.translation import ugettext_lazy, ugettext as _, pgettext
from django.utils.safestring import mark_safe
if six.PY2:
# Import force_unicode even though this module doesn't use it, because some
# people rely on it being here.
from django.utils.encoding import force_unicode # NOQA
# Capitalizes the first letter of a string.
capfirst = lambda x: x and force_text(x)[0].upper() + force_text(x)[1:]
capfirst = allow_lazy(capfirst, six.text_type)
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))')
def wrap(text, width):
"""
A word-wrap function that preserves existing line breaks and most spaces in
the text. Expects that existing line breaks are posix newlines.
"""
text = force_text(text)
def _generator():
it = iter(text.split(' '))
word = next(it)
yield word
pos = len(word) - word.rfind('\n') - 1
for word in it:
if "\n" in word:
lines = word.split('\n')
else:
lines = (word,)
pos += len(lines[0]) + 1
if pos > width:
yield '\n'
pos = len(lines[-1])
else:
yield ' '
if len(lines) > 1:
pos = len(lines[-1])
yield word
return ''.join(_generator())
wrap = allow_lazy(wrap, six.text_type)
class Truncator(SimpleLazyObject):
"""
An object used to truncate text, either by characters or words.
"""
def __init__(self, text):
super(Truncator, self).__init__(lambda: force_text(text))
def add_truncation_text(self, text, truncate=None):
if truncate is None:
truncate = pgettext(
'String to return when truncating text',
'%(truncated_text)s...')
truncate = force_text(truncate)
if '%(truncated_text)s' in truncate:
return truncate % {'truncated_text': text}
# The truncation text didn't contain the %(truncated_text)s string
# replacement argument so just append it to the text.
if text.endswith(truncate):
# But don't append the truncation text if the current text already
# ends in this.
return text
return '%s%s' % (text, truncate)
def chars(self, num, truncate=None, html=False):
"""
Returns the text truncated to be no longer than the specified number
of characters.
Takes an optional argument of what should be used to notify that the
string has been truncated, defaulting to a translatable string of an
ellipsis (...).
"""
length = int(num)
text = unicodedata.normalize('NFC', self._wrapped)
# Calculate the length to truncate to (max length - end_text length)
truncate_len = length
for char in self.add_truncation_text('', truncate):
if not unicodedata.combining(char):
truncate_len -= 1
if truncate_len == 0:
break
if html:
return self._truncate_html(length, truncate, text, truncate_len, False)
return self._text_chars(length, truncate, text, truncate_len)
chars = allow_lazy(chars)
def _text_chars(self, length, truncate, text, truncate_len):
"""
Truncates a string after a certain number of chars.
"""
s_len = 0
end_index = None
for i, char in enumerate(text):
if unicodedata.combining(char):
# Don't consider combining characters
# as adding to the string length
continue
s_len += 1
if end_index is None and s_len > truncate_len:
end_index = i
if s_len > length:
# Return the truncated string
return self.add_truncation_text(text[:end_index or 0],
truncate)
# Return the original string since no truncation was necessary
return text
def words(self, num, truncate=None, html=False):
"""
Truncates a string after a certain number of words. Takes an optional
argument of what should be used to notify that the string has been
truncated, defaulting to ellipsis (...).
"""
length = int(num)
if html:
return self._truncate_html(length, truncate, self._wrapped, length, True)
return self._text_words(length, truncate)
words = allow_lazy(words)
def _text_words(self, length, truncate):
"""
Truncates a string after a certain number of words.
Newlines in the string will be stripped.
"""
words = self._wrapped.split()
if len(words) > length:
words = words[:length]
return self.add_truncation_text(' '.join(words), truncate)
return ' '.join(words)
def _truncate_html(self, length, truncate, text, truncate_len, words):
"""
Truncates HTML to a certain number of chars (not counting tags and
comments), or, if words is True, then to a certain number of words.
Closes opened tags if they were correctly closed in the given HTML.
Newlines in the HTML are preserved.
"""
if words and length <= 0:
return ''
html4_singlets = (
'br', 'col', 'link', 'base', 'img',
'param', 'area', 'hr', 'input'
)
# Count non-HTML chars/words and keep note of open tags
pos = 0
end_text_pos = 0
current_len = 0
open_tags = []
regex = re_words if words else re_chars
while current_len <= length:
m = regex.search(text, pos)
if not m:
# Checked through whole string
break
pos = m.end(0)
if m.group(1):
# It's an actual non-HTML word or char
current_len += 1
if current_len == truncate_len:
end_text_pos = pos
continue
# Check for tag
tag = re_tag.match(m.group(0))
if not tag or current_len >= truncate_len:
# Don't worry about non tags or tags after our truncate point
continue
closing_tag, tagname, self_closing = tag.groups()
# Element names are always case-insensitive
tagname = tagname.lower()
if self_closing or tagname in html4_singlets:
pass
elif closing_tag:
# Check for match in open tags list
try:
i = open_tags.index(tagname)
except ValueError:
pass
else:
# SGML: An end tag closes, back to the matching start tag,
# all unclosed intervening start tags with omitted end tags
open_tags = open_tags[i + 1:]
else:
# Add it to the start of the open tags list
open_tags.insert(0, tagname)
if current_len <= length:
return text
out = text[:end_text_pos]
truncate_text = self.add_truncation_text('', truncate)
if truncate_text:
out += truncate_text
# Close any tags still open
for tag in open_tags:
out += '</%s>' % tag
# Return string
return out
def get_valid_filename(s):
"""
Returns the given string converted to a string that can be used for a clean
filename. Specifically, leading and trailing spaces are removed; other
spaces are converted to underscores; and anything that is not a unicode
alphanumeric, dash, underscore, or dot, is removed.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
"""
s = force_text(s).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
get_valid_filename = allow_lazy(get_valid_filename, six.text_type)
def get_text_list(list_, last_word=ugettext_lazy('or')):
"""
>>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'
>>> get_text_list(['a', 'b', 'c'], 'and')
'a, b and c'
>>> get_text_list(['a', 'b'], 'and')
'a and b'
>>> get_text_list(['a'])
'a'
>>> get_text_list([])
''
"""
if len(list_) == 0:
return ''
if len(list_) == 1:
return force_text(list_[0])
return '%s %s %s' % (
# Translators: This string is used as a separator between list elements
_(', ').join(force_text(i) for i in list_[:-1]),
force_text(last_word), force_text(list_[-1]))
get_text_list = allow_lazy(get_text_list, six.text_type)
def normalize_newlines(text):
"""Normalizes CRLF and CR newlines to just LF."""
text = force_text(text)
return re_newlines.sub('\n', text)
normalize_newlines = allow_lazy(normalize_newlines, six.text_type)
def phone2numeric(phone):
"""Converts a phone number with letters into its numeric equivalent."""
char2number = {'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3',
'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6',
'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8',
'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9'}
return ''.join(char2number.get(c, c) for c in phone.lower())
phone2numeric = allow_lazy(phone2numeric)
# From http://www.xhaus.com/alan/python/httpcomp.html#gzip
# Used with permission.
def compress_string(s):
zbuf = BytesIO()
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
zfile.write(s)
zfile.close()
return zbuf.getvalue()
class StreamingBuffer(object):
def __init__(self):
self.vals = []
def write(self, val):
self.vals.append(val)
def read(self):
ret = b''.join(self.vals)
self.vals = []
return ret
def flush(self):
return
def close(self):
return
# Like compress_string, but for iterators of strings.
def compress_sequence(sequence):
buf = StreamingBuffer()
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=buf)
# Output headers...
yield buf.read()
for item in sequence:
zfile.write(item)
zfile.flush()
yield buf.read()
zfile.close()
yield buf.read()
ustring_re = re.compile("([\u0080-\uffff])")
def javascript_quote(s, quote_double_quotes=False):
msg = (
"django.utils.text.javascript_quote() is deprecated. "
"Use django.utils.html.escapejs() instead."
)
warnings.warn(msg, RemovedInDjango19Warning, stacklevel=2)
def fix(match):
return "\\u%04x" % ord(match.group(1))
if type(s) == bytes:
s = s.decode('utf-8')
elif type(s) != six.text_type:
raise TypeError(s)
s = s.replace('\\', '\\\\')
s = s.replace('\r', '\\r')
s = s.replace('\n', '\\n')
s = s.replace('\t', '\\t')
s = s.replace("'", "\\'")
s = s.replace('</', '<\\/')
if quote_double_quotes:
s = s.replace('"', '"')
return ustring_re.sub(fix, s)
javascript_quote = allow_lazy(javascript_quote, six.text_type)
# Expression to match some_token and some_token="with spaces" (and similarly
# for single-quoted strings).
smart_split_re = re.compile(r"""
((?:
[^\s'"]*
(?:
(?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
[^\s'"]*
)+
) | \S+)
""", re.VERBOSE)
def smart_split(text):
r"""
Generator that splits a string by spaces, leaving quoted phrases together.
Supports both single and double quotes, and supports escaping quotes with
backslashes. In the output, strings will keep their initial and trailing
quote marks and escaped quotes will remain escaped (the results can then
be further processed with unescape_string_literal()).
>>> list(smart_split(r'This is "a person\'s" test.'))
['This', 'is', '"a person\\\'s"', 'test.']
>>> list(smart_split(r"Another 'person\'s' test."))
['Another', "'person\\'s'", 'test.']
>>> list(smart_split(r'A "\"funky\" style" test.'))
['A', '"\\"funky\\" style"', 'test.']
"""
text = force_text(text)
for bit in smart_split_re.finditer(text):
yield bit.group(0)
def _replace_entity(match):
text = match.group(1)
if text[0] == '#':
text = text[1:]
try:
if text[0] in 'xX':
c = int(text[1:], 16)
else:
c = int(text)
return six.unichr(c)
except ValueError:
return match.group(0)
else:
try:
return six.unichr(html_entities.name2codepoint[text])
except (ValueError, KeyError):
return match.group(0)
_entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
def unescape_entities(text):
return _entity_re.sub(_replace_entity, text)
unescape_entities = allow_lazy(unescape_entities, six.text_type)
def unescape_string_literal(s):
r"""
Convert quoted string literals to unquoted strings with escaped quotes and
backslashes unquoted::
>>> unescape_string_literal('"abc"')
'abc'
>>> unescape_string_literal("'abc'")
'abc'
>>> unescape_string_literal('"a \"bc\""')
'a "bc"'
>>> unescape_string_literal("'\'ab\' c'")
"'ab' c"
"""
if s[0] not in "\"'" or s[-1] != s[0]:
raise ValueError("Not a string literal: %r" % s)
quote = s[0]
return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
unescape_string_literal = allow_lazy(unescape_string_literal)
def slugify(value):
"""
Converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and
trailing whitespace.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub('[^\w\s-]', '', value).strip().lower()
return mark_safe(re.sub('[-\s]+', '-', value))
slugify = allow_lazy(slugify, six.text_type)
def camel_case_to_spaces(value):
"""
Splits CamelCase and converts to lower case. Also strips leading and
trailing whitespace.
"""
return re_camel_case.sub(r' \1', value).strip().lower()
| gpl-3.0 |
hdinsight/hue | desktop/core/ext-py/pysaml2-2.4.0/src/saml2/schema/soapenv.py | 34 | 9278 | #!/usr/bin/env python
#
# Generated Fri May 27 17:26:51 2011 by parse_xsd.py version 0.4.
#
import saml2
from saml2 import SamlBase
NAMESPACE = 'http://schemas.xmlsoap.org/soap/envelope/'
class Header_(SamlBase):
"""The http://schemas.xmlsoap.org/soap/envelope/:Header element """
c_tag = 'Header'
c_namespace = NAMESPACE
c_children = SamlBase.c_children.copy()
c_attributes = SamlBase.c_attributes.copy()
c_child_order = SamlBase.c_child_order[:]
c_cardinality = SamlBase.c_cardinality.copy()
def header__from_string(xml_string):
return saml2.create_class_from_xml_string(Header_, xml_string)
class Body_(SamlBase):
"""The http://schemas.xmlsoap.org/soap/envelope/:Body element """
c_tag = 'Body'
c_namespace = NAMESPACE
c_children = SamlBase.c_children.copy()
c_attributes = SamlBase.c_attributes.copy()
c_child_order = SamlBase.c_child_order[:]
c_cardinality = SamlBase.c_cardinality.copy()
def body__from_string(xml_string):
return saml2.create_class_from_xml_string(Body_, xml_string)
class EncodingStyle_(SamlBase):
"""The http://schemas.xmlsoap.org/soap/envelope/:encodingStyle element """
c_tag = 'encodingStyle'
c_namespace = NAMESPACE
c_children = SamlBase.c_children.copy()
c_attributes = SamlBase.c_attributes.copy()
c_child_order = SamlBase.c_child_order[:]
c_cardinality = SamlBase.c_cardinality.copy()
def encoding_style__from_string(xml_string):
return saml2.create_class_from_xml_string(EncodingStyle_, xml_string)
class Fault_faultcode(SamlBase):
c_tag = 'faultcode'
c_namespace = NAMESPACE
c_value_type = {'base': 'QName'}
c_children = SamlBase.c_children.copy()
c_attributes = SamlBase.c_attributes.copy()
c_child_order = SamlBase.c_child_order[:]
c_cardinality = SamlBase.c_cardinality.copy()
def fault_faultcode_from_string(xml_string):
return saml2.create_class_from_xml_string(Fault_faultcode, xml_string)
class Fault_faultstring(SamlBase):
c_tag = 'faultstring'
c_namespace = NAMESPACE
c_value_type = {'base': 'string'}
c_children = SamlBase.c_children.copy()
c_attributes = SamlBase.c_attributes.copy()
c_child_order = SamlBase.c_child_order[:]
c_cardinality = SamlBase.c_cardinality.copy()
def fault_faultstring_from_string(xml_string):
return saml2.create_class_from_xml_string(Fault_faultstring, xml_string)
class Fault_faultactor(SamlBase):
c_tag = 'faultactor'
c_namespace = NAMESPACE
c_value_type = {'base': 'anyURI'}
c_children = SamlBase.c_children.copy()
c_attributes = SamlBase.c_attributes.copy()
c_child_order = SamlBase.c_child_order[:]
c_cardinality = SamlBase.c_cardinality.copy()
def fault_faultactor_from_string(xml_string):
return saml2.create_class_from_xml_string(Fault_faultactor, xml_string)
class Detail_(SamlBase):
"""The http://schemas.xmlsoap.org/soap/envelope/:detail element """
c_tag = 'detail'
c_namespace = NAMESPACE
c_children = SamlBase.c_children.copy()
c_attributes = SamlBase.c_attributes.copy()
c_child_order = SamlBase.c_child_order[:]
c_cardinality = SamlBase.c_cardinality.copy()
def detail__from_string(xml_string):
return saml2.create_class_from_xml_string(Detail_, xml_string)
class Envelope_(SamlBase):
"""The http://schemas.xmlsoap.org/soap/envelope/:Envelope element """
c_tag = 'Envelope'
c_namespace = NAMESPACE
c_children = SamlBase.c_children.copy()
c_attributes = SamlBase.c_attributes.copy()
c_child_order = SamlBase.c_child_order[:]
c_cardinality = SamlBase.c_cardinality.copy()
c_children['{http://schemas.xmlsoap.org/soap/envelope/}Header'] = ('header', Header_)
c_cardinality['header'] = {"min":0, "max":1}
c_children['{http://schemas.xmlsoap.org/soap/envelope/}Body'] = ('body', Body_)
c_child_order.extend(['header', 'body'])
def __init__(self,
header=None,
body=None,
text=None,
extension_elements=None,
extension_attributes=None,
):
SamlBase.__init__(self,
text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
)
self.header=header
self.body=body
def envelope__from_string(xml_string):
return saml2.create_class_from_xml_string(Envelope_, xml_string)
class Header(Header_):
"""The http://schemas.xmlsoap.org/soap/envelope/:Header element """
c_tag = 'Header'
c_namespace = NAMESPACE
c_children = Header_.c_children.copy()
c_attributes = Header_.c_attributes.copy()
c_child_order = Header_.c_child_order[:]
c_cardinality = Header_.c_cardinality.copy()
def header_from_string(xml_string):
return saml2.create_class_from_xml_string(Header, xml_string)
class Body(Body_):
"""The http://schemas.xmlsoap.org/soap/envelope/:Body element """
c_tag = 'Body'
c_namespace = NAMESPACE
c_children = Body_.c_children.copy()
c_attributes = Body_.c_attributes.copy()
c_child_order = Body_.c_child_order[:]
c_cardinality = Body_.c_cardinality.copy()
def body_from_string(xml_string):
return saml2.create_class_from_xml_string(Body, xml_string)
class Fault_detail(Detail_):
c_tag = 'detail'
c_namespace = NAMESPACE
c_children = Detail_.c_children.copy()
c_attributes = Detail_.c_attributes.copy()
c_child_order = Detail_.c_child_order[:]
c_cardinality = Detail_.c_cardinality.copy()
def fault_detail_from_string(xml_string):
return saml2.create_class_from_xml_string(Fault_detail, xml_string)
class Fault_(SamlBase):
"""The http://schemas.xmlsoap.org/soap/envelope/:Fault element """
c_tag = 'Fault'
c_namespace = NAMESPACE
c_children = SamlBase.c_children.copy()
c_attributes = SamlBase.c_attributes.copy()
c_child_order = SamlBase.c_child_order[:]
c_cardinality = SamlBase.c_cardinality.copy()
c_children['{http://schemas.xmlsoap.org/soap/envelope/}faultcode'] = ('faultcode', Fault_faultcode)
c_children['{http://schemas.xmlsoap.org/soap/envelope/}faultstring'] = ('faultstring', Fault_faultstring)
c_children['{http://schemas.xmlsoap.org/soap/envelope/}faultactor'] = ('faultactor', Fault_faultactor)
c_cardinality['faultactor'] = {"min":0, "max":1}
c_children['{http://schemas.xmlsoap.org/soap/envelope/}detail'] = ('detail', Fault_detail)
c_cardinality['detail'] = {"min":0, "max":1}
c_child_order.extend(['faultcode', 'faultstring', 'faultactor', 'detail'])
def __init__(self,
faultcode=None,
faultstring=None,
faultactor=None,
detail=None,
text=None,
extension_elements=None,
extension_attributes=None,
):
SamlBase.__init__(self,
text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
)
self.faultcode=faultcode
self.faultstring=faultstring
self.faultactor=faultactor
self.detail=detail
def fault__from_string(xml_string):
return saml2.create_class_from_xml_string(Fault_, xml_string)
class Envelope(Envelope_):
"""The http://schemas.xmlsoap.org/soap/envelope/:Envelope element """
c_tag = 'Envelope'
c_namespace = NAMESPACE
c_children = Envelope_.c_children.copy()
c_attributes = Envelope_.c_attributes.copy()
c_child_order = Envelope_.c_child_order[:]
c_cardinality = Envelope_.c_cardinality.copy()
def envelope_from_string(xml_string):
return saml2.create_class_from_xml_string(Envelope, xml_string)
class Fault(Fault_):
"""The http://schemas.xmlsoap.org/soap/envelope/:Fault element """
c_tag = 'Fault'
c_namespace = NAMESPACE
c_children = Fault_.c_children.copy()
c_attributes = Fault_.c_attributes.copy()
c_child_order = Fault_.c_child_order[:]
c_cardinality = Fault_.c_cardinality.copy()
def fault_from_string(xml_string):
return saml2.create_class_from_xml_string(Fault, xml_string)
#..................
# []
AG_encodingStyle = [
('encodingStyle', '', False),
]
ELEMENT_FROM_STRING = {
Envelope.c_tag: envelope_from_string,
Envelope_.c_tag: envelope__from_string,
Header.c_tag: header_from_string,
Header_.c_tag: header__from_string,
Body.c_tag: body_from_string,
Body_.c_tag: body__from_string,
EncodingStyle_.c_tag: encoding_style__from_string,
Fault.c_tag: fault_from_string,
Fault_.c_tag: fault__from_string,
Detail_.c_tag: detail__from_string,
Fault_faultcode.c_tag: fault_faultcode_from_string,
Fault_faultstring.c_tag: fault_faultstring_from_string,
Fault_faultactor.c_tag: fault_faultactor_from_string,
}
ELEMENT_BY_TAG = {
'Envelope': Envelope,
'Envelope': Envelope_,
'Header': Header,
'Header': Header_,
'Body': Body,
'Body': Body_,
'encodingStyle': EncodingStyle_,
'Fault': Fault,
'Fault': Fault_,
'detail': Detail_,
'faultcode': Fault_faultcode,
'faultstring': Fault_faultstring,
'faultactor': Fault_faultactor,
}
def factory(tag, **kwargs):
return ELEMENT_BY_TAG[tag](**kwargs)
| apache-2.0 |
marratj/ansible | lib/ansible/modules/cloud/atomic/atomic_image.py | 85 | 5230 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: atomic_image
short_description: Manage the container images on the atomic host platform
description:
- Manage the container images on the atomic host platform.
- Allows to execute the commands specified by the RUN label in the container image when present.
version_added: "2.2"
author:
- Saravanan KR (@krsacme)
notes:
- Host should support C(atomic) command.
requirements:
- atomic
- python >= 2.6
options:
backend:
description:
- Define the backend where the image is pulled.
choices: [ docker, ostree ]
version_added: "2.4"
name:
description:
- Name of the container image.
required: True
state:
description:
- The state of the container image.
- The state C(latest) will ensure container image is upgraded to the latest version and forcefully restart container, if running.
choices: [ absent, latest, present ]
default: latest
started:
description:
- Start or Stop the container.
type: bool
default: 'yes'
'''
EXAMPLES = '''
- name: Execute the run command on rsyslog container image (atomic run rhel7/rsyslog)
atomic_image:
name: rhel7/rsyslog
state: latest
- name: Pull busybox to the OSTree backend
atomic_image:
name: busybox
state: latest
backend: ostree
'''
RETURN = '''
msg:
description: The command standard output
returned: always
type: string
sample: [u'Using default tag: latest ...']
'''
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
def do_upgrade(module, image):
args = ['atomic', 'update', '--force', image]
rc, out, err = module.run_command(args, check_rc=False)
if rc != 0: # something went wrong emit the msg
module.fail_json(rc=rc, msg=err)
elif 'Image is up to date' in out:
return False
return True
def core(module):
image = module.params['name']
state = module.params['state']
started = module.params['started']
backend = module.params['backend']
is_upgraded = False
module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C')
out = {}
err = {}
rc = 0
if backend:
if state == 'present' or state == 'latest':
args = ['atomic', 'pull', "--storage=%s" % backend, image]
rc, out, err = module.run_command(args, check_rc=False)
if rc < 0:
module.fail_json(rc=rc, msg=err)
else:
out_run = ""
if started:
args = ['atomic', 'run', "--storage=%s" % backend, image]
rc, out_run, err = module.run_command(args, check_rc=False)
if rc < 0:
module.fail_json(rc=rc, msg=err)
changed = "Extracting" in out or "Copying blob" in out
module.exit_json(msg=(out + out_run), changed=changed)
elif state == 'absent':
args = ['atomic', 'images', 'delete', "--storage=%s" % backend, image]
if rc < 0:
module.fail_json(rc=rc, msg=err)
else:
changed = "Unable to find" not in out
module.exit_json(msg=out, changed=changed)
return
if state == 'present' or state == 'latest':
if state == 'latest':
is_upgraded = do_upgrade(module, image)
if started:
args = ['atomic', 'run', image]
else:
args = ['atomic', 'install', image]
elif state == 'absent':
args = ['atomic', 'uninstall', image]
rc, out, err = module.run_command(args, check_rc=False)
if rc < 0:
module.fail_json(rc=rc, msg=err)
elif rc == 1 and 'already present' in err:
module.exit_json(restult=err, changed=is_upgraded)
elif started and 'Container is running' in out:
module.exit_json(result=out, changed=is_upgraded)
else:
module.exit_json(msg=out, changed=True)
def main():
module = AnsibleModule(
argument_spec=dict(
backend=dict(type='str', choices=['docker', 'ostree']),
name=dict(type='str', required=True),
state=dict(type='str', default='latest', choices=['absent', 'latest', 'present']),
started=dict(type='bool', default=True),
),
)
# Verify that the platform supports atomic command
rc, out, err = module.run_command('atomic -v', check_rc=False)
if rc != 0:
module.fail_json(msg="Error in running atomic command", err=err)
try:
core(module)
except Exception as e:
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
if __name__ == '__main__':
main()
| gpl-3.0 |
cchurch/ansible | test/units/plugins/test_plugins.py | 10 | 5397 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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 Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from units.compat import unittest
from units.compat.builtins import BUILTINS
from units.compat.mock import patch, MagicMock
from ansible.plugins.loader import PluginLoader
class TestErrors(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
@patch.object(PluginLoader, '_get_paths')
def test_print_paths(self, mock_method):
mock_method.return_value = ['/path/one', '/path/two', '/path/three']
pl = PluginLoader('foo', 'foo', '', 'test_plugins')
paths = pl.print_paths()
expected_paths = os.pathsep.join(['/path/one', '/path/two', '/path/three'])
self.assertEqual(paths, expected_paths)
def test_plugins__get_package_paths_no_package(self):
pl = PluginLoader('test', '', 'test', 'test_plugin')
self.assertEqual(pl._get_package_paths(), [])
def test_plugins__get_package_paths_with_package(self):
# the _get_package_paths() call uses __import__ to load a
# python library, and then uses the __file__ attribute of
# the result for that to get the library path, so we mock
# that here and patch the builtin to use our mocked result
foo = MagicMock()
bar = MagicMock()
bam = MagicMock()
bam.__file__ = '/path/to/my/foo/bar/bam/__init__.py'
bar.bam = bam
foo.return_value.bar = bar
pl = PluginLoader('test', 'foo.bar.bam', 'test', 'test_plugin')
with patch('{0}.__import__'.format(BUILTINS), foo):
self.assertEqual(pl._get_package_paths(), ['/path/to/my/foo/bar/bam'])
def test_plugins__get_paths(self):
pl = PluginLoader('test', '', 'test', 'test_plugin')
pl._paths = ['/path/one', '/path/two']
self.assertEqual(pl._get_paths(), ['/path/one', '/path/two'])
# NOT YET WORKING
# def fake_glob(path):
# if path == 'test/*':
# return ['test/foo', 'test/bar', 'test/bam']
# elif path == 'test/*/*'
# m._paths = None
# mock_glob = MagicMock()
# mock_glob.return_value = []
# with patch('glob.glob', mock_glob):
# pass
def assertPluginLoaderConfigBecomes(self, arg, expected):
pl = PluginLoader('test', '', arg, 'test_plugin')
self.assertEqual(pl.config, expected)
def test_plugin__init_config_list(self):
config = ['/one', '/two']
self.assertPluginLoaderConfigBecomes(config, config)
def test_plugin__init_config_str(self):
self.assertPluginLoaderConfigBecomes('test', ['test'])
def test_plugin__init_config_none(self):
self.assertPluginLoaderConfigBecomes(None, [])
def test__load_module_source_no_duplicate_names(self):
'''
This test simulates importing 2 plugins with the same name,
and validating that the import is short circuited if a file with the same name
has already been imported
'''
fixture_path = os.path.join(os.path.dirname(__file__), 'loader_fixtures')
pl = PluginLoader('test', '', 'test', 'test_plugin')
one = pl._load_module_source('import_fixture', os.path.join(fixture_path, 'import_fixture.py'))
# This line wouldn't even succeed if we didn't short circuit on finding a duplicate name
two = pl._load_module_source('import_fixture', '/path/to/import_fixture.py')
self.assertEqual(one, two)
@patch('ansible.plugins.loader.glob')
@patch.object(PluginLoader, '_get_paths')
def test_all_no_duplicate_names(self, gp_mock, glob_mock):
'''
This test goes along with ``test__load_module_source_no_duplicate_names``
and ensures that we ignore duplicate imports on multiple paths
'''
fixture_path = os.path.join(os.path.dirname(__file__), 'loader_fixtures')
gp_mock.return_value = [
fixture_path,
'/path/to'
]
glob_mock.glob.side_effect = [
[os.path.join(fixture_path, 'import_fixture.py')],
['/path/to/import_fixture.py']
]
pl = PluginLoader('test', '', 'test', 'test_plugin')
# Aside from needing ``list()`` so we can do a len, ``PluginLoader.all`` returns a generator
# so ``list()`` actually causes ``PluginLoader.all`` to run.
plugins = list(pl.all())
self.assertEqual(len(plugins), 1)
self.assertIn(os.path.join(fixture_path, 'import_fixture.py'), pl._module_cache)
self.assertNotIn('/path/to/import_fixture.py', pl._module_cache)
| gpl-3.0 |
2014c2g4/c2g4 | w2/static/Brython2.0.0-20140209-164925/Lib/unittest/test/test_skipping.py | 744 | 5173 | import unittest
from .support import LoggingResult
class Test_TestSkipping(unittest.TestCase):
def test_skipping(self):
class Foo(unittest.TestCase):
def test_skip_me(self):
self.skipTest("skip")
events = []
result = LoggingResult(events)
test = Foo("test_skip_me")
test.run(result)
self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
self.assertEqual(result.skipped, [(test, "skip")])
# Try letting setUp skip the test now.
class Foo(unittest.TestCase):
def setUp(self):
self.skipTest("testing")
def test_nothing(self): pass
events = []
result = LoggingResult(events)
test = Foo("test_nothing")
test.run(result)
self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
self.assertEqual(result.skipped, [(test, "testing")])
self.assertEqual(result.testsRun, 1)
def test_skipping_decorators(self):
op_table = ((unittest.skipUnless, False, True),
(unittest.skipIf, True, False))
for deco, do_skip, dont_skip in op_table:
class Foo(unittest.TestCase):
@deco(do_skip, "testing")
def test_skip(self): pass
@deco(dont_skip, "testing")
def test_dont_skip(self): pass
test_do_skip = Foo("test_skip")
test_dont_skip = Foo("test_dont_skip")
suite = unittest.TestSuite([test_do_skip, test_dont_skip])
events = []
result = LoggingResult(events)
suite.run(result)
self.assertEqual(len(result.skipped), 1)
expected = ['startTest', 'addSkip', 'stopTest',
'startTest', 'addSuccess', 'stopTest']
self.assertEqual(events, expected)
self.assertEqual(result.testsRun, 2)
self.assertEqual(result.skipped, [(test_do_skip, "testing")])
self.assertTrue(result.wasSuccessful())
def test_skip_class(self):
@unittest.skip("testing")
class Foo(unittest.TestCase):
def test_1(self):
record.append(1)
record = []
result = unittest.TestResult()
test = Foo("test_1")
suite = unittest.TestSuite([test])
suite.run(result)
self.assertEqual(result.skipped, [(test, "testing")])
self.assertEqual(record, [])
def test_skip_non_unittest_class(self):
@unittest.skip("testing")
class Mixin:
def test_1(self):
record.append(1)
class Foo(Mixin, unittest.TestCase):
pass
record = []
result = unittest.TestResult()
test = Foo("test_1")
suite = unittest.TestSuite([test])
suite.run(result)
self.assertEqual(result.skipped, [(test, "testing")])
self.assertEqual(record, [])
def test_expected_failure(self):
class Foo(unittest.TestCase):
@unittest.expectedFailure
def test_die(self):
self.fail("help me!")
events = []
result = LoggingResult(events)
test = Foo("test_die")
test.run(result)
self.assertEqual(events,
['startTest', 'addExpectedFailure', 'stopTest'])
self.assertEqual(result.expectedFailures[0][0], test)
self.assertTrue(result.wasSuccessful())
def test_unexpected_success(self):
class Foo(unittest.TestCase):
@unittest.expectedFailure
def test_die(self):
pass
events = []
result = LoggingResult(events)
test = Foo("test_die")
test.run(result)
self.assertEqual(events,
['startTest', 'addUnexpectedSuccess', 'stopTest'])
self.assertFalse(result.failures)
self.assertEqual(result.unexpectedSuccesses, [test])
self.assertTrue(result.wasSuccessful())
def test_skip_doesnt_run_setup(self):
class Foo(unittest.TestCase):
wasSetUp = False
wasTornDown = False
def setUp(self):
Foo.wasSetUp = True
def tornDown(self):
Foo.wasTornDown = True
@unittest.skip('testing')
def test_1(self):
pass
result = unittest.TestResult()
test = Foo("test_1")
suite = unittest.TestSuite([test])
suite.run(result)
self.assertEqual(result.skipped, [(test, "testing")])
self.assertFalse(Foo.wasSetUp)
self.assertFalse(Foo.wasTornDown)
def test_decorated_skip(self):
def decorator(func):
def inner(*a):
return func(*a)
return inner
class Foo(unittest.TestCase):
@decorator
@unittest.skip('testing')
def test_1(self):
pass
result = unittest.TestResult()
test = Foo("test_1")
suite = unittest.TestSuite([test])
suite.run(result)
self.assertEqual(result.skipped, [(test, "testing")])
| gpl-2.0 |
deandunbar/bitwave | hackathon_version/venv/lib/python2.7/site-packages/django/contrib/staticfiles/utils.py | 114 | 1976 | import os
import fnmatch
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def matches_patterns(path, patterns=None):
"""
Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``).
"""
if patterns is None:
patterns = []
for pattern in patterns:
if fnmatch.fnmatchcase(path, pattern):
return True
return False
def get_files(storage, ignore_patterns=None, location=''):
"""
Recursively walk the storage directories yielding the paths
of all files that should be copied.
"""
if ignore_patterns is None:
ignore_patterns = []
directories, files = storage.listdir(location)
for fn in files:
if matches_patterns(fn, ignore_patterns):
continue
if location:
fn = os.path.join(location, fn)
yield fn
for dir in directories:
if matches_patterns(dir, ignore_patterns):
continue
if location:
dir = os.path.join(location, dir)
for fn in get_files(storage, ignore_patterns, dir):
yield fn
def check_settings(base_url=None):
"""
Checks if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
"You're using the staticfiles app "
"without having set the required STATIC_URL setting.")
if settings.MEDIA_URL == base_url:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
(settings.MEDIA_ROOT == settings.STATIC_ROOT)):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values")
| mit |
qmagico/sampleappqm | src/django/contrib/staticfiles/management/commands/runserver.py | 80 | 1344 | from optparse import make_option
from django.conf import settings
from django.core.management.commands.runserver import BaseRunserverCommand
from django.contrib.staticfiles.handlers import StaticFilesHandler
class Command(BaseRunserverCommand):
option_list = BaseRunserverCommand.option_list + (
make_option('--nostatic', action="store_false", dest='use_static_handler', default=True,
help='Tells Django to NOT automatically serve static files at STATIC_URL.'),
make_option('--insecure', action="store_true", dest='insecure_serving', default=False,
help='Allows serving static files even if DEBUG is False.'),
)
help = "Starts a lightweight Web server for development and also serves static files."
def get_handler(self, *args, **options):
"""
Returns the static files serving handler wrapping the default handler,
if static files should be served. Otherwise just returns the default
handler.
"""
handler = super(Command, self).get_handler(*args, **options)
use_static_handler = options.get('use_static_handler', True)
insecure_serving = options.get('insecure_serving', False)
if use_static_handler and (settings.DEBUG or insecure_serving):
return StaticFilesHandler(handler)
return handler
| mit |
kayhayen/Nuitka | tests/basics/Slots.py | 1 | 1630 | # Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class W1(object):
def __init__(self):
self.__hidden = 5
class W2(object):
__slots__ = ["__hidden"]
def __init__(self):
self.__hidden = 5
class _W1(object):
def __init__(self):
self.__hidden = 5
class _W2(object):
__slots__ = ["__hidden"]
def __init__(self):
self.__hidden = 5
class a_W1(object):
def __init__(self):
self.__hidden = 5
class a_W2(object):
__slots__ = ["__hidden"]
def __init__(self):
self.__hidden = 5
class W1_(object):
def __init__(self):
self.__hidden = 5
class W2_(object):
__slots__ = ["__hidden"]
def __init__(self):
self.__hidden = 5
for w in (W1, W2, _W1, _W2, a_W1, a_W2, W1_, W2_):
try:
print(w)
print(dir(w))
a = w()
except AttributeError:
print("bug in %s" % w)
| apache-2.0 |
sandeepdsouza93/TensorFlow-15712 | tensorflow/contrib/learn/python/learn/evaluable.py | 4 | 4320 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""`Evaluable` interface."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
class Evaluable(object):
"""Interface for objects that are evaluatable by, e.g., `Experiment`.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def evaluate(
self, x=None, y=None, input_fn=None, feed_fn=None, batch_size=None,
steps=None, metrics=None, name=None):
"""Evaluates given model with provided evaluation data.
Stop conditions - we evaluate on the given input data until one of the
following:
- If `steps` is provided, and `steps` batches of size `batch_size` are
processed.
- If `input_fn` is provided, and it raises an end-of-input
exception (`OutOfRangeError` or `StopIteration`).
- If `x` is provided, and all items in `x` have been processed.
The return value is a dict containing the metrics specified in `metrics`, as
well as an entry `global_step` which contains the value of the global step
for which this evaluation was performed.
Args:
x: Matrix of shape [n_samples, n_features...] or dictionary of many matrices
containing the input samples for fitting the model. Can be iterator that returns
arrays of features or dictionary of array of features. If set, `input_fn` must
be `None`.
y: Vector or matrix [n_samples] or [n_samples, n_outputs] containing the
label values (class labels in classification, real numbers in
regression) or dictionary of multiple vectors/matrices. Can be iterator
that returns array of targets or dictionary of array of targets. If set,
`input_fn` must be `None`. Note: For classification, label values must
be integers representing the class index (i.e. values from 0 to
n_classes-1).
input_fn: Input function returning a tuple of:
features - Dictionary of string feature name to `Tensor` or `Tensor`.
labels - `Tensor` or dictionary of `Tensor` with labels.
If input_fn is set, `x`, `y`, and `batch_size` must be `None`. If
`steps` is not provided, this should raise `OutOfRangeError` or
`StopIteration` after the desired amount of data (e.g., one epoch) has
been provided. See "Stop conditions" above for specifics.
feed_fn: Function creating a feed dict every time it is called. Called
once per iteration. Must be `None` if `input_fn` is provided.
batch_size: minibatch size to use on the input, defaults to first
dimension of `x`, if specified. Must be `None` if `input_fn` is
provided.
steps: Number of steps for which to evaluate model. If `None`, evaluate
until `x` is consumed or `input_fn` raises an end-of-input exception.
See "Stop conditions" above for specifics.
metrics: Dict of metrics to run. If None, the default metric functions
are used; if {}, no metrics are used. Otherwise, `metrics` should map
friendly names for the metric to a `MetricSpec` object defining which
model outputs to evaluate against which labels with which metric
function.
Metric ops should support streaming, e.g., returning `update_op` and
`value` tensors. For example, see the options defined in
`../../../metrics/python/ops/metrics_ops.py`.
name: Name of the evaluation if user needs to run multiple evaluations on
different data sets, such as on training data vs test data.
Returns:
Returns `dict` with evaluation results.
"""
raise NotImplementedError
| apache-2.0 |
Lightmatter/django-inlineformfield | .tox/py27/lib/python2.7/site-packages/django/core/management/commands/diffsettings.py | 67 | 1647 | from optparse import make_option
from django.core.management.base import NoArgsCommand
def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"""Converts a module namespace to a Python dictionary."""
return dict((k, repr(v)) for k, v in module.__dict__.items() if not omittable(k))
class Command(NoArgsCommand):
help = """Displays differences between the current settings.py and Django's
default settings. Settings that don't appear in the defaults are
followed by "###"."""
option_list = NoArgsCommand.option_list + (
make_option('--all', action='store_true', dest='all', default=False,
help='Display all settings, regardless of their value. '
'Default values are prefixed by "###".'),
)
requires_system_checks = False
def handle_noargs(self, **options):
# Inspired by Postfix's "postconf -n".
from django.conf import settings, global_settings
# Because settings are imported lazily, we need to explicitly load them.
settings._setup()
user_settings = module_to_dict(settings._wrapped)
default_settings = module_to_dict(global_settings)
output = []
for key in sorted(user_settings):
if key not in default_settings:
output.append("%s = %s ###" % (key, user_settings[key]))
elif user_settings[key] != default_settings[key]:
output.append("%s = %s" % (key, user_settings[key]))
elif options['all']:
output.append("### %s = %s" % (key, user_settings[key]))
return '\n'.join(output)
| mit |
omakk/servo | tests/wpt/css-tests/tools/pytest/testing/test_assertinterpret.py | 171 | 6254 | "PYTEST_DONT_REWRITE"
import py
import pytest
from _pytest.assertion import util
def exvalue():
return py.std.sys.exc_info()[1]
def f():
return 2
def test_not_being_rewritten():
assert "@py_builtins" not in globals()
def test_assert():
try:
assert f() == 3
except AssertionError:
e = exvalue()
s = str(e)
assert s.startswith('assert 2 == 3\n')
def test_assert_with_explicit_message():
try:
assert f() == 3, "hello"
except AssertionError:
e = exvalue()
assert e.msg == 'hello'
def test_assert_within_finally():
excinfo = pytest.raises(ZeroDivisionError, """
try:
1/0
finally:
i = 42
""")
s = excinfo.exconly()
assert py.std.re.search("division.+by zero", s) is not None
#def g():
# A.f()
#excinfo = getexcinfo(TypeError, g)
#msg = getmsg(excinfo)
#assert msg.find("must be called with A") != -1
def test_assert_multiline_1():
try:
assert (f() ==
3)
except AssertionError:
e = exvalue()
s = str(e)
assert s.startswith('assert 2 == 3\n')
def test_assert_multiline_2():
try:
assert (f() == (4,
3)[-1])
except AssertionError:
e = exvalue()
s = str(e)
assert s.startswith('assert 2 ==')
def test_in():
try:
assert "hi" in [1, 2]
except AssertionError:
e = exvalue()
s = str(e)
assert s.startswith("assert 'hi' in")
def test_is():
try:
assert 1 is 2
except AssertionError:
e = exvalue()
s = str(e)
assert s.startswith("assert 1 is 2")
def test_attrib():
class Foo(object):
b = 1
i = Foo()
try:
assert i.b == 2
except AssertionError:
e = exvalue()
s = str(e)
assert s.startswith("assert 1 == 2")
def test_attrib_inst():
class Foo(object):
b = 1
try:
assert Foo().b == 2
except AssertionError:
e = exvalue()
s = str(e)
assert s.startswith("assert 1 == 2")
def test_len():
l = list(range(42))
try:
assert len(l) == 100
except AssertionError:
e = exvalue()
s = str(e)
assert s.startswith("assert 42 == 100")
assert "where 42 = len([" in s
def test_assert_non_string_message():
class A:
def __str__(self):
return "hello"
try:
assert 0 == 1, A()
except AssertionError:
e = exvalue()
assert e.msg == "hello"
def test_assert_keyword_arg():
def f(x=3):
return False
try:
assert f(x=5)
except AssertionError:
e = exvalue()
assert "x=5" in e.msg
def test_private_class_variable():
class X:
def __init__(self):
self.__v = 41
def m(self):
assert self.__v == 42
try:
X().m()
except AssertionError:
e = exvalue()
assert "== 42" in e.msg
# These tests should both fail, but should fail nicely...
class WeirdRepr:
def __repr__(self):
return '<WeirdRepr\nsecond line>'
def bug_test_assert_repr():
v = WeirdRepr()
try:
assert v == 1
except AssertionError:
e = exvalue()
assert e.msg.find('WeirdRepr') != -1
assert e.msg.find('second line') != -1
assert 0
def test_assert_non_string():
try:
assert 0, ['list']
except AssertionError:
e = exvalue()
assert e.msg.find("list") != -1
def test_assert_implicit_multiline():
try:
x = [1,2,3]
assert x != [1,
2, 3]
except AssertionError:
e = exvalue()
assert e.msg.find('assert [1, 2, 3] !=') != -1
def test_assert_with_brokenrepr_arg():
class BrokenRepr:
def __repr__(self): 0 / 0
e = AssertionError(BrokenRepr())
if e.msg.find("broken __repr__") == -1:
pytest.fail("broken __repr__ not handle correctly")
def test_multiple_statements_per_line():
try:
a = 1; assert a == 2
except AssertionError:
e = exvalue()
assert "assert 1 == 2" in e.msg
def test_power():
try:
assert 2**3 == 7
except AssertionError:
e = exvalue()
assert "assert (2 ** 3) == 7" in e.msg
def test_assert_customizable_reprcompare(monkeypatch):
monkeypatch.setattr(util, '_reprcompare', lambda *args: 'hello')
try:
assert 3 == 4
except AssertionError:
e = exvalue()
s = str(e)
assert "hello" in s
def test_assert_long_source_1():
try:
assert len == [
(None, ['somet text', 'more text']),
]
except AssertionError:
e = exvalue()
s = str(e)
assert 're-run' not in s
assert 'somet text' in s
def test_assert_long_source_2():
try:
assert(len == [
(None, ['somet text', 'more text']),
])
except AssertionError:
e = exvalue()
s = str(e)
assert 're-run' not in s
assert 'somet text' in s
def test_assert_raise_alias(testdir):
testdir.makepyfile("""
"PYTEST_DONT_REWRITE"
import sys
EX = AssertionError
def test_hello():
raise EX("hello"
"multi"
"line")
""")
result = testdir.runpytest()
result.stdout.fnmatch_lines([
"*def test_hello*",
"*raise EX*",
"*1 failed*",
])
def test_assert_raise_subclass():
class SomeEx(AssertionError):
def __init__(self, *args):
super(SomeEx, self).__init__()
try:
raise SomeEx("hello")
except AssertionError:
s = str(exvalue())
assert 're-run' not in s
assert 'could not determine' in s
def test_assert_raises_in_nonzero_of_object_pytest_issue10():
class A(object):
def __nonzero__(self):
raise ValueError(42)
def __lt__(self, other):
return A()
def __repr__(self):
return "<MY42 object>"
def myany(x):
return True
try:
assert not(myany(A() < 0))
except AssertionError:
e = exvalue()
s = str(e)
assert "<MY42 object> < 0" in s
| mpl-2.0 |
brockk/clintrials | clintrials/stats.py | 1 | 6647 | __author__ = 'Kristian Brock'
__contact__ = 'kristian.brock@gmail.com'
""" Classes and methods to perform general useful statistical routines. """
from collections import OrderedDict
import logging
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde, chi2, norm
from scipy.optimize import fsolve
def bootstrap(x):
""" Bootstrap sample a list.
:param x: sample observations
:type x: list
:return: bootstrap sample
:rtype: numpy.array
"""
return np.random.choice(x, size=len(x), replace=1)
def density(x, n_points=100, covariance_factor=0.25):
""" Calculate and plot approximate densoty function from a sample.
:param x: sample observations
:type x: list
:param n_points: number of points in density function to estimate
:type n_points: int
:param covariance_factor: covariance factor in scipy routine, see scipy.stats.gaussian_kde
:type covariance_factor: float
:return: None (yet)
:rtype: None
"""
d = gaussian_kde(x)
xs = np.linspace(min(x), max(x), n_points)
d.covariance_factor = lambda : covariance_factor
d._compute_covariance()
plt.plot(xs, d(xs))
plt.show()
def beta_like_normal(mu, sigma):
""" If X ~ N(mu, sigma^2), get alpha and beta s.t. Y ~ Beta(alpha, beta) has:
E[X] = E[Y] & Var[X] = Var[Y]
This is useful for quickly estimating the effective sample size of a normal prior,
using the principle that the effective sample size of Beta(a, b) is a+b.
:param mu: Mean of a normal r.v.
:type mu: float
:param sigma: Standard deviation of a normal r.v.
:type sigma: float
:return: (alpha, beta) pair of floats
:rtype: tuple
"""
alpha = (mu/sigma)**2 * (1-mu) - mu
beta = ((1-mu)/mu) * alpha
return alpha, beta
def or_test(a, b, c, d, ci_alpha=0.05):
""" Calculate odds ratio and asymptotic confidence interval for events with counts a, b, c, and d.
:param a: Number of observations with positive exposure (e.g. treated) and positive outcome (e.g cured)
:type a: int
:param b: Number of observations with positive exposure (e.g. treated) and negative outcome (e.g not cured)
:type b: int
:param c: Number of observations with negative exposure (e.g. not treated) and positive outcome (e.g cured)
:type c: int
:param d: Number of observations with negative exposure (e.g. not treated) and negative outcome (e.g not cured)
:type d: int
:param ci_alpha: significance for asymptotic confidence ionterval of odds-ratio
:type ci_alpha: float
:return: A dict object with all available statistics
:rtype: collections.OrderedDict
"""
abcd = [a, b, c, d]
to_return = OrderedDict()
to_return['ABCD'] = abcd
if np.any(np.array(abcd) < 0):
logging.error('Negative event count. Garbage!')
elif np.any(np.array(abcd) == 0):
logging.info('At least one event count was zero. Added one to all counts.')
abcd = np.array(abcd) + 1
a,b,c,d = abcd
odds_ratio = 1. * (a * d) / (c * b)
log_or_se = np.sqrt(sum(1. / np.array(abcd)))
ci_scalars = norm.ppf([ci_alpha/2, 1-ci_alpha/2])
or_ci = np.exp(np.log(odds_ratio) + ci_scalars * log_or_se)
to_return['OR'] = odds_ratio
to_return['Log(OR) SE'] = log_or_se
to_return['OR CI'] = list(or_ci)
to_return['Alpha'] = ci_alpha
return to_return
def chi_squ_test(x, y, x_positive_value=None, y_positive_value=None, ci_alpha=0.05):
""" Run a chi-squared test for association between x and y.
:param x:
:type x: list
:param y:
:type y: list
:param x_positive_value: item in x corresponding to positive event, 1 by default
:type x_positive_value: object
:param y_positive_value: item in y corresponding to positive event, 1 by default
:type y_positive_value: object
:param ci_alpha: significance for asymptotic confidence ionterval of odds-ratio
:type ci_alpha: float
:return: A dict object with all available statistics
:rtype: collections.OrderedDict
"""
sum_oe = 0.0
x_set = set(x)
y_set = set(y)
for x_case in x_set:
x_matches = [z == x_case for z in x]
for y_case in y_set:
y_matches = [z == y_case for z in y]
obs = sum(np.array(x_matches) & np.array(y_matches))
exp = 1. * sum(x_matches) * sum(y_matches) / len(x)
oe = (obs - exp)**2 / exp
sum_oe += oe
num_df = (len(x_set)-1) * (len(y_set)-1)
p = 1-chi2.cdf(sum_oe, num_df)
to_return = OrderedDict([('TestStatistic', sum_oe), ('p', p), ('Df', num_df)])
if len(x_set) == 2 and len(y_set)==2:
x = np.array(x)
y = np.array(y)
if not x_positive_value:
x_positive_value=1
if not y_positive_value:
y_positive_value=1
x_pos_val, y_pos_val = x_positive_value, y_positive_value
a, b, c, d = (sum((x == x_pos_val) & (y == y_pos_val)), sum((x == x_pos_val) & (y != y_pos_val)),
sum((x != x_pos_val) & (y == y_pos_val)), sum((x != x_pos_val) & (y != y_pos_val)))
to_return['Odds'] = or_test(a, b, c, d, ci_alpha=ci_alpha)
else:
# There's no reason why the OR logic could not be calculated for each combination pair
# in x and y, but it's more work so leave it for now.
pass
return to_return
class ProbabilityDensitySample:
def __init__(self, samp, func):
self._samp = samp
self._probs = func(samp)
self._scale = self._probs.mean()
def expectation(self, vector):
return np.mean(vector * self._probs / self._scale)
def variance(self, vector):
exp = self.expectation(vector)
exp2 = self.expectation(vector**2)
return exp2 - exp**2
def cdf(self, i, y):
""" Get the cumulative density of the parameter in position i that is less than y. """
return self.expectation(self._samp[:,i]<y)
def quantile(self, i, p, start_value=0.1):
""" Get the value of the parameter at position i for which p of the probability mass is in the left-tail. """
return fsolve(lambda z: self.cdf(i, z) - p, start_value)[0]
def cdf_vector(self, vector, y):
""" Get the cumulative density of sample vector that is less than y. """
return self.expectation(vector < y)
def quantile_vector(self, vector, p, start_value=0.1):
""" Get the value of a vector for which p of the probability mass is in the left-tail. """
return fsolve(lambda z: self.cdf_vector(vector, z) - p, start_value)[0] | gpl-3.0 |
venzen/p2pool_zen | p2pool/bitcoin/stratum.py | 191 | 3756 | import random
import sys
from twisted.internet import protocol, reactor
from twisted.python import log
from p2pool.bitcoin import data as bitcoin_data, getwork
from p2pool.util import expiring_dict, jsonrpc, pack
class StratumRPCMiningProvider(object):
def __init__(self, wb, other, transport):
self.wb = wb
self.other = other
self.transport = transport
self.username = None
self.handler_map = expiring_dict.ExpiringDict(300)
self.watch_id = self.wb.new_work_event.watch(self._send_work)
def rpc_subscribe(self, miner_version=None, session_id=None):
reactor.callLater(0, self._send_work)
return [
["mining.notify", "ae6812eb4cd7735a302a8a9dd95cf71f"], # subscription details
"", # extranonce1
self.wb.COINBASE_NONCE_LENGTH, # extranonce2_size
]
def rpc_authorize(self, username, password):
self.username = username
reactor.callLater(0, self._send_work)
def _send_work(self):
try:
x, got_response = self.wb.get_work(*self.wb.preprocess_request('' if self.username is None else self.username))
except:
log.err()
self.transport.loseConnection()
return
jobid = str(random.randrange(2**128))
self.other.svc_mining.rpc_set_difficulty(bitcoin_data.target_to_difficulty(x['share_target'])*self.wb.net.DUMB_SCRYPT_DIFF).addErrback(lambda err: None)
self.other.svc_mining.rpc_notify(
jobid, # jobid
getwork._swap4(pack.IntType(256).pack(x['previous_block'])).encode('hex'), # prevhash
x['coinb1'].encode('hex'), # coinb1
x['coinb2'].encode('hex'), # coinb2
[pack.IntType(256).pack(s).encode('hex') for s in x['merkle_link']['branch']], # merkle_branch
getwork._swap4(pack.IntType(32).pack(x['version'])).encode('hex'), # version
getwork._swap4(pack.IntType(32).pack(x['bits'].bits)).encode('hex'), # nbits
getwork._swap4(pack.IntType(32).pack(x['timestamp'])).encode('hex'), # ntime
True, # clean_jobs
).addErrback(lambda err: None)
self.handler_map[jobid] = x, got_response
def rpc_submit(self, worker_name, job_id, extranonce2, ntime, nonce):
if job_id not in self.handler_map:
print >>sys.stderr, '''Couldn't link returned work's job id with its handler. This should only happen if this process was recently restarted!'''
return False
x, got_response = self.handler_map[job_id]
coinb_nonce = extranonce2.decode('hex')
assert len(coinb_nonce) == self.wb.COINBASE_NONCE_LENGTH
new_packed_gentx = x['coinb1'] + coinb_nonce + x['coinb2']
header = dict(
version=x['version'],
previous_block=x['previous_block'],
merkle_root=bitcoin_data.check_merkle_link(bitcoin_data.hash256(new_packed_gentx), x['merkle_link']),
timestamp=pack.IntType(32).unpack(getwork._swap4(ntime.decode('hex'))),
bits=x['bits'],
nonce=pack.IntType(32).unpack(getwork._swap4(nonce.decode('hex'))),
)
return got_response(header, worker_name, coinb_nonce)
def close(self):
self.wb.new_work_event.unwatch(self.watch_id)
class StratumProtocol(jsonrpc.LineBasedPeer):
def connectionMade(self):
self.svc_mining = StratumRPCMiningProvider(self.factory.wb, self.other, self.transport)
def connectionLost(self, reason):
self.svc_mining.close()
class StratumServerFactory(protocol.ServerFactory):
protocol = StratumProtocol
def __init__(self, wb):
self.wb = wb
| gpl-3.0 |
IndraVikas/scikit-learn | sklearn/linear_model/least_angle.py | 57 | 49338 | """
Least Angle Regression algorithm. See the documentation on the
Generalized Linear Model for a complete discussion.
"""
from __future__ import print_function
# Author: Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Gael Varoquaux
#
# License: BSD 3 clause
from math import log
import sys
import warnings
from distutils.version import LooseVersion
import numpy as np
from scipy import linalg, interpolate
from scipy.linalg.lapack import get_lapack_funcs
from .base import LinearModel
from ..base import RegressorMixin
from ..utils import arrayfuncs, as_float_array, check_X_y
from ..cross_validation import check_cv
from ..utils import ConvergenceWarning
from ..externals.joblib import Parallel, delayed
from ..externals.six.moves import xrange
import scipy
solve_triangular_args = {}
if LooseVersion(scipy.__version__) >= LooseVersion('0.12'):
solve_triangular_args = {'check_finite': False}
def lars_path(X, y, Xy=None, Gram=None, max_iter=500,
alpha_min=0, method='lar', copy_X=True,
eps=np.finfo(np.float).eps,
copy_Gram=True, verbose=0, return_path=True,
return_n_iter=False):
"""Compute Least Angle Regression or Lasso path using LARS algorithm [1]
The optimization objective for the case method='lasso' is::
(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
in the case of method='lars', the objective function is only known in
the form of an implicit equation (see discussion in [1])
Read more in the :ref:`User Guide <least_angle_regression>`.
Parameters
-----------
X : array, shape: (n_samples, n_features)
Input data.
y : array, shape: (n_samples)
Input targets.
max_iter : integer, optional (default=500)
Maximum number of iterations to perform, set to infinity for no limit.
Gram : None, 'auto', array, shape: (n_features, n_features), optional
Precomputed Gram matrix (X' * X), if ``'auto'``, the Gram
matrix is precomputed from the given X, if there are more samples
than features.
alpha_min : float, optional (default=0)
Minimum correlation along the path. It corresponds to the
regularization parameter alpha parameter in the Lasso.
method : {'lar', 'lasso'}, optional (default='lar')
Specifies the returned model. Select ``'lar'`` for Least Angle
Regression, ``'lasso'`` for the Lasso.
eps : float, optional (default=``np.finfo(np.float).eps``)
The machine-precision regularization in the computation of the
Cholesky diagonal factors. Increase this for very ill-conditioned
systems.
copy_X : bool, optional (default=True)
If ``False``, ``X`` is overwritten.
copy_Gram : bool, optional (default=True)
If ``False``, ``Gram`` is overwritten.
verbose : int (default=0)
Controls output verbosity.
return_path : bool, optional (default=True)
If ``return_path==True`` returns the entire path, else returns only the
last point of the path.
return_n_iter : bool, optional (default=False)
Whether to return the number of iterations.
Returns
--------
alphas : array, shape: [n_alphas + 1]
Maximum of covariances (in absolute value) at each iteration.
``n_alphas`` is either ``max_iter``, ``n_features`` or the
number of nodes in the path with ``alpha >= alpha_min``, whichever
is smaller.
active : array, shape [n_alphas]
Indices of active variables at the end of the path.
coefs : array, shape (n_features, n_alphas + 1)
Coefficients along the path
n_iter : int
Number of iterations run. Returned only if return_n_iter is set
to True.
See also
--------
lasso_path
LassoLars
Lars
LassoLarsCV
LarsCV
sklearn.decomposition.sparse_encode
References
----------
.. [1] "Least Angle Regression", Effron et al.
http://www-stat.stanford.edu/~tibs/ftp/lars.pdf
.. [2] `Wikipedia entry on the Least-angle regression
<http://en.wikipedia.org/wiki/Least-angle_regression>`_
.. [3] `Wikipedia entry on the Lasso
<http://en.wikipedia.org/wiki/Lasso_(statistics)#Lasso_method>`_
"""
n_features = X.shape[1]
n_samples = y.size
max_features = min(max_iter, n_features)
if return_path:
coefs = np.zeros((max_features + 1, n_features))
alphas = np.zeros(max_features + 1)
else:
coef, prev_coef = np.zeros(n_features), np.zeros(n_features)
alpha, prev_alpha = np.array([0.]), np.array([0.]) # better ideas?
n_iter, n_active = 0, 0
active, indices = list(), np.arange(n_features)
# holds the sign of covariance
sign_active = np.empty(max_features, dtype=np.int8)
drop = False
# will hold the cholesky factorization. Only lower part is
# referenced.
# We are initializing this to "zeros" and not empty, because
# it is passed to scipy linalg functions and thus if it has NaNs,
# even if they are in the upper part that it not used, we
# get errors raised.
# Once we support only scipy > 0.12 we can use check_finite=False and
# go back to "empty"
L = np.zeros((max_features, max_features), dtype=X.dtype)
swap, nrm2 = linalg.get_blas_funcs(('swap', 'nrm2'), (X,))
solve_cholesky, = get_lapack_funcs(('potrs',), (X,))
if Gram is None:
if copy_X:
# force copy. setting the array to be fortran-ordered
# speeds up the calculation of the (partial) Gram matrix
# and allows to easily swap columns
X = X.copy('F')
elif Gram == 'auto':
Gram = None
if X.shape[0] > X.shape[1]:
Gram = np.dot(X.T, X)
elif copy_Gram:
Gram = Gram.copy()
if Xy is None:
Cov = np.dot(X.T, y)
else:
Cov = Xy.copy()
if verbose:
if verbose > 1:
print("Step\t\tAdded\t\tDropped\t\tActive set size\t\tC")
else:
sys.stdout.write('.')
sys.stdout.flush()
tiny = np.finfo(np.float).tiny # to avoid division by 0 warning
tiny32 = np.finfo(np.float32).tiny # to avoid division by 0 warning
equality_tolerance = np.finfo(np.float32).eps
while True:
if Cov.size:
C_idx = np.argmax(np.abs(Cov))
C_ = Cov[C_idx]
C = np.fabs(C_)
else:
C = 0.
if return_path:
alpha = alphas[n_iter, np.newaxis]
coef = coefs[n_iter]
prev_alpha = alphas[n_iter - 1, np.newaxis]
prev_coef = coefs[n_iter - 1]
alpha[0] = C / n_samples
if alpha[0] <= alpha_min + equality_tolerance: # early stopping
if abs(alpha[0] - alpha_min) > equality_tolerance:
# interpolation factor 0 <= ss < 1
if n_iter > 0:
# In the first iteration, all alphas are zero, the formula
# below would make ss a NaN
ss = ((prev_alpha[0] - alpha_min) /
(prev_alpha[0] - alpha[0]))
coef[:] = prev_coef + ss * (coef - prev_coef)
alpha[0] = alpha_min
if return_path:
coefs[n_iter] = coef
break
if n_iter >= max_iter or n_active >= n_features:
break
if not drop:
##########################################################
# Append x_j to the Cholesky factorization of (Xa * Xa') #
# #
# ( L 0 ) #
# L -> ( ) , where L * w = Xa' x_j #
# ( w z ) and z = ||x_j|| #
# #
##########################################################
sign_active[n_active] = np.sign(C_)
m, n = n_active, C_idx + n_active
Cov[C_idx], Cov[0] = swap(Cov[C_idx], Cov[0])
indices[n], indices[m] = indices[m], indices[n]
Cov_not_shortened = Cov
Cov = Cov[1:] # remove Cov[0]
if Gram is None:
X.T[n], X.T[m] = swap(X.T[n], X.T[m])
c = nrm2(X.T[n_active]) ** 2
L[n_active, :n_active] = \
np.dot(X.T[n_active], X.T[:n_active].T)
else:
# swap does only work inplace if matrix is fortran
# contiguous ...
Gram[m], Gram[n] = swap(Gram[m], Gram[n])
Gram[:, m], Gram[:, n] = swap(Gram[:, m], Gram[:, n])
c = Gram[n_active, n_active]
L[n_active, :n_active] = Gram[n_active, :n_active]
# Update the cholesky decomposition for the Gram matrix
if n_active:
linalg.solve_triangular(L[:n_active, :n_active],
L[n_active, :n_active],
trans=0, lower=1,
overwrite_b=True,
**solve_triangular_args)
v = np.dot(L[n_active, :n_active], L[n_active, :n_active])
diag = max(np.sqrt(np.abs(c - v)), eps)
L[n_active, n_active] = diag
if diag < 1e-7:
# The system is becoming too ill-conditioned.
# We have degenerate vectors in our active set.
# We'll 'drop for good' the last regressor added.
# Note: this case is very rare. It is no longer triggered by the
# test suite. The `equality_tolerance` margin added in 0.16.0 to
# get early stopping to work consistently on all versions of
# Python including 32 bit Python under Windows seems to make it
# very difficult to trigger the 'drop for good' strategy.
warnings.warn('Regressors in active set degenerate. '
'Dropping a regressor, after %i iterations, '
'i.e. alpha=%.3e, '
'with an active set of %i regressors, and '
'the smallest cholesky pivot element being %.3e'
% (n_iter, alpha, n_active, diag),
ConvergenceWarning)
# XXX: need to figure a 'drop for good' way
Cov = Cov_not_shortened
Cov[0] = 0
Cov[C_idx], Cov[0] = swap(Cov[C_idx], Cov[0])
continue
active.append(indices[n_active])
n_active += 1
if verbose > 1:
print("%s\t\t%s\t\t%s\t\t%s\t\t%s" % (n_iter, active[-1], '',
n_active, C))
if method == 'lasso' and n_iter > 0 and prev_alpha[0] < alpha[0]:
# alpha is increasing. This is because the updates of Cov are
# bringing in too much numerical error that is greater than
# than the remaining correlation with the
# regressors. Time to bail out
warnings.warn('Early stopping the lars path, as the residues '
'are small and the current value of alpha is no '
'longer well controlled. %i iterations, alpha=%.3e, '
'previous alpha=%.3e, with an active set of %i '
'regressors.'
% (n_iter, alpha, prev_alpha, n_active),
ConvergenceWarning)
break
# least squares solution
least_squares, info = solve_cholesky(L[:n_active, :n_active],
sign_active[:n_active],
lower=True)
if least_squares.size == 1 and least_squares == 0:
# This happens because sign_active[:n_active] = 0
least_squares[...] = 1
AA = 1.
else:
# is this really needed ?
AA = 1. / np.sqrt(np.sum(least_squares * sign_active[:n_active]))
if not np.isfinite(AA):
# L is too ill-conditioned
i = 0
L_ = L[:n_active, :n_active].copy()
while not np.isfinite(AA):
L_.flat[::n_active + 1] += (2 ** i) * eps
least_squares, info = solve_cholesky(
L_, sign_active[:n_active], lower=True)
tmp = max(np.sum(least_squares * sign_active[:n_active]),
eps)
AA = 1. / np.sqrt(tmp)
i += 1
least_squares *= AA
if Gram is None:
# equiangular direction of variables in the active set
eq_dir = np.dot(X.T[:n_active].T, least_squares)
# correlation between each unactive variables and
# eqiangular vector
corr_eq_dir = np.dot(X.T[n_active:], eq_dir)
else:
# if huge number of features, this takes 50% of time, I
# think could be avoided if we just update it using an
# orthogonal (QR) decomposition of X
corr_eq_dir = np.dot(Gram[:n_active, n_active:].T,
least_squares)
g1 = arrayfuncs.min_pos((C - Cov) / (AA - corr_eq_dir + tiny))
g2 = arrayfuncs.min_pos((C + Cov) / (AA + corr_eq_dir + tiny))
gamma_ = min(g1, g2, C / AA)
# TODO: better names for these variables: z
drop = False
z = -coef[active] / (least_squares + tiny32)
z_pos = arrayfuncs.min_pos(z)
if z_pos < gamma_:
# some coefficients have changed sign
idx = np.where(z == z_pos)[0][::-1]
# update the sign, important for LAR
sign_active[idx] = -sign_active[idx]
if method == 'lasso':
gamma_ = z_pos
drop = True
n_iter += 1
if return_path:
if n_iter >= coefs.shape[0]:
del coef, alpha, prev_alpha, prev_coef
# resize the coefs and alphas array
add_features = 2 * max(1, (max_features - n_active))
coefs = np.resize(coefs, (n_iter + add_features, n_features))
alphas = np.resize(alphas, n_iter + add_features)
coef = coefs[n_iter]
prev_coef = coefs[n_iter - 1]
alpha = alphas[n_iter, np.newaxis]
prev_alpha = alphas[n_iter - 1, np.newaxis]
else:
# mimic the effect of incrementing n_iter on the array references
prev_coef = coef
prev_alpha[0] = alpha[0]
coef = np.zeros_like(coef)
coef[active] = prev_coef[active] + gamma_ * least_squares
# update correlations
Cov -= gamma_ * corr_eq_dir
# See if any coefficient has changed sign
if drop and method == 'lasso':
# handle the case when idx is not length of 1
[arrayfuncs.cholesky_delete(L[:n_active, :n_active], ii) for ii in
idx]
n_active -= 1
m, n = idx, n_active
# handle the case when idx is not length of 1
drop_idx = [active.pop(ii) for ii in idx]
if Gram is None:
# propagate dropped variable
for ii in idx:
for i in range(ii, n_active):
X.T[i], X.T[i + 1] = swap(X.T[i], X.T[i + 1])
# yeah this is stupid
indices[i], indices[i + 1] = indices[i + 1], indices[i]
# TODO: this could be updated
residual = y - np.dot(X[:, :n_active], coef[active])
temp = np.dot(X.T[n_active], residual)
Cov = np.r_[temp, Cov]
else:
for ii in idx:
for i in range(ii, n_active):
indices[i], indices[i + 1] = indices[i + 1], indices[i]
Gram[i], Gram[i + 1] = swap(Gram[i], Gram[i + 1])
Gram[:, i], Gram[:, i + 1] = swap(Gram[:, i],
Gram[:, i + 1])
# Cov_n = Cov_j + x_j * X + increment(betas) TODO:
# will this still work with multiple drops ?
# recompute covariance. Probably could be done better
# wrong as Xy is not swapped with the rest of variables
# TODO: this could be updated
residual = y - np.dot(X, coef)
temp = np.dot(X.T[drop_idx], residual)
Cov = np.r_[temp, Cov]
sign_active = np.delete(sign_active, idx)
sign_active = np.append(sign_active, 0.) # just to maintain size
if verbose > 1:
print("%s\t\t%s\t\t%s\t\t%s\t\t%s" % (n_iter, '', drop_idx,
n_active, abs(temp)))
if return_path:
# resize coefs in case of early stop
alphas = alphas[:n_iter + 1]
coefs = coefs[:n_iter + 1]
if return_n_iter:
return alphas, active, coefs.T, n_iter
else:
return alphas, active, coefs.T
else:
if return_n_iter:
return alpha, active, coef, n_iter
else:
return alpha, active, coef
###############################################################################
# Estimator classes
class Lars(LinearModel, RegressorMixin):
"""Least Angle Regression model a.k.a. LAR
Read more in the :ref:`User Guide <least_angle_regression>`.
Parameters
----------
n_nonzero_coefs : int, optional
Target number of non-zero coefficients. Use ``np.inf`` for no limit.
fit_intercept : boolean
Whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
verbose : boolean or integer, optional
Sets the verbosity amount
normalize : boolean, optional, default False
If ``True``, the regressors X will be normalized before regression.
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to ``'auto'`` let us decide. The Gram
matrix can also be passed as argument.
copy_X : boolean, optional, default True
If ``True``, X will be copied; else, it may be overwritten.
eps : float, optional
The machine-precision regularization in the computation of the
Cholesky diagonal factors. Increase this for very ill-conditioned
systems. Unlike the ``tol`` parameter in some iterative
optimization-based algorithms, this parameter does not control
the tolerance of the optimization.
fit_path : boolean
If True the full path is stored in the ``coef_path_`` attribute.
If you compute the solution for a large problem or many targets,
setting ``fit_path`` to ``False`` will lead to a speedup, especially
with a small alpha.
Attributes
----------
alphas_ : array, shape (n_alphas + 1,) | list of n_targets such arrays
Maximum of covariances (in absolute value) at each iteration. \
``n_alphas`` is either ``n_nonzero_coefs`` or ``n_features``, \
whichever is smaller.
active_ : list, length = n_alphas | list of n_targets such lists
Indices of active variables at the end of the path.
coef_path_ : array, shape (n_features, n_alphas + 1) \
| list of n_targets such arrays
The varying values of the coefficients along the path. It is not
present if the ``fit_path`` parameter is ``False``.
coef_ : array, shape (n_features,) or (n_targets, n_features)
Parameter vector (w in the formulation formula).
intercept_ : float | array, shape (n_targets,)
Independent term in decision function.
n_iter_ : array-like or int
The number of iterations taken by lars_path to find the
grid of alphas for each target.
Examples
--------
>>> from sklearn import linear_model
>>> clf = linear_model.Lars(n_nonzero_coefs=1)
>>> clf.fit([[-1, 1], [0, 0], [1, 1]], [-1.1111, 0, -1.1111])
... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Lars(copy_X=True, eps=..., fit_intercept=True, fit_path=True,
n_nonzero_coefs=1, normalize=True, precompute='auto', verbose=False)
>>> print(clf.coef_) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
[ 0. -1.11...]
See also
--------
lars_path, LarsCV
sklearn.decomposition.sparse_encode
"""
def __init__(self, fit_intercept=True, verbose=False, normalize=True,
precompute='auto', n_nonzero_coefs=500,
eps=np.finfo(np.float).eps, copy_X=True, fit_path=True):
self.fit_intercept = fit_intercept
self.verbose = verbose
self.normalize = normalize
self.method = 'lar'
self.precompute = precompute
self.n_nonzero_coefs = n_nonzero_coefs
self.eps = eps
self.copy_X = copy_X
self.fit_path = fit_path
def _get_gram(self):
# precompute if n_samples > n_features
precompute = self.precompute
if hasattr(precompute, '__array__'):
Gram = precompute
elif precompute == 'auto':
Gram = 'auto'
else:
Gram = None
return Gram
def fit(self, X, y, Xy=None):
"""Fit the model using X, y as training data.
parameters
----------
X : array-like, shape (n_samples, n_features)
Training data.
y : array-like, shape (n_samples,) or (n_samples, n_targets)
Target values.
Xy : array-like, shape (n_samples,) or (n_samples, n_targets), \
optional
Xy = np.dot(X.T, y) that can be precomputed. It is useful
only when the Gram matrix is precomputed.
returns
-------
self : object
returns an instance of self.
"""
X, y = check_X_y(X, y, y_numeric=True, multi_output=True)
n_features = X.shape[1]
X, y, X_mean, y_mean, X_std = self._center_data(X, y,
self.fit_intercept,
self.normalize,
self.copy_X)
if y.ndim == 1:
y = y[:, np.newaxis]
n_targets = y.shape[1]
alpha = getattr(self, 'alpha', 0.)
if hasattr(self, 'n_nonzero_coefs'):
alpha = 0. # n_nonzero_coefs parametrization takes priority
max_iter = self.n_nonzero_coefs
else:
max_iter = self.max_iter
precompute = self.precompute
if not hasattr(precompute, '__array__') and (
precompute is True or
(precompute == 'auto' and X.shape[0] > X.shape[1]) or
(precompute == 'auto' and y.shape[1] > 1)):
Gram = np.dot(X.T, X)
else:
Gram = self._get_gram()
self.alphas_ = []
self.n_iter_ = []
if self.fit_path:
self.coef_ = []
self.active_ = []
self.coef_path_ = []
for k in xrange(n_targets):
this_Xy = None if Xy is None else Xy[:, k]
alphas, active, coef_path, n_iter_ = lars_path(
X, y[:, k], Gram=Gram, Xy=this_Xy, copy_X=self.copy_X,
copy_Gram=True, alpha_min=alpha, method=self.method,
verbose=max(0, self.verbose - 1), max_iter=max_iter,
eps=self.eps, return_path=True,
return_n_iter=True)
self.alphas_.append(alphas)
self.active_.append(active)
self.n_iter_.append(n_iter_)
self.coef_path_.append(coef_path)
self.coef_.append(coef_path[:, -1])
if n_targets == 1:
self.alphas_, self.active_, self.coef_path_, self.coef_ = [
a[0] for a in (self.alphas_, self.active_, self.coef_path_,
self.coef_)]
self.n_iter_ = self.n_iter_[0]
else:
self.coef_ = np.empty((n_targets, n_features))
for k in xrange(n_targets):
this_Xy = None if Xy is None else Xy[:, k]
alphas, _, self.coef_[k], n_iter_ = lars_path(
X, y[:, k], Gram=Gram, Xy=this_Xy, copy_X=self.copy_X,
copy_Gram=True, alpha_min=alpha, method=self.method,
verbose=max(0, self.verbose - 1), max_iter=max_iter,
eps=self.eps, return_path=False, return_n_iter=True)
self.alphas_.append(alphas)
self.n_iter_.append(n_iter_)
if n_targets == 1:
self.alphas_ = self.alphas_[0]
self.n_iter_ = self.n_iter_[0]
self._set_intercept(X_mean, y_mean, X_std)
return self
class LassoLars(Lars):
"""Lasso model fit with Least Angle Regression a.k.a. Lars
It is a Linear Model trained with an L1 prior as regularizer.
The optimization objective for Lasso is::
(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
Read more in the :ref:`User Guide <least_angle_regression>`.
Parameters
----------
alpha : float
Constant that multiplies the penalty term. Defaults to 1.0.
``alpha = 0`` is equivalent to an ordinary least square, solved
by :class:`LinearRegression`. For numerical reasons, using
``alpha = 0`` with the LassoLars object is not advised and you
should prefer the LinearRegression object.
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
verbose : boolean or integer, optional
Sets the verbosity amount
normalize : boolean, optional, default False
If True, the regressors X will be normalized before regression.
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to ``'auto'`` let us decide. The Gram
matrix can also be passed as argument.
max_iter : integer, optional
Maximum number of iterations to perform.
eps : float, optional
The machine-precision regularization in the computation of the
Cholesky diagonal factors. Increase this for very ill-conditioned
systems. Unlike the ``tol`` parameter in some iterative
optimization-based algorithms, this parameter does not control
the tolerance of the optimization.
fit_path : boolean
If ``True`` the full path is stored in the ``coef_path_`` attribute.
If you compute the solution for a large problem or many targets,
setting ``fit_path`` to ``False`` will lead to a speedup, especially
with a small alpha.
Attributes
----------
alphas_ : array, shape (n_alphas + 1,) | list of n_targets such arrays
Maximum of covariances (in absolute value) at each iteration. \
``n_alphas`` is either ``max_iter``, ``n_features``, or the number of \
nodes in the path with correlation greater than ``alpha``, whichever \
is smaller.
active_ : list, length = n_alphas | list of n_targets such lists
Indices of active variables at the end of the path.
coef_path_ : array, shape (n_features, n_alphas + 1) or list
If a list is passed it's expected to be one of n_targets such arrays.
The varying values of the coefficients along the path. It is not
present if the ``fit_path`` parameter is ``False``.
coef_ : array, shape (n_features,) or (n_targets, n_features)
Parameter vector (w in the formulation formula).
intercept_ : float | array, shape (n_targets,)
Independent term in decision function.
n_iter_ : array-like or int.
The number of iterations taken by lars_path to find the
grid of alphas for each target.
Examples
--------
>>> from sklearn import linear_model
>>> clf = linear_model.LassoLars(alpha=0.01)
>>> clf.fit([[-1, 1], [0, 0], [1, 1]], [-1, 0, -1])
... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
LassoLars(alpha=0.01, copy_X=True, eps=..., fit_intercept=True,
fit_path=True, max_iter=500, normalize=True, precompute='auto',
verbose=False)
>>> print(clf.coef_) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
[ 0. -0.963257...]
See also
--------
lars_path
lasso_path
Lasso
LassoCV
LassoLarsCV
sklearn.decomposition.sparse_encode
"""
def __init__(self, alpha=1.0, fit_intercept=True, verbose=False,
normalize=True, precompute='auto', max_iter=500,
eps=np.finfo(np.float).eps, copy_X=True, fit_path=True):
self.alpha = alpha
self.fit_intercept = fit_intercept
self.max_iter = max_iter
self.verbose = verbose
self.normalize = normalize
self.method = 'lasso'
self.precompute = precompute
self.copy_X = copy_X
self.eps = eps
self.fit_path = fit_path
###############################################################################
# Cross-validated estimator classes
def _check_copy_and_writeable(array, copy=False):
if copy or not array.flags.writeable:
return array.copy()
return array
def _lars_path_residues(X_train, y_train, X_test, y_test, Gram=None,
copy=True, method='lars', verbose=False,
fit_intercept=True, normalize=True, max_iter=500,
eps=np.finfo(np.float).eps):
"""Compute the residues on left-out data for a full LARS path
Parameters
-----------
X_train : array, shape (n_samples, n_features)
The data to fit the LARS on
y_train : array, shape (n_samples)
The target variable to fit LARS on
X_test : array, shape (n_samples, n_features)
The data to compute the residues on
y_test : array, shape (n_samples)
The target variable to compute the residues on
Gram : None, 'auto', array, shape: (n_features, n_features), optional
Precomputed Gram matrix (X' * X), if ``'auto'``, the Gram
matrix is precomputed from the given X, if there are more samples
than features
copy : boolean, optional
Whether X_train, X_test, y_train and y_test should be copied;
if False, they may be overwritten.
method : 'lar' | 'lasso'
Specifies the returned model. Select ``'lar'`` for Least Angle
Regression, ``'lasso'`` for the Lasso.
verbose : integer, optional
Sets the amount of verbosity
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional, default False
If True, the regressors X will be normalized before regression.
max_iter : integer, optional
Maximum number of iterations to perform.
eps : float, optional
The machine-precision regularization in the computation of the
Cholesky diagonal factors. Increase this for very ill-conditioned
systems. Unlike the ``tol`` parameter in some iterative
optimization-based algorithms, this parameter does not control
the tolerance of the optimization.
Returns
--------
alphas : array, shape (n_alphas,)
Maximum of covariances (in absolute value) at each iteration.
``n_alphas`` is either ``max_iter`` or ``n_features``, whichever
is smaller.
active : list
Indices of active variables at the end of the path.
coefs : array, shape (n_features, n_alphas)
Coefficients along the path
residues : array, shape (n_alphas, n_samples)
Residues of the prediction on the test data
"""
X_train = _check_copy_and_writeable(X_train, copy)
y_train = _check_copy_and_writeable(y_train, copy)
X_test = _check_copy_and_writeable(X_test, copy)
y_test = _check_copy_and_writeable(y_test, copy)
if fit_intercept:
X_mean = X_train.mean(axis=0)
X_train -= X_mean
X_test -= X_mean
y_mean = y_train.mean(axis=0)
y_train = as_float_array(y_train, copy=False)
y_train -= y_mean
y_test = as_float_array(y_test, copy=False)
y_test -= y_mean
if normalize:
norms = np.sqrt(np.sum(X_train ** 2, axis=0))
nonzeros = np.flatnonzero(norms)
X_train[:, nonzeros] /= norms[nonzeros]
alphas, active, coefs = lars_path(
X_train, y_train, Gram=Gram, copy_X=False, copy_Gram=False,
method=method, verbose=max(0, verbose - 1), max_iter=max_iter, eps=eps)
if normalize:
coefs[nonzeros] /= norms[nonzeros][:, np.newaxis]
residues = np.dot(X_test, coefs) - y_test[:, np.newaxis]
return alphas, active, coefs, residues.T
class LarsCV(Lars):
"""Cross-validated Least Angle Regression model
Read more in the :ref:`User Guide <least_angle_regression>`.
Parameters
----------
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
verbose : boolean or integer, optional
Sets the verbosity amount
normalize : boolean, optional, default False
If True, the regressors X will be normalized before regression.
copy_X : boolean, optional, default True
If ``True``, X will be copied; else, it may be overwritten.
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to ``'auto'`` let us decide. The Gram
matrix can also be passed as argument.
max_iter: integer, optional
Maximum number of iterations to perform.
cv : cross-validation generator, optional
see :mod:`sklearn.cross_validation`. If ``None`` is passed, default to
a 5-fold strategy
max_n_alphas : integer, optional
The maximum number of points on the path used to compute the
residuals in the cross-validation
n_jobs : integer, optional
Number of CPUs to use during the cross validation. If ``-1``, use
all the CPUs
eps : float, optional
The machine-precision regularization in the computation of the
Cholesky diagonal factors. Increase this for very ill-conditioned
systems.
Attributes
----------
coef_ : array, shape (n_features,)
parameter vector (w in the formulation formula)
intercept_ : float
independent term in decision function
coef_path_ : array, shape (n_features, n_alphas)
the varying values of the coefficients along the path
alpha_ : float
the estimated regularization parameter alpha
alphas_ : array, shape (n_alphas,)
the different values of alpha along the path
cv_alphas_ : array, shape (n_cv_alphas,)
all the values of alpha along the path for the different folds
cv_mse_path_ : array, shape (n_folds, n_cv_alphas)
the mean square error on left-out for each fold along the path
(alpha values given by ``cv_alphas``)
n_iter_ : array-like or int
the number of iterations run by Lars with the optimal alpha.
See also
--------
lars_path, LassoLars, LassoLarsCV
"""
method = 'lar'
def __init__(self, fit_intercept=True, verbose=False, max_iter=500,
normalize=True, precompute='auto', cv=None,
max_n_alphas=1000, n_jobs=1, eps=np.finfo(np.float).eps,
copy_X=True):
self.fit_intercept = fit_intercept
self.max_iter = max_iter
self.verbose = verbose
self.normalize = normalize
self.precompute = precompute
self.copy_X = copy_X
self.cv = cv
self.max_n_alphas = max_n_alphas
self.n_jobs = n_jobs
self.eps = eps
def fit(self, X, y):
"""Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data.
y : array-like, shape (n_samples,)
Target values.
Returns
-------
self : object
returns an instance of self.
"""
self.fit_path = True
X, y = check_X_y(X, y, y_numeric=True)
# init cross-validation generator
cv = check_cv(self.cv, X, y, classifier=False)
Gram = 'auto' if self.precompute else None
cv_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
delayed(_lars_path_residues)(
X[train], y[train], X[test], y[test], Gram=Gram, copy=False,
method=self.method, verbose=max(0, self.verbose - 1),
normalize=self.normalize, fit_intercept=self.fit_intercept,
max_iter=self.max_iter, eps=self.eps)
for train, test in cv)
all_alphas = np.concatenate(list(zip(*cv_paths))[0])
# Unique also sorts
all_alphas = np.unique(all_alphas)
# Take at most max_n_alphas values
stride = int(max(1, int(len(all_alphas) / float(self.max_n_alphas))))
all_alphas = all_alphas[::stride]
mse_path = np.empty((len(all_alphas), len(cv_paths)))
for index, (alphas, active, coefs, residues) in enumerate(cv_paths):
alphas = alphas[::-1]
residues = residues[::-1]
if alphas[0] != 0:
alphas = np.r_[0, alphas]
residues = np.r_[residues[0, np.newaxis], residues]
if alphas[-1] != all_alphas[-1]:
alphas = np.r_[alphas, all_alphas[-1]]
residues = np.r_[residues, residues[-1, np.newaxis]]
this_residues = interpolate.interp1d(alphas,
residues,
axis=0)(all_alphas)
this_residues **= 2
mse_path[:, index] = np.mean(this_residues, axis=-1)
mask = np.all(np.isfinite(mse_path), axis=-1)
all_alphas = all_alphas[mask]
mse_path = mse_path[mask]
# Select the alpha that minimizes left-out error
i_best_alpha = np.argmin(mse_path.mean(axis=-1))
best_alpha = all_alphas[i_best_alpha]
# Store our parameters
self.alpha_ = best_alpha
self.cv_alphas_ = all_alphas
self.cv_mse_path_ = mse_path
# Now compute the full model
# it will call a lasso internally when self if LassoLarsCV
# as self.method == 'lasso'
Lars.fit(self, X, y)
return self
@property
def alpha(self):
# impedance matching for the above Lars.fit (should not be documented)
return self.alpha_
class LassoLarsCV(LarsCV):
"""Cross-validated Lasso, using the LARS algorithm
The optimization objective for Lasso is::
(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
Read more in the :ref:`User Guide <least_angle_regression>`.
Parameters
----------
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
verbose : boolean or integer, optional
Sets the verbosity amount
normalize : boolean, optional, default False
If True, the regressors X will be normalized before regression.
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to ``'auto'`` let us decide. The Gram
matrix can also be passed as argument.
max_iter : integer, optional
Maximum number of iterations to perform.
cv : cross-validation generator, optional
see sklearn.cross_validation module. If None is passed, default to
a 5-fold strategy
max_n_alphas : integer, optional
The maximum number of points on the path used to compute the
residuals in the cross-validation
n_jobs : integer, optional
Number of CPUs to use during the cross validation. If ``-1``, use
all the CPUs
eps : float, optional
The machine-precision regularization in the computation of the
Cholesky diagonal factors. Increase this for very ill-conditioned
systems.
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
Attributes
----------
coef_ : array, shape (n_features,)
parameter vector (w in the formulation formula)
intercept_ : float
independent term in decision function.
coef_path_ : array, shape (n_features, n_alphas)
the varying values of the coefficients along the path
alpha_ : float
the estimated regularization parameter alpha
alphas_ : array, shape (n_alphas,)
the different values of alpha along the path
cv_alphas_ : array, shape (n_cv_alphas,)
all the values of alpha along the path for the different folds
cv_mse_path_ : array, shape (n_folds, n_cv_alphas)
the mean square error on left-out for each fold along the path
(alpha values given by ``cv_alphas``)
n_iter_ : array-like or int
the number of iterations run by Lars with the optimal alpha.
Notes
-----
The object solves the same problem as the LassoCV object. However,
unlike the LassoCV, it find the relevant alphas values by itself.
In general, because of this property, it will be more stable.
However, it is more fragile to heavily multicollinear datasets.
It is more efficient than the LassoCV if only a small number of
features are selected compared to the total number, for instance if
there are very few samples compared to the number of features.
See also
--------
lars_path, LassoLars, LarsCV, LassoCV
"""
method = 'lasso'
class LassoLarsIC(LassoLars):
"""Lasso model fit with Lars using BIC or AIC for model selection
The optimization objective for Lasso is::
(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
AIC is the Akaike information criterion and BIC is the Bayes
Information criterion. Such criteria are useful to select the value
of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should
explain well the data while being simple.
Read more in the :ref:`User Guide <least_angle_regression>`.
Parameters
----------
criterion : 'bic' | 'aic'
The type of criterion to use.
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
verbose : boolean or integer, optional
Sets the verbosity amount
normalize : boolean, optional, default False
If True, the regressors X will be normalized before regression.
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to ``'auto'`` let us decide. The Gram
matrix can also be passed as argument.
max_iter : integer, optional
Maximum number of iterations to perform. Can be used for
early stopping.
eps : float, optional
The machine-precision regularization in the computation of the
Cholesky diagonal factors. Increase this for very ill-conditioned
systems. Unlike the ``tol`` parameter in some iterative
optimization-based algorithms, this parameter does not control
the tolerance of the optimization.
Attributes
----------
coef_ : array, shape (n_features,)
parameter vector (w in the formulation formula)
intercept_ : float
independent term in decision function.
alpha_ : float
the alpha parameter chosen by the information criterion
n_iter_ : int
number of iterations run by lars_path to find the grid of
alphas.
criterion_ : array, shape (n_alphas,)
The value of the information criteria ('aic', 'bic') across all
alphas. The alpha which has the smallest information criteria
is chosen.
Examples
--------
>>> from sklearn import linear_model
>>> clf = linear_model.LassoLarsIC(criterion='bic')
>>> clf.fit([[-1, 1], [0, 0], [1, 1]], [-1.1111, 0, -1.1111])
... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
LassoLarsIC(copy_X=True, criterion='bic', eps=..., fit_intercept=True,
max_iter=500, normalize=True, precompute='auto',
verbose=False)
>>> print(clf.coef_) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
[ 0. -1.11...]
Notes
-----
The estimation of the number of degrees of freedom is given by:
"On the degrees of freedom of the lasso"
Hui Zou, Trevor Hastie, and Robert Tibshirani
Ann. Statist. Volume 35, Number 5 (2007), 2173-2192.
http://en.wikipedia.org/wiki/Akaike_information_criterion
http://en.wikipedia.org/wiki/Bayesian_information_criterion
See also
--------
lars_path, LassoLars, LassoLarsCV
"""
def __init__(self, criterion='aic', fit_intercept=True, verbose=False,
normalize=True, precompute='auto', max_iter=500,
eps=np.finfo(np.float).eps, copy_X=True):
self.criterion = criterion
self.fit_intercept = fit_intercept
self.max_iter = max_iter
self.verbose = verbose
self.normalize = normalize
self.copy_X = copy_X
self.precompute = precompute
self.eps = eps
def fit(self, X, y, copy_X=True):
"""Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape (n_samples, n_features)
training data.
y : array-like, shape (n_samples,)
target values.
copy_X : boolean, optional, default True
If ``True``, X will be copied; else, it may be overwritten.
Returns
-------
self : object
returns an instance of self.
"""
self.fit_path = True
X, y = check_X_y(X, y, y_numeric=True)
X, y, Xmean, ymean, Xstd = LinearModel._center_data(
X, y, self.fit_intercept, self.normalize, self.copy_X)
max_iter = self.max_iter
Gram = self._get_gram()
alphas_, active_, coef_path_, self.n_iter_ = lars_path(
X, y, Gram=Gram, copy_X=copy_X, copy_Gram=True, alpha_min=0.0,
method='lasso', verbose=self.verbose, max_iter=max_iter,
eps=self.eps, return_n_iter=True)
n_samples = X.shape[0]
if self.criterion == 'aic':
K = 2 # AIC
elif self.criterion == 'bic':
K = log(n_samples) # BIC
else:
raise ValueError('criterion should be either bic or aic')
R = y[:, np.newaxis] - np.dot(X, coef_path_) # residuals
mean_squared_error = np.mean(R ** 2, axis=0)
df = np.zeros(coef_path_.shape[1], dtype=np.int) # Degrees of freedom
for k, coef in enumerate(coef_path_.T):
mask = np.abs(coef) > np.finfo(coef.dtype).eps
if not np.any(mask):
continue
# get the number of degrees of freedom equal to:
# Xc = X[:, mask]
# Trace(Xc * inv(Xc.T, Xc) * Xc.T) ie the number of non-zero coefs
df[k] = np.sum(mask)
self.alphas_ = alphas_
with np.errstate(divide='ignore'):
self.criterion_ = n_samples * np.log(mean_squared_error) + K * df
n_best = np.argmin(self.criterion_)
self.alpha_ = alphas_[n_best]
self.coef_ = coef_path_[:, n_best]
self._set_intercept(Xmean, ymean, Xstd)
return self
| bsd-3-clause |
alonbl/otopi | src/plugins/otopi/packagers/__init__.py | 1 | 1073 | #
# otopi -- plugable installer
# Copyright (C) 2012-2013 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
"""Packager provider."""
from otopi import util
from . import dnfpackager
from . import yumpackager
@util.export
def createPlugins(context):
dnfpackager.Plugin(context=context)
yumpackager.Plugin(context=context)
# vim: expandtab tabstop=4 shiftwidth=4
| lgpl-2.1 |
KhalidGit/flask | Work/Trivia - Module 5/env/Lib/site-packages/setuptools/tests/test_develop.py | 286 | 3605 | """develop tests
"""
import sys
import os, shutil, tempfile, unittest
import tempfile
import site
from distutils.errors import DistutilsError
from setuptools.command.develop import develop
from setuptools.command import easy_install as easy_install_pkg
from setuptools.compat import StringIO
from setuptools.dist import Distribution
SETUP_PY = """\
from setuptools import setup
setup(name='foo',
packages=['foo'],
use_2to3=True,
)
"""
INIT_PY = """print "foo"
"""
class TestDevelopTest(unittest.TestCase):
def setUp(self):
if sys.version < "2.6" or hasattr(sys, 'real_prefix'):
return
# Directory structure
self.dir = tempfile.mkdtemp()
os.mkdir(os.path.join(self.dir, 'foo'))
# setup.py
setup = os.path.join(self.dir, 'setup.py')
f = open(setup, 'w')
f.write(SETUP_PY)
f.close()
self.old_cwd = os.getcwd()
# foo/__init__.py
init = os.path.join(self.dir, 'foo', '__init__.py')
f = open(init, 'w')
f.write(INIT_PY)
f.close()
os.chdir(self.dir)
self.old_base = site.USER_BASE
site.USER_BASE = tempfile.mkdtemp()
self.old_site = site.USER_SITE
site.USER_SITE = tempfile.mkdtemp()
def tearDown(self):
if sys.version < "2.6" or hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
return
os.chdir(self.old_cwd)
shutil.rmtree(self.dir)
shutil.rmtree(site.USER_BASE)
shutil.rmtree(site.USER_SITE)
site.USER_BASE = self.old_base
site.USER_SITE = self.old_site
def test_develop(self):
if sys.version < "2.6" or hasattr(sys, 'real_prefix'):
return
dist = Distribution(
dict(name='foo',
packages=['foo'],
use_2to3=True,
version='0.0',
))
dist.script_name = 'setup.py'
cmd = develop(dist)
cmd.user = 1
cmd.ensure_finalized()
cmd.install_dir = site.USER_SITE
cmd.user = 1
old_stdout = sys.stdout
#sys.stdout = StringIO()
try:
cmd.run()
finally:
sys.stdout = old_stdout
# let's see if we got our egg link at the right place
content = os.listdir(site.USER_SITE)
content.sort()
self.assertEqual(content, ['easy-install.pth', 'foo.egg-link'])
# Check that we are using the right code.
egg_link_file = open(os.path.join(site.USER_SITE, 'foo.egg-link'), 'rt')
try:
path = egg_link_file.read().split()[0].strip()
finally:
egg_link_file.close()
init_file = open(os.path.join(path, 'foo', '__init__.py'), 'rt')
try:
init = init_file.read().strip()
finally:
init_file.close()
if sys.version < "3":
self.assertEqual(init, 'print "foo"')
else:
self.assertEqual(init, 'print("foo")')
def notest_develop_with_setup_requires(self):
wanted = ("Could not find suitable distribution for "
"Requirement.parse('I-DONT-EXIST')")
old_dir = os.getcwd()
os.chdir(self.dir)
try:
try:
dist = Distribution({'setup_requires': ['I_DONT_EXIST']})
except DistutilsError:
e = sys.exc_info()[1]
error = str(e)
if error == wanted:
pass
finally:
os.chdir(old_dir)
| apache-2.0 |
unifycore/ryu | ryu/ofproto/ofproto_v1_3_parser.py | 1 | 206989 | # Copyright (C) 2012 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2012, 2013 Isaku Yamahata <yamahata at valinux co jp>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import struct
import itertools
from ryu.lib import addrconv
from ryu.lib import mac
from ryu import utils
from ofproto_parser import StringifyMixin, MsgBase, msg_pack_into, msg_str_attr
from . import ofproto_parser
from . import ofproto_v1_3
import logging
LOG = logging.getLogger('ryu.ofproto.ofproto_v1_3_parser')
_MSG_PARSERS = {}
def _set_msg_type(msg_type):
def _set_cls_msg_type(cls):
cls.cls_msg_type = msg_type
return cls
return _set_cls_msg_type
def _register_parser(cls):
'''class decorator to register msg parser'''
assert cls.cls_msg_type is not None
assert cls.cls_msg_type not in _MSG_PARSERS
_MSG_PARSERS[cls.cls_msg_type] = cls.parser
return cls
@ofproto_parser.register_msg_parser(ofproto_v1_3.OFP_VERSION)
def msg_parser(datapath, version, msg_type, msg_len, xid, buf):
parser = _MSG_PARSERS.get(msg_type)
return parser(datapath, version, msg_type, msg_len, xid, buf)
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_HELLO)
class OFPHello(MsgBase):
"""
Hello message
When connection is started, the hello message is exchanged between a
switch and a controller.
This message is handled by the Ryu framework, so the Ryu application
do not need to process this typically.
========== =========================================================
Attribute Description
========== =========================================================
elements list of ``OFPHelloElemVersionBitmap`` instance
========== =========================================================
"""
def __init__(self, datapath, elements=[]):
super(OFPHello, self).__init__(datapath)
self.elements = elements
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPHello, cls).parser(datapath, version, msg_type,
msg_len, xid, buf)
offset = ofproto_v1_3.OFP_HELLO_HEADER_SIZE
elems = []
while offset < msg.msg_len:
type_, length = struct.unpack_from(
ofproto_v1_3.OFP_HELLO_ELEM_HEADER_PACK_STR, msg.buf, offset)
# better to register Hello Element classes but currently
# Only VerisonBitmap is supported so let's be simple.
if type_ == ofproto_v1_3.OFPHET_VERSIONBITMAP:
elem = OFPHelloElemVersionBitmap.parser(msg.buf, offset)
elems.append(elem)
offset += length
msg.elements = elems
return msg
class OFPHelloElemVersionBitmap(StringifyMixin):
"""
Version bitmap Hello Element
========== =========================================================
Attribute Description
========== =========================================================
versions list of versions of OpenFlow protocol a device supports
========== =========================================================
"""
def __init__(self, versions, type_=None, length=None):
super(OFPHelloElemVersionBitmap, self).__init__()
self.type = ofproto_v1_3.OFPHET_VERSIONBITMAP
self.length = None
self._bitmaps = None
self.versions = versions
@classmethod
def parser(cls, buf, offset):
type_, length = struct.unpack_from(
ofproto_v1_3.OFP_HELLO_ELEM_VERSIONBITMAP_HEADER_PACK_STR,
buf, offset)
assert type_ == ofproto_v1_3.OFPHET_VERSIONBITMAP
bitmaps_len = (length -
ofproto_v1_3.OFP_HELLO_ELEM_VERSIONBITMAP_HEADER_SIZE)
offset += ofproto_v1_3.OFP_HELLO_ELEM_VERSIONBITMAP_HEADER_SIZE
bitmaps = []
while bitmaps_len >= 4:
bitmap = struct.unpack_from('!I', buf, offset)
bitmaps.append(bitmap[0])
offset += 4
bitmaps_len -= 4
versions = [i * 32 + shift
for i, bitmap in enumerate(bitmaps)
for shift in range(31) if bitmap & (1 << shift)]
elem = cls(versions)
elem.length = length
elem._bitmaps = bitmaps
return elem
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_ERROR)
class OFPErrorMsg(MsgBase):
"""
Error message
The switch notifies controller of problems by this message.
========== =========================================================
Attribute Description
========== =========================================================
type High level type of error
code Details depending on the type
data Variable length data depending on the type and code
========== =========================================================
``type`` attribute corresponds to ``type_`` parameter of __init__.
Types and codes are defined in ``ryu.ofproto.ofproto_v1_3``.
============================= ===========
Type Code
============================= ===========
OFPET_HELLO_FAILED OFPHFC_*
OFPET_BAD_REQUEST OFPBRC_*
OFPET_BAD_ACTION OFPBAC_*
OFPET_BAD_INSTRUCTION OFPBIC_*
OFPET_BAD_MATCH OFPBMC_*
OFPET_FLOW_MOD_FAILED OFPFMFC_*
OFPET_GROUP_MOD_FAILED OFPGMFC_*
OFPET_PORT_MOD_FAILED OFPPMFC_*
OFPET_TABLE_MOD_FAILED OFPTMFC_*
OFPET_QUEUE_OP_FAILED OFPQOFC_*
OFPET_SWITCH_CONFIG_FAILED OFPSCFC_*
OFPET_ROLE_REQUEST_FAILED OFPRRFC_*
OFPET_METER_MOD_FAILED OFPMMFC_*
OFPET_TABLE_FEATURES_FAILED OFPTFFC_*
OFPET_EXPERIMENTER N/A
============================= ===========
Example::
@set_ev_cls(ofp_event.EventOFPErrorMsg,
[HANDSHAKE_DISPATCHER, CONFIG_DISPATCHER, MAIN_DISPATCHER])
def error_msg_handler(self, ev):
msg = ev.msg
self.logger.debug('OFPErrorMsg received: type=0x%02x code=0x%02x '
'message=%s',
msg.type, msg.code, utils.hex_array(msg.data))
"""
def __init__(self, datapath, type_=None, code=None, data=None):
super(OFPErrorMsg, self).__init__(datapath)
self.type = type_
self.code = code
self.data = data
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPErrorMsg, cls).parser(datapath, version, msg_type,
msg_len, xid, buf)
msg.type, msg.code = struct.unpack_from(
ofproto_v1_3.OFP_ERROR_MSG_PACK_STR, msg.buf,
ofproto_v1_3.OFP_HEADER_SIZE)
msg.data = msg.buf[ofproto_v1_3.OFP_ERROR_MSG_SIZE:]
return msg
def _serialize_body(self):
assert self.data is not None
msg_pack_into(ofproto_v1_3.OFP_ERROR_MSG_PACK_STR, self.buf,
ofproto_v1_3.OFP_HEADER_SIZE, self.type, self.code)
self.buf += self.data
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_ECHO_REQUEST)
class OFPEchoRequest(MsgBase):
"""
Echo request message
This message is handled by the Ryu framework, so the Ryu application
do not need to process this typically.
========== =========================================================
Attribute Description
========== =========================================================
data An arbitrary length data
========== =========================================================
Example::
def send_echo_request(self, datapath, data):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPEchoRequest(datapath, data)
datapath.send_msg(req)
@set_ev_cls(ofp_event.EventOFPEchoRequest,
[HANDSHAKE_DISPATCHER, CONFIG_DISPATCHER, MAIN_DISPATCHER])
def echo_request_handler(self, ev):
self.logger.debug('OFPEchoRequest received: data=%s',
utils.hex_array(ev.msg.data))
"""
def __init__(self, datapath, data=None):
super(OFPEchoRequest, self).__init__(datapath)
self.data = data
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPEchoRequest, cls).parser(datapath, version, msg_type,
msg_len, xid, buf)
msg.data = msg.buf[ofproto_v1_3.OFP_HEADER_SIZE:]
return msg
def _serialize_body(self):
if self.data is not None:
self.buf += self.data
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_ECHO_REPLY)
class OFPEchoReply(MsgBase):
"""
Echo reply message
This message is handled by the Ryu framework, so the Ryu application
do not need to process this typically.
========== =========================================================
Attribute Description
========== =========================================================
data An arbitrary length data
========== =========================================================
Example::
def send_echo_reply(self, datapath, data):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
reply = ofp_parser.OFPEchoReply(datapath, data)
datapath.send_msg(reply)
@set_ev_cls(ofp_event.EventOFPEchoReply,
[HANDSHAKE_DISPATCHER, CONFIG_DISPATCHER, MAIN_DISPATCHER])
def echo_reply_handler(self, ev):
self.logger.debug('OFPEchoReply received: data=%s',
utils.hex_array(ev.msg.data))
"""
def __init__(self, datapath, data=None):
super(OFPEchoReply, self).__init__(datapath)
self.data = data
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPEchoReply, cls).parser(datapath, version, msg_type,
msg_len, xid, buf)
msg.data = msg.buf[ofproto_v1_3.OFP_HEADER_SIZE:]
return msg
def _serialize_body(self):
assert self.data is not None
self.buf += self.data
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_EXPERIMENTER)
class OFPExperimenter(MsgBase):
"""
Experimenter extension message
============= =========================================================
Attribute Description
============= =========================================================
experimenter Experimenter ID
exp_type Experimenter defined
data Experimenter defined arbitrary additional data
============= =========================================================
"""
def __init__(self, datapath, experimenter=None, exp_type=None, data=None):
super(OFPExperimenter, self).__init__(datapath)
self.experimenter = experimenter
self.exp_type = exp_type
self.data = data
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPExperimenter, cls).parser(datapath, version,
msg_type, msg_len,
xid, buf)
(msg.experimenter, msg.exp_type) = struct.unpack_from(
ofproto_v1_3.OFP_EXPERIMENTER_HEADER_PACK_STR, msg.buf,
ofproto_v1_3.OFP_HEADER_SIZE)
msg.data = msg.buf[ofproto_v1_3.OFP_EXPERIMENTER_HEADER_SIZE:]
return msg
@_set_msg_type(ofproto_v1_3.OFPT_FEATURES_REQUEST)
class OFPFeaturesRequest(MsgBase):
"""
Features request message
The controller sends a feature request to the switch upon session
establishment.
This message is handled by the Ryu framework, so the Ryu application
do not need to process this typically.
Example::
def send_features_request(self, datapath):
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPFeaturesRequest(datapath)
datapath.send_msg(req)
"""
def __init__(self, datapath):
super(OFPFeaturesRequest, self).__init__(datapath)
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_FEATURES_REPLY)
class OFPSwitchFeatures(MsgBase):
"""
Features reply message
The switch responds with a features reply message to a features
request.
This message is handled by the Ryu framework, so the Ryu application
do not need to process this typically.
Example::
@set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
msg = ev.msg
self.logger.debug('OFPSwitchFeatures received: '
'datapath_id=0x%016x n_buffers=%d '
'n_tables=%d auxiliary_id=%d '
'capabilities=0x%08x',
msg.datapath_id, msg.n_buffers, msg.n_tables,
msg.auxiliary_id, msg.capabilities)
"""
def __init__(self, datapath, datapath_id=None, n_buffers=None,
n_tables=None, auxiliary_id=None, capabilities=None):
super(OFPSwitchFeatures, self).__init__(datapath)
self.datapath_id = datapath_id
self.n_buffers = n_buffers
self.n_tables = n_tables
self.auxiliary_id = auxiliary_id
self.capabilities = capabilities
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPSwitchFeatures, cls).parser(datapath, version, msg_type,
msg_len, xid, buf)
(msg.datapath_id,
msg.n_buffers,
msg.n_tables,
msg.auxiliary_id,
msg.capabilities,
msg._reserved) = struct.unpack_from(
ofproto_v1_3.OFP_SWITCH_FEATURES_PACK_STR, msg.buf,
ofproto_v1_3.OFP_HEADER_SIZE)
return msg
@_set_msg_type(ofproto_v1_3.OFPT_GET_CONFIG_REQUEST)
class OFPGetConfigRequest(MsgBase):
"""
Get config request message
The controller sends a get config request to query configuration
parameters in the switch.
Example::
def send_get_config_request(self, datapath):
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPGetConfigRequest(datapath)
datapath.send_msg(req)
"""
def __init__(self, datapath):
super(OFPGetConfigRequest, self).__init__(datapath)
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_GET_CONFIG_REPLY)
class OFPGetConfigReply(MsgBase):
"""
Get config reply message
The switch responds to a configuration request with a get config reply
message.
============= =========================================================
Attribute Description
============= =========================================================
flags One of the following configuration flags.
OFPC_FRAG_NORMAL
OFPC_FRAG_DROP
OFPC_FRAG_REASM
OFPC_FRAG_MASK
miss_send_len Max bytes of new flow that datapath should send to the
controller
============= =========================================================
Example::
@set_ev_cls(ofp_event.EventOFPGetConfigReply, MAIN_DISPATCHER)
def get_config_reply_handler(self, ev):
msg = ev.msg
dp = msg.datapath
ofp = dp.ofproto
if msg.flags == ofp.OFPC_FRAG_NORMAL:
flags = 'NORMAL'
elif msg.flags == ofp.OFPC_FRAG_DROP:
flags = 'DROP'
elif msg.flags == ofp.OFPC_FRAG_REASM:
flags = 'REASM'
elif msg.flags == ofp.OFPC_FRAG_MASK:
flags = 'MASK'
else:
flags = 'unknown'
self.logger.debug('OFPGetConfigReply received: '
'flags=%s miss_send_len=%d',
flags, msg.miss_send_len)
"""
def __init__(self, datapath, flags=None, miss_send_len=None):
super(OFPGetConfigReply, self).__init__(datapath)
self.flags = flags
self.miss_send_len = miss_send_len
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPGetConfigReply, cls).parser(datapath, version, msg_type,
msg_len, xid, buf)
msg.flags, msg.miss_send_len = struct.unpack_from(
ofproto_v1_3.OFP_SWITCH_CONFIG_PACK_STR, msg.buf,
ofproto_v1_3.OFP_HEADER_SIZE)
return msg
@_set_msg_type(ofproto_v1_3.OFPT_SET_CONFIG)
class OFPSetConfig(MsgBase):
"""
Set config request message
The controller sends a set config request message to set configuraion
parameters.
============= =========================================================
Attribute Description
============= =========================================================
flags One of the following configuration flags.
OFPC_FRAG_NORMAL
OFPC_FRAG_DROP
OFPC_FRAG_REASM
OFPC_FRAG_MASK
miss_send_len Max bytes of new flow that datapath should send to the
controller
============= =========================================================
Example::
def send_set_config(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPSetConfig(datapath, ofp.OFPC_FRAG_NORMAL, 256)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags=0, miss_send_len=0):
super(OFPSetConfig, self).__init__(datapath)
self.flags = flags
self.miss_send_len = miss_send_len
def _serialize_body(self):
assert self.flags is not None
assert self.miss_send_len is not None
msg_pack_into(ofproto_v1_3.OFP_SWITCH_CONFIG_PACK_STR,
self.buf, ofproto_v1_3.OFP_HEADER_SIZE,
self.flags, self.miss_send_len)
UINT64_MAX = (1 << 64) - 1
UINT32_MAX = (1 << 32) - 1
UINT16_MAX = (1 << 16) - 1
class Flow(object):
def __init__(self):
self.in_port = 0
self.in_phy_port = 0
self.metadata = 0
self.dl_dst = mac.DONTCARE
self.dl_src = mac.DONTCARE
self.dl_type = 0
self.vlan_vid = 0
self.vlan_pcp = 0
self.ip_dscp = 0
self.ip_ecn = 0
self.ip_proto = 0
self.ipv4_src = 0
self.ipv4_dst = 0
self.tcp_src = 0
self.tcp_dst = 0
self.udp_src = 0
self.udp_dst = 0
self.sctp_src = 0
self.sctp_dst = 0
self.icmpv4_type = 0
self.icmpv4_code = 0
self.arp_op = 0
self.arp_spa = 0
self.arp_tpa = 0
self.arp_sha = 0
self.arp_tha = 0
self.ipv6_src = []
self.ipv6_dst = []
self.ipv6_flabel = 0
self.icmpv6_type = 0
self.icmpv6_code = 0
self.ipv6_nd_target = []
self.ipv6_nd_sll = 0
self.ipv6_nd_tll = 0
self.mpls_label = 0
self.mpls_tc = 0
self.mpls_bos = 0
self.pbb_isid = 0
self.tunnel_id = 0
self.ipv6_exthdr = 0
self.ns_type = 0
self.ns_bvci = 0
self.bssgp_tlli = 0
self.llc_sapi = 0
self.sndcp_nsapi = 0
self.sndcp_first_segment = 0
self.sndcp_more_segments = 0
self.sndcp_comp = 0
class FlowWildcards(object):
def __init__(self):
self.metadata_mask = 0
self.dl_dst_mask = 0
self.dl_src_mask = 0
self.vlan_vid_mask = 0
self.ipv4_src_mask = 0
self.ipv4_dst_mask = 0
self.arp_spa_mask = 0
self.arp_tpa_mask = 0
self.arp_sha_mask = 0
self.arp_tha_mask = 0
self.ipv6_src_mask = []
self.ipv6_dst_mask = []
self.ipv6_flabel_mask = 0
self.pbb_isid_mask = 0
self.tunnel_id_mask = 0
self.ipv6_exthdr_mask = 0
self.wildcards = (1 << 64) - 1
def ft_set(self, shift):
self.wildcards &= ~(1 << shift)
def ft_test(self, shift):
return not self.wildcards & (1 << shift)
class OFPMatch(StringifyMixin):
"""
Flow Match Structure
This class is implementation of the flow match structure having
compose/query API.
There are new API and old API for compatibility. the old API is
supposed to be removed later.
You can define the flow match by the keyword arguments.
The following arguments are available.
================ =============== ==================================
Argument Value Description
================ =============== ==================================
in_port Integer 32bit Switch input port
in_phy_port Integer 32bit Switch physical input port
metadata Integer 64bit Metadata passed between tables
eth_dst MAC address Ethernet destination address
eth_src MAC address Ethernet source address
eth_type Integer 16bit Ethernet frame type
vlan_vid Integer 16bit VLAN id
vlan_pcp Integer 8bit VLAN priority
ip_dscp Integer 8bit IP DSCP (6 bits in ToS field)
ip_ecn Integer 8bit IP ECN (2 bits in ToS field)
ip_proto Integer 8bit IP protocol
ipv4_src IPv4 address IPv4 source address
ipv4_dst IPv4 address IPv4 destination address
tcp_src Integer 16bit TCP source port
tcp_dst Integer 16bit TCP destination port
udp_src Integer 16bit UDP source port
udp_dst Integer 16bit UDP destination port
sctp_src Integer 16bit SCTP source port
sctp_dst Integer 16bit SCTP destination port
icmpv4_type Integer 8bit ICMP type
icmpv4_code Integer 8bit ICMP code
arp_op Integer 16bit ARP opcode
arp_spa IPv4 address ARP source IPv4 address
arp_tpa IPv4 address ARP target IPv4 address
arp_sha MAC address ARP source hardware address
arp_tha MAC address ARP target hardware address
ipv6_src IPv6 address IPv6 source address
ipv6_dst IPv6 address IPv6 destination address
ipv6_flabel Integer 32bit IPv6 Flow Label
icmpv6_type Integer 8bit ICMPv6 type
icmpv6_code Integer 8bit ICMPv6 code
ipv6_nd_target IPv6 address Target address for ND
ipv6_nd_sll MAC address Source link-layer for ND
ipv6_nd_tll MAC address Target link-layer for ND
mpls_label Integer 32bit MPLS label
mpls_tc Integer 8bit MPLS TC
mpls_bos Integer 8bit MPLS BoS bit
pbb_isid Integer 24bit PBB I-SID
tunnel_id Integer 64bit Logical Port Metadata
ipv6_exthdr Integer 16bit IPv6 Extension Header pseudo-field
================ =============== ==================================
Example::
>>> # compose
>>> match = parser.OFPMatch(
... in_port=1,
... eth_type=0x86dd,
... ipv6_src=('2001:db8:bd05:1d2:288a:1fc0:1:10ee',
... 'ffff:ffff:ffff:ffff::'),
... ipv6_dst='2001:db8:bd05:1d2:288a:1fc0:1:10ee')
>>> # query
>>> if 'ipv6_src' in match:
... print match['ipv6_src']
...
('2001:db8:bd05:1d2:288a:1fc0:1:10ee', 'ffff:ffff:ffff:ffff::')
"""
def __init__(self, type_=None, length=None, _ordered_fields=None,
**kwargs):
"""
You can define the flow match by the keyword arguments.
Please refer to ofproto_v1_3.oxm_types for the key which you can
define.
"""
super(OFPMatch, self).__init__()
self._wc = FlowWildcards()
self._flow = Flow()
self.fields = []
self.type = ofproto_v1_3.OFPMT_OXM
self.length = length
if not _ordered_fields is None:
assert not kwargs
self._fields2 = _ordered_fields
else:
# eg.
# OFPMatch(eth_src=('ff:ff:ff:00:00:00'), eth_type=0x800,
# ipv4_src='10.0.0.1')
kwargs = dict(ofproto_v1_3.oxm_normalize_user(k, v) for
(k, v) in kwargs.iteritems())
fields = [ofproto_v1_3.oxm_from_user(k, v) for (k, v)
in kwargs.iteritems()]
# assumption: sorting by OXM type values makes fields
# meet ordering requirements (eg. eth_type before ipv4_src)
#FIXME:
fields = sorted(fields, cmp=self.oxm_sort_cmp)
self._fields2 = [ofproto_v1_3.oxm_to_user(n, v, m) for (n, v, m)
in fields]
def oxm_sort_cmp(self, oxm1, oxm2):
(n1, v1, m1) = oxm1
(n2, v2, m2) = oxm2
c1 = n1 & 0xffff00
c2 = n2 & 0xffff00
f1 = n1 & 0x0000ff
f2 = n2 & 0x0000ff
# order by OXM_CLASS descending
if c1 < c2:
return 1
elif c1 > c2:
return -1
# order by field (within class) ascending
if f1 < f2:
return -1
elif f1 > f2:
return 1
# same
return 0
def __getitem__(self, key):
return dict(self._fields2)[key]
def __contains__(self, key):
return key in dict(self._fields2)
def iteritems(self):
return dict(self._fields2).iteritems()
def get(self, key, default=None):
return dict(self._fields2).get(key, default)
def stringify_attrs(self):
yield "oxm_fields", dict(self._fields2)
def to_jsondict(self):
"""
Returns a dict expressing the flow match.
"""
# XXX old api compat
if self._composed_with_old_api():
# copy object first because serialize_old is destructive
o2 = OFPMatch()
o2.fields = self.fields[:]
# serialize and parse to fill OFPMatch._fields2
buf = bytearray()
o2.serialize(buf, 0)
o = OFPMatch.parser(str(buf), 0)
else:
o = self
body = {"oxm_fields": [ofproto_v1_3.oxm_to_jsondict(k, uv) for k, uv
in o._fields2],
"length": o.length,
"type": o.type}
return {self.__class__.__name__: body}
@classmethod
def from_jsondict(cls, dict_):
"""
Returns an object which is generated from a dict.
Exception raises:
KeyError -- Unknown match field is defined in dict
"""
fields = [ofproto_v1_3.oxm_from_jsondict(f) for f
in dict_['oxm_fields']]
o = OFPMatch(_ordered_fields=fields)
# XXX old api compat
# serialize and parse to fill OFPMatch.fields
buf = bytearray()
o.serialize(buf, 0)
return OFPMatch.parser(str(buf), 0)
def __str__(self):
# XXX old api compat
if self._composed_with_old_api():
# copy object first because serialize_old is destructive
o2 = OFPMatch()
o2.fields = self.fields[:]
# serialize and parse to fill OFPMatch._fields2
buf = bytearray()
o2.serialize(buf, 0)
o = OFPMatch.parser(str(buf), 0)
else:
o = self
return super(OFPMatch, o).__str__()
__repr__ = __str__
def append_field(self, header, value, mask=None):
"""
Append a match field.
========= =======================================================
Argument Description
========= =======================================================
header match field header ID which is defined automatically in
``ofproto_v1_3``
value match field value
mask mask value to the match field
========= =======================================================
The available ``header`` is as follows.
====================== ===================================
Header ID Description
====================== ===================================
OXM_OF_IN_PORT Switch input port
OXM_OF_IN_PHY_PORT Switch physical input port
OXM_OF_METADATA Metadata passed between tables
OXM_OF_ETH_DST Ethernet destination address
OXM_OF_ETH_SRC Ethernet source address
OXM_OF_ETH_TYPE Ethernet frame type
OXM_OF_VLAN_VID VLAN id
OXM_OF_VLAN_PCP VLAN priority
OXM_OF_IP_DSCP IP DSCP (6 bits in ToS field)
OXM_OF_IP_ECN IP ECN (2 bits in ToS field)
OXM_OF_IP_PROTO IP protocol
OXM_OF_IPV4_SRC IPv4 source address
OXM_OF_IPV4_DST IPv4 destination address
OXM_OF_TCP_SRC TCP source port
OXM_OF_TCP_DST TCP destination port
OXM_OF_UDP_SRC UDP source port
OXM_OF_UDP_DST UDP destination port
OXM_OF_SCTP_SRC SCTP source port
OXM_OF_SCTP_DST SCTP destination port
OXM_OF_ICMPV4_TYPE ICMP type
OXM_OF_ICMPV4_CODE ICMP code
OXM_OF_ARP_OP ARP opcode
OXM_OF_ARP_SPA ARP source IPv4 address
OXM_OF_ARP_TPA ARP target IPv4 address
OXM_OF_ARP_SHA ARP source hardware address
OXM_OF_ARP_THA ARP target hardware address
OXM_OF_IPV6_SRC IPv6 source address
OXM_OF_IPV6_DST IPv6 destination address
OXM_OF_IPV6_FLABEL IPv6 Flow Label
OXM_OF_ICMPV6_TYPE ICMPv6 type
OXM_OF_ICMPV6_CODE ICMPv6 code
OXM_OF_IPV6_ND_TARGET Target address for ND
OXM_OF_IPV6_ND_SLL Source link-layer for ND
OXM_OF_IPV6_ND_TLL Target link-layer for ND
OXM_OF_MPLS_LABEL MPLS label
OXM_OF_MPLS_TC MPLS TC
OXM_OF_MPLS_BOS MPLS BoS bit
OXM_OF_PBB_ISID PBB I-SID
OXM_OF_TUNNEL_ID Logical Port Metadata
OXM_OF_IPV6_EXTHDR IPv6 Extension Header pseudo-field
====================== ===================================
"""
self.fields.append(OFPMatchField.make(header, value, mask))
def _composed_with_old_api(self):
return (self.fields and not self._fields2) or \
self._wc.__dict__ != FlowWildcards().__dict__
def serialize(self, buf, offset):
"""
Outputs the expression of the wire protocol of the flow match into
the buf.
Returns the output length.
"""
# XXX compat
if self._composed_with_old_api():
return self.serialize_old(buf, offset)
fields = [ofproto_v1_3.oxm_from_user(k, uv) for (k, uv)
in self._fields2]
hdr_pack_str = '!HH'
field_offset = offset + struct.calcsize(hdr_pack_str)
for (n, value, mask) in fields:
field_offset += ofproto_v1_3.oxm_serialize(n, value, mask, buf,
field_offset)
length = field_offset - offset
msg_pack_into(hdr_pack_str, buf, offset,
ofproto_v1_3.OFPMT_OXM, length)
self.length = length
pad_len = utils.round_up(length, 8) - length
ofproto_parser.msg_pack_into("%dx" % pad_len, buf, field_offset)
return length + pad_len
def serialize_old(self, buf, offset):
if hasattr(self, '_serialized'):
raise Exception('serializing an OFPMatch composed with '
'old API multiple times is not supported')
self._serialized = True
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IN_PORT):
self.append_field(ofproto_v1_3.OXM_OF_IN_PORT,
self._flow.in_port)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IN_PHY_PORT):
self.append_field(ofproto_v1_3.OXM_OF_IN_PHY_PORT,
self._flow.in_phy_port)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_METADATA):
if self._wc.metadata_mask == UINT64_MAX:
header = ofproto_v1_3.OXM_OF_METADATA
else:
header = ofproto_v1_3.OXM_OF_METADATA_W
self.append_field(header, self._flow.metadata,
self._wc.metadata_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ETH_DST):
if self._wc.dl_dst_mask:
header = ofproto_v1_3.OXM_OF_ETH_DST_W
else:
header = ofproto_v1_3.OXM_OF_ETH_DST
self.append_field(header, self._flow.dl_dst, self._wc.dl_dst_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ETH_SRC):
if self._wc.dl_src_mask:
header = ofproto_v1_3.OXM_OF_ETH_SRC_W
else:
header = ofproto_v1_3.OXM_OF_ETH_SRC
self.append_field(header, self._flow.dl_src, self._wc.dl_src_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ETH_TYPE):
self.append_field(ofproto_v1_3.OXM_OF_ETH_TYPE, self._flow.dl_type)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_VLAN_VID):
if self._wc.vlan_vid_mask == UINT16_MAX:
header = ofproto_v1_3.OXM_OF_VLAN_VID
else:
header = ofproto_v1_3.OXM_OF_VLAN_VID_W
self.append_field(header, self._flow.vlan_vid,
self._wc.vlan_vid_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_VLAN_PCP):
self.append_field(ofproto_v1_3.OXM_OF_VLAN_PCP,
self._flow.vlan_pcp)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IP_DSCP):
self.append_field(ofproto_v1_3.OXM_OF_IP_DSCP, self._flow.ip_dscp)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IP_ECN):
self.append_field(ofproto_v1_3.OXM_OF_IP_ECN, self._flow.ip_ecn)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IP_PROTO):
self.append_field(ofproto_v1_3.OXM_OF_IP_PROTO,
self._flow.ip_proto)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IPV4_SRC):
if self._wc.ipv4_src_mask == UINT32_MAX:
header = ofproto_v1_3.OXM_OF_IPV4_SRC
else:
header = ofproto_v1_3.OXM_OF_IPV4_SRC_W
self.append_field(header, self._flow.ipv4_src,
self._wc.ipv4_src_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IPV4_DST):
if self._wc.ipv4_dst_mask == UINT32_MAX:
header = ofproto_v1_3.OXM_OF_IPV4_DST
else:
header = ofproto_v1_3.OXM_OF_IPV4_DST_W
self.append_field(header, self._flow.ipv4_dst,
self._wc.ipv4_dst_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_TCP_SRC):
self.append_field(ofproto_v1_3.OXM_OF_TCP_SRC, self._flow.tcp_src)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_TCP_DST):
self.append_field(ofproto_v1_3.OXM_OF_TCP_DST, self._flow.tcp_dst)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_UDP_SRC):
self.append_field(ofproto_v1_3.OXM_OF_UDP_SRC, self._flow.udp_src)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_UDP_DST):
self.append_field(ofproto_v1_3.OXM_OF_UDP_DST, self._flow.udp_dst)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_SCTP_SRC):
self.append_field(ofproto_v1_3.OXM_OF_SCTP_SRC,
self._flow.sctp_src)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_SCTP_DST):
self.append_field(ofproto_v1_3.OXM_OF_SCTP_DST,
self._flow.sctp_dst)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ICMPV4_TYPE):
self.append_field(ofproto_v1_3.OXM_OF_ICMPV4_TYPE,
self._flow.icmpv4_type)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ICMPV4_CODE):
self.append_field(ofproto_v1_3.OXM_OF_ICMPV4_CODE,
self._flow.icmpv4_code)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ARP_OP):
self.append_field(ofproto_v1_3.OXM_OF_ARP_OP, self._flow.arp_op)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ARP_SPA):
if self._wc.arp_spa_mask == UINT32_MAX:
header = ofproto_v1_3.OXM_OF_ARP_SPA
else:
header = ofproto_v1_3.OXM_OF_ARP_SPA_W
self.append_field(header, self._flow.arp_spa,
self._wc.arp_spa_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ARP_TPA):
if self._wc.arp_tpa_mask == UINT32_MAX:
header = ofproto_v1_3.OXM_OF_ARP_TPA
else:
header = ofproto_v1_3.OXM_OF_ARP_TPA_W
self.append_field(header, self._flow.arp_tpa,
self._wc.arp_tpa_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ARP_SHA):
if self._wc.arp_sha_mask:
header = ofproto_v1_3.OXM_OF_ARP_SHA_W
else:
header = ofproto_v1_3.OXM_OF_ARP_SHA
self.append_field(header, self._flow.arp_sha,
self._wc.arp_sha_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ARP_THA):
if self._wc.arp_tha_mask:
header = ofproto_v1_3.OXM_OF_ARP_THA_W
else:
header = ofproto_v1_3.OXM_OF_ARP_THA
self.append_field(header, self._flow.arp_tha,
self._wc.arp_tha_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IPV6_SRC):
if len(self._wc.ipv6_src_mask):
header = ofproto_v1_3.OXM_OF_IPV6_SRC_W
else:
header = ofproto_v1_3.OXM_OF_IPV6_SRC
self.append_field(header, self._flow.ipv6_src,
self._wc.ipv6_src_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IPV6_DST):
if len(self._wc.ipv6_dst_mask):
header = ofproto_v1_3.OXM_OF_IPV6_DST_W
else:
header = ofproto_v1_3.OXM_OF_IPV6_DST
self.append_field(header, self._flow.ipv6_dst,
self._wc.ipv6_dst_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IPV6_FLABEL):
if self._wc.ipv6_flabel_mask == UINT32_MAX:
header = ofproto_v1_3.OXM_OF_IPV6_FLABEL
else:
header = ofproto_v1_3.OXM_OF_IPV6_FLABEL_W
self.append_field(header, self._flow.ipv6_flabel,
self._wc.ipv6_flabel_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ICMPV6_TYPE):
self.append_field(ofproto_v1_3.OXM_OF_ICMPV6_TYPE,
self._flow.icmpv6_type)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_ICMPV6_CODE):
self.append_field(ofproto_v1_3.OXM_OF_ICMPV6_CODE,
self._flow.icmpv6_code)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IPV6_ND_TARGET):
self.append_field(ofproto_v1_3.OXM_OF_IPV6_ND_TARGET,
self._flow.ipv6_nd_target)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IPV6_ND_SLL):
self.append_field(ofproto_v1_3.OXM_OF_IPV6_ND_SLL,
self._flow.ipv6_nd_sll)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IPV6_ND_TLL):
self.append_field(ofproto_v1_3.OXM_OF_IPV6_ND_TLL,
self._flow.ipv6_nd_tll)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_MPLS_LABEL):
self.append_field(ofproto_v1_3.OXM_OF_MPLS_LABEL,
self._flow.mpls_label)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_MPLS_TC):
self.append_field(ofproto_v1_3.OXM_OF_MPLS_TC,
self._flow.mpls_tc)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_MPLS_BOS):
self.append_field(ofproto_v1_3.OXM_OF_MPLS_BOS,
self._flow.mpls_bos)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_PBB_ISID):
if self._wc.pbb_isid_mask:
header = ofproto_v1_3.OXM_OF_PBB_ISID_W
else:
header = ofproto_v1_3.OXM_OF_PBB_ISID
self.append_field(header, self._flow.pbb_isid,
self._wc.pbb_isid_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_TUNNEL_ID):
if self._wc.tunnel_id_mask:
header = ofproto_v1_3.OXM_OF_TUNNEL_ID_W
else:
header = ofproto_v1_3.OXM_OF_TUNNEL_ID
self.append_field(header, self._flow.tunnel_id,
self._wc.tunnel_id_mask)
if self._wc.ft_test(ofproto_v1_3.OFPXMT_OFB_IPV6_EXTHDR):
if self._wc.ipv6_exthdr_mask:
header = ofproto_v1_3.OXM_OF_IPV6_EXTHDR_W
else:
header = ofproto_v1_3.OXM_OF_IPV6_EXTHDR
self.append_field(header, self._flow.ipv6_exthdr,
self._wc.ipv6_exthdr_mask)
field_offset = offset + 4
for f in self.fields:
f.serialize(buf, field_offset)
field_offset += f.length
length = field_offset - offset
msg_pack_into('!HH', buf, offset, ofproto_v1_3.OFPMT_OXM, length)
pad_len = utils.round_up(length, 8) - length
ofproto_parser.msg_pack_into("%dx" % pad_len, buf, field_offset)
return length + pad_len
@classmethod
def parser(cls, buf, offset):
"""
Returns an object which is generated from a buffer including the
expression of the wire protocol of the flow match.
"""
match = OFPMatch()
type_, length = struct.unpack_from('!HH', buf, offset)
match.type = type_
match.length = length
# ofp_match adjustment
offset += 4
length -= 4
# XXXcompat
cls.parser_old(match, buf, offset, length)
fields = []
while length > 0:
n, value, mask, field_len = ofproto_v1_3.oxm_parse(buf, offset)
k, uv = ofproto_v1_3.oxm_to_user(n, value, mask)
fields.append((k, uv))
offset += field_len
length -= field_len
match._fields2 = fields
return match
@staticmethod
def parser_old(match, buf, offset, length):
while length > 0:
field = OFPMatchField.parser(buf, offset)
offset += field.length
length -= field.length
match.fields.append(field)
def set_in_port(self, port):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IN_PORT)
self._flow.in_port = port
def set_in_phy_port(self, phy_port):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IN_PHY_PORT)
self._flow.in_phy_port = phy_port
def set_metadata(self, metadata):
self.set_metadata_masked(metadata, UINT64_MAX)
def set_metadata_masked(self, metadata, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_METADATA)
self._wc.metadata_mask = mask
self._flow.metadata = metadata & mask
def set_dl_dst(self, dl_dst):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ETH_DST)
self._flow.dl_dst = dl_dst
def set_dl_dst_masked(self, dl_dst, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ETH_DST)
self._wc.dl_dst_mask = mask
# bit-wise and of the corresponding elements of dl_dst and mask
self._flow.dl_dst = mac.haddr_bitand(dl_dst, mask)
def set_dl_src(self, dl_src):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ETH_SRC)
self._flow.dl_src = dl_src
def set_dl_src_masked(self, dl_src, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ETH_SRC)
self._wc.dl_src_mask = mask
self._flow.dl_src = mac.haddr_bitand(dl_src, mask)
def set_dl_type(self, dl_type):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ETH_TYPE)
self._flow.dl_type = dl_type
def set_vlan_vid(self, vid):
self.set_vlan_vid_masked(vid, UINT16_MAX)
def set_vlan_vid_masked(self, vid, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_VLAN_VID)
self._wc.vlan_vid_mask = mask
self._flow.vlan_vid = vid
def set_vlan_pcp(self, pcp):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_VLAN_PCP)
self._flow.vlan_pcp = pcp
def set_ip_dscp(self, ip_dscp):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IP_DSCP)
self._flow.ip_dscp = ip_dscp
def set_ip_ecn(self, ip_ecn):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IP_ECN)
self._flow.ip_ecn = ip_ecn
def set_ip_proto(self, ip_proto):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IP_PROTO)
self._flow.ip_proto = ip_proto
def set_ipv4_src(self, ipv4_src):
self.set_ipv4_src_masked(ipv4_src, UINT32_MAX)
def set_ipv4_src_masked(self, ipv4_src, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV4_SRC)
self._flow.ipv4_src = ipv4_src
self._wc.ipv4_src_mask = mask
def set_ipv4_dst(self, ipv4_dst):
self.set_ipv4_dst_masked(ipv4_dst, UINT32_MAX)
def set_ipv4_dst_masked(self, ipv4_dst, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV4_DST)
self._flow.ipv4_dst = ipv4_dst
self._wc.ipv4_dst_mask = mask
def set_tcp_src(self, tcp_src):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_TCP_SRC)
self._flow.tcp_src = tcp_src
def set_tcp_dst(self, tcp_dst):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_TCP_DST)
self._flow.tcp_dst = tcp_dst
def set_udp_src(self, udp_src):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_UDP_SRC)
self._flow.udp_src = udp_src
# FIXME:
# def set_ns_type(self, ns_type):
# self._wc.ft_set(ofproto_v1_3.OFPXMT_GPRS_NS_TYPE)
# self._flow.ns_type = ns_type
#
def set_udp_dst(self, udp_dst):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_UDP_DST)
self._flow.udp_dst = udp_dst
def set_sctp_src(self, sctp_src):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_SCTP_SRC)
self._flow.sctp_src = sctp_src
def set_sctp_dst(self, sctp_dst):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_SCTP_DST)
self._flow.sctp_dst = sctp_dst
def set_icmpv4_type(self, icmpv4_type):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ICMPV4_TYPE)
self._flow.icmpv4_type = icmpv4_type
def set_icmpv4_code(self, icmpv4_code):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ICMPV4_CODE)
self._flow.icmpv4_code = icmpv4_code
def set_arp_opcode(self, arp_op):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ARP_OP)
self._flow.arp_op = arp_op
def set_arp_spa(self, arp_spa):
self.set_arp_spa_masked(arp_spa, UINT32_MAX)
def set_arp_spa_masked(self, arp_spa, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ARP_SPA)
self._wc.arp_spa_mask = mask
self._flow.arp_spa = arp_spa
def set_arp_tpa(self, arp_tpa):
self.set_arp_tpa_masked(arp_tpa, UINT32_MAX)
def set_arp_tpa_masked(self, arp_tpa, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ARP_TPA)
self._wc.arp_tpa_mask = mask
self._flow.arp_tpa = arp_tpa
def set_arp_sha(self, arp_sha):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ARP_SHA)
self._flow.arp_sha = arp_sha
def set_arp_sha_masked(self, arp_sha, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ARP_SHA)
self._wc.arp_sha_mask = mask
self._flow.arp_sha = mac.haddr_bitand(arp_sha, mask)
def set_arp_tha(self, arp_tha):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ARP_THA)
self._flow.arp_tha = arp_tha
def set_arp_tha_masked(self, arp_tha, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ARP_THA)
self._wc.arp_tha_mask = mask
self._flow.arp_tha = mac.haddr_bitand(arp_tha, mask)
def set_ipv6_src(self, src):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_SRC)
self._flow.ipv6_src = src
def set_ipv6_src_masked(self, src, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_SRC)
self._wc.ipv6_src_mask = mask
self._flow.ipv6_src = [x & y for (x, y) in itertools.izip(src, mask)]
def set_ipv6_dst(self, dst):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_DST)
self._flow.ipv6_dst = dst
def set_ipv6_dst_masked(self, dst, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_DST)
self._wc.ipv6_dst_mask = mask
self._flow.ipv6_dst = [x & y for (x, y) in itertools.izip(dst, mask)]
def set_ipv6_flabel(self, flabel):
self.set_ipv6_flabel_masked(flabel, UINT32_MAX)
def set_ipv6_flabel_masked(self, flabel, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_FLABEL)
self._wc.ipv6_flabel_mask = mask
self._flow.ipv6_flabel = flabel
def set_icmpv6_type(self, icmpv6_type):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ICMPV6_TYPE)
self._flow.icmpv6_type = icmpv6_type
def set_icmpv6_code(self, icmpv6_code):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_ICMPV6_CODE)
self._flow.icmpv6_code = icmpv6_code
def set_ipv6_nd_target(self, target):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_ND_TARGET)
self._flow.ipv6_nd_target = target
def set_ipv6_nd_sll(self, ipv6_nd_sll):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_ND_SLL)
self._flow.ipv6_nd_sll = ipv6_nd_sll
def set_ipv6_nd_tll(self, ipv6_nd_tll):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_ND_TLL)
self._flow.ipv6_nd_tll = ipv6_nd_tll
def set_mpls_label(self, mpls_label):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_MPLS_LABEL)
self._flow.mpls_label = mpls_label
def set_mpls_tc(self, mpls_tc):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_MPLS_TC)
self._flow.mpls_tc = mpls_tc
def set_mpls_bos(self, bos):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_MPLS_BOS)
self._flow.mpls_bos = bos
def set_pbb_isid(self, isid):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_PBB_ISID)
self._flow.pbb_isid = isid
def set_pbb_isid_masked(self, isid, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_PBB_ISID)
self._wc.pbb_isid_mask = mask
self._flow.pbb_isid = isid
def set_tunnel_id(self, tunnel_id):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_TUNNEL_ID)
self._flow.tunnel_id = tunnel_id
def set_tunnel_id_masked(self, tunnel_id, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_TUNNEL_ID)
self._wc.tunnel_id_mask = mask
self._flow.tunnel_id = tunnel_id
def set_ipv6_exthdr(self, hdr):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_EXTHDR)
self._flow.ipv6_exthdr = hdr
def set_ipv6_exthdr_masked(self, hdr, mask):
self._wc.ft_set(ofproto_v1_3.OFPXMT_OFB_IPV6_EXTHDR)
self._wc.ipv6_exthdr_mask = mask
self._flow.ipv6_exthdr = hdr
class OFPMatchField(StringifyMixin):
_FIELDS_HEADERS = {}
@staticmethod
def register_field_header(headers):
def _register_field_header(cls):
for header in headers:
OFPMatchField._FIELDS_HEADERS[header] = cls
return cls
return _register_field_header
def __init__(self, header):
self.header = header
self.n_bytes = ofproto_v1_3.oxm_tlv_header_extract_length(header)
self.length = 0
@classmethod
def cls_to_header(cls, cls_, hasmask):
# XXX efficiency
inv = dict((v, k) for k, v in cls._FIELDS_HEADERS.iteritems()
if (((k >> 8) & 1) != 0) == hasmask)
return inv[cls_]
@staticmethod
def make(header, value, mask=None):
cls_ = OFPMatchField._FIELDS_HEADERS.get(header)
return cls_(header, value, mask)
@classmethod
def parser(cls, buf, offset):
(header,) = struct.unpack_from('!I', buf, offset)
cls_ = OFPMatchField._FIELDS_HEADERS.get(header)
if cls_:
field = cls_.field_parser(header, buf, offset)
else:
field = OFPMatchField(header)
field.length = (header & 0xff) + 4
return field
@classmethod
def field_parser(cls, header, buf, offset):
hasmask = (header >> 8) & 1
mask = None
if ofproto_v1_3.oxm_tlv_header_extract_hasmask(header):
pack_str = '!' + cls.pack_str[1:] * 2
(value, mask) = struct.unpack_from(pack_str, buf, offset + 4)
else:
(value,) = struct.unpack_from(cls.pack_str, buf, offset + 4)
return cls(header, value, mask)
def serialize(self, buf, offset):
if ofproto_v1_3.oxm_tlv_header_extract_hasmask(self.header):
self.put_w(buf, offset, self.value, self.mask)
else:
self.put(buf, offset, self.value)
def _put_header(self, buf, offset):
ofproto_parser.msg_pack_into('!I', buf, offset, self.header)
self.length = 4
def _put(self, buf, offset, value):
ofproto_parser.msg_pack_into(self.pack_str, buf, offset, value)
self.length += self.n_bytes
def put_w(self, buf, offset, value, mask):
self._put_header(buf, offset)
self._put(buf, offset + self.length, value)
self._put(buf, offset + self.length, mask)
def put(self, buf, offset, value):
self._put_header(buf, offset)
self._put(buf, offset + self.length, value)
def _putv6(self, buf, offset, value):
ofproto_parser.msg_pack_into(self.pack_str, buf, offset,
*value)
self.length += self.n_bytes
def putv6(self, buf, offset, value, mask=None):
self._put_header(buf, offset)
self._putv6(buf, offset + self.length, value)
if mask and len(mask):
self._putv6(buf, offset + self.length, mask)
def oxm_len(self):
return self.header & 0xff
def to_jsondict(self):
# remove some redundant attributes
d = super(OFPMatchField, self).to_jsondict()
v = d[self.__class__.__name__]
del v['header']
del v['length']
del v['n_bytes']
return d
@classmethod
def from_jsondict(cls, dict_):
# just pass the dict around.
# it will be converted by OFPMatch.__init__().
return {cls.__name__: dict_}
def stringify_attrs(self):
f = super(OFPMatchField, self).stringify_attrs
if not ofproto_v1_3.oxm_tlv_header_extract_hasmask(self.header):
# something like the following, but yield two values (k,v)
# return itertools.ifilter(lambda k, v: k != 'mask', iter())
def g():
for k, v in f():
if k != 'mask':
yield (k, v)
return g()
else:
return f()
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IN_PORT])
class MTInPort(OFPMatchField):
pack_str = '!I'
def __init__(self, header, value, mask=None):
super(MTInPort, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_METADATA,
ofproto_v1_3.OXM_OF_METADATA_W])
class MTMetadata(OFPMatchField):
pack_str = '!Q'
def __init__(self, header, value, mask=None):
super(MTMetadata, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IN_PHY_PORT])
class MTInPhyPort(OFPMatchField):
pack_str = '!I'
def __init__(self, header, value, mask=None):
super(MTInPhyPort, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ETH_DST,
ofproto_v1_3.OXM_OF_ETH_DST_W])
class MTEthDst(OFPMatchField):
pack_str = '!6s'
def __init__(self, header, value, mask=None):
super(MTEthDst, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ETH_SRC,
ofproto_v1_3.OXM_OF_ETH_SRC_W])
class MTEthSrc(OFPMatchField):
pack_str = '!6s'
def __init__(self, header, value, mask=None):
super(MTEthSrc, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ETH_TYPE])
class MTEthType(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTEthType, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_VLAN_VID,
ofproto_v1_3.OXM_OF_VLAN_VID_W])
class MTVlanVid(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTVlanVid, self).__init__(header)
self.value = value
self.mask = mask
@classmethod
def field_parser(cls, header, buf, offset):
m = super(MTVlanVid, cls).field_parser(header, buf, offset)
m.value &= ~ofproto_v1_3.OFPVID_PRESENT
return m
def serialize(self, buf, offset):
self.value |= ofproto_v1_3.OFPVID_PRESENT
super(MTVlanVid, self).serialize(buf, offset)
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_VLAN_PCP])
class MTVlanPcp(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTVlanPcp, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IP_DSCP])
class MTIPDscp(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTIPDscp, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IP_ECN])
class MTIPECN(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTIPECN, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IP_PROTO])
class MTIPProto(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTIPProto, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IPV4_SRC,
ofproto_v1_3.OXM_OF_IPV4_SRC_W])
class MTIPV4Src(OFPMatchField):
pack_str = '!I'
def __init__(self, header, value, mask=None):
super(MTIPV4Src, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IPV4_DST,
ofproto_v1_3.OXM_OF_IPV4_DST_W])
class MTIPV4Dst(OFPMatchField):
pack_str = '!I'
def __init__(self, header, value, mask=None):
super(MTIPV4Dst, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_TCP_SRC])
class MTTCPSrc(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTTCPSrc, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_TCP_DST])
class MTTCPDst(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTTCPDst, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_UDP_SRC])
class MTUDPSrc(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTUDPSrc, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_UDP_DST])
class MTUDPDst(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTUDPDst, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_SCTP_SRC])
class MTSCTPSrc(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTSCTPSrc, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_SCTP_DST])
class MTSCTPDst(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTSCTPDst, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ICMPV4_TYPE])
class MTICMPV4Type(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTICMPV4Type, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ICMPV4_CODE])
class MTICMPV4Code(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTICMPV4Code, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ARP_OP])
class MTArpOp(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTArpOp, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ARP_SPA,
ofproto_v1_3.OXM_OF_ARP_SPA_W])
class MTArpSpa(OFPMatchField):
pack_str = '!I'
def __init__(self, header, value, mask=None):
super(MTArpSpa, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ARP_TPA,
ofproto_v1_3.OXM_OF_ARP_TPA_W])
class MTArpTpa(OFPMatchField):
pack_str = '!I'
def __init__(self, header, value, mask=None):
super(MTArpTpa, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ARP_SHA,
ofproto_v1_3.OXM_OF_ARP_SHA_W])
class MTArpSha(OFPMatchField):
pack_str = '!6s'
def __init__(self, header, value, mask=None):
super(MTArpSha, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ARP_THA,
ofproto_v1_3.OXM_OF_ARP_THA_W])
class MTArpTha(OFPMatchField):
pack_str = '!6s'
def __init__(self, header, value, mask=None):
super(MTArpTha, self).__init__(header)
self.value = value
self.mask = mask
class MTIPv6(StringifyMixin):
@classmethod
def field_parser(cls, header, buf, offset):
if ofproto_v1_3.oxm_tlv_header_extract_hasmask(header):
pack_str = '!' + cls.pack_str[1:] * 2
value = struct.unpack_from(pack_str, buf, offset + 4)
return cls(header, list(value[:8]), list(value[8:]))
else:
value = struct.unpack_from(cls.pack_str, buf, offset + 4)
return cls(header, list(value))
def serialize(self, buf, offset):
self.putv6(buf, offset, self.value, self.mask)
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IPV6_SRC,
ofproto_v1_3.OXM_OF_IPV6_SRC_W])
class MTIPv6Src(MTIPv6, OFPMatchField):
pack_str = '!8H'
def __init__(self, header, value, mask=None):
super(MTIPv6Src, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IPV6_DST,
ofproto_v1_3.OXM_OF_IPV6_DST_W])
class MTIPv6Dst(MTIPv6, OFPMatchField):
pack_str = '!8H'
def __init__(self, header, value, mask=None):
super(MTIPv6Dst, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IPV6_FLABEL,
ofproto_v1_3.OXM_OF_IPV6_FLABEL_W])
class MTIPv6Flabel(OFPMatchField):
pack_str = '!I'
def __init__(self, header, value, mask=None):
super(MTIPv6Flabel, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_MPLS_LABEL])
class MTMplsLabel(OFPMatchField):
pack_str = '!I'
def __init__(self, header, value, mask=None):
super(MTMplsLabel, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ICMPV6_TYPE])
class MTICMPV6Type(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTICMPV6Type, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_ICMPV6_CODE])
class MTICMPV6Code(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTICMPV6Code, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IPV6_ND_TARGET])
class MTIPv6NdTarget(MTIPv6, OFPMatchField):
pack_str = '!8H'
def __init__(self, header, value, mask=None):
super(MTIPv6NdTarget, self).__init__(header)
self.value = value
def serialize(self, buf, offset):
self.putv6(buf, offset, self.value)
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IPV6_ND_SLL])
class MTIPv6NdSll(OFPMatchField):
pack_str = '!6s'
def __init__(self, header, value, mask=None):
super(MTIPv6NdSll, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IPV6_ND_TLL])
class MTIPv6NdTll(OFPMatchField):
pack_str = '!6s'
def __init__(self, header, value, mask=None):
super(MTIPv6NdTll, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_MPLS_TC])
class MTMplsTc(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTMplsTc, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_MPLS_BOS])
class MTMplsBos(OFPMatchField):
pack_str = '!B'
def __init__(self, header, value, mask=None):
super(MTMplsBos, self).__init__(header)
self.value = value
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_PBB_ISID,
ofproto_v1_3.OXM_OF_PBB_ISID_W])
class MTPbbIsid(OFPMatchField):
pack_str = '!3B'
def __init__(self, header, value, mask=None):
super(MTPbbIsid, self).__init__(header)
self.value = value
self.mask = mask
@classmethod
def field_parser(cls, header, buf, offset):
hasmask = (header >> 8) & 1
mask = None
if ofproto_v1_3.oxm_tlv_header_extract_hasmask(header):
pack_str = '!' + cls.pack_str[1:] * 2
(v1, v2, v3, m1, m2, m3) = struct.unpack_from(pack_str, buf,
offset + 4)
value = v1 << 16 | v2 << 8 | v3
mask = m1 << 16 | m2 << 8 | m3
else:
(v1, v2, v3,) = struct.unpack_from(cls.pack_str, buf, offset + 4)
value = v1 << 16 | v2 << 8 | v3
return cls(header, value, mask)
def _put(self, buf, offset, value):
ofproto_parser.msg_pack_into(self.pack_str, buf, offset,
(value >> 16) & 0xff,
(value >> 8) & 0xff,
(value >> 0) & 0xff)
self.length += self.n_bytes
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_TUNNEL_ID,
ofproto_v1_3.OXM_OF_TUNNEL_ID_W])
class MTTunnelId(OFPMatchField):
pack_str = '!Q'
def __init__(self, header, value, mask=None):
super(MTTunnelId, self).__init__(header)
self.value = value
self.mask = mask
@OFPMatchField.register_field_header([ofproto_v1_3.OXM_OF_IPV6_EXTHDR,
ofproto_v1_3.OXM_OF_IPV6_EXTHDR_W])
class MTIPv6ExtHdr(OFPMatchField):
pack_str = '!H'
def __init__(self, header, value, mask=None):
super(MTIPv6ExtHdr, self).__init__(header)
self.value = value
self.mask = mask
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_PACKET_IN)
class OFPPacketIn(MsgBase):
"""
Packet-In message
The switch sends the packet that received to the controller by this
message.
============= =========================================================
Attribute Description
============= =========================================================
buffer_id ID assigned by datapath
total_len Full length of frame
reason Reason packet is being sent.
OFPR_NO_MATCH
OFPR_ACTION
OFPR_INVALID_TTL
table_id ID of the table that was looked up
cookie Cookie of the flow entry that was looked up
match Instance of ``OFPMatch``
data Ethernet frame
============= =========================================================
Example::
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def packet_in_handler(self, ev):
msg = ev.msg
ofp = dp.ofproto
if msg.reason == ofp.OFPR_NO_MATCH:
reason = 'NO MATCH'
elif msg.reason == ofp.OFPR_ACTION:
reason = 'ACTION'
elif msg.reason == ofp.OFPR_INVALID_TTL:
reason = 'INVALID TTL'
else:
reason = 'unknown'
self.logger.debug('OFPPacketIn received: '
'buffer_id=%x total_len=%d reason=%s '
'table_id=%d cookie=%d match=%s data=%s',
msg.buffer_id, msg.total_len, reason,
msg.table_id, msg.cookie, msg.match,
utils.hex_array(msg.data))
"""
def __init__(self, datapath, buffer_id=None, total_len=None, reason=None,
table_id=None, cookie=None, match=None, data=None):
super(OFPPacketIn, self).__init__(datapath)
self.buffer_id = buffer_id
self.total_len = total_len
self.reason = reason
self.table_id = table_id
self.cookie = cookie
self.match = match
self.data = data
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPPacketIn, cls).parser(datapath, version, msg_type,
msg_len, xid, buf)
(msg.buffer_id, msg.total_len, msg.reason,
msg.table_id, msg.cookie) = struct.unpack_from(
ofproto_v1_3.OFP_PACKET_IN_PACK_STR,
msg.buf, ofproto_v1_3.OFP_HEADER_SIZE)
msg.match = OFPMatch.parser(msg.buf, ofproto_v1_3.OFP_PACKET_IN_SIZE -
ofproto_v1_3.OFP_MATCH_SIZE)
match_len = utils.round_up(msg.match.length, 8)
msg.data = msg.buf[(ofproto_v1_3.OFP_PACKET_IN_SIZE -
ofproto_v1_3.OFP_MATCH_SIZE + match_len + 2):]
if msg.total_len < len(msg.data):
# discard padding for 8-byte alignment of OFP packet
msg.data = msg.data[:msg.total_len]
return msg
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_FLOW_REMOVED)
class OFPFlowRemoved(MsgBase):
"""
Flow removed message
When flow entries time out or are deleted, the switch notifies controller
with this message.
================ ======================================================
Attribute Description
================ ======================================================
cookie Opaque controller-issued identifier
priority Priority level of flow entry
reason One of the following values.
OFPRR_IDLE_TIMEOUT
OFPRR_HARD_TIMEOUT
OFPRR_DELETE
OFPRR_GROUP_DELETE
table_id ID of the table
duration_sec Time flow was alive in seconds
duration_nsec Time flow was alive in nanoseconds beyond duration_sec
idle_timeout Idle timeout from original flow mod
hard_timeout Hard timeout from original flow mod
packet_count Number of packets that was associated with the flow
byte_count Number of bytes that was associated with the flow
match Instance of ``OFPMatch``
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPFlowRemoved, MAIN_DISPATCHER)
def flow_removed_handler(self, ev):
msg = ev.msg
dp = msg.datapath
ofp = dp.ofproto
if msg.reason == ofp.OFPRR_IDLE_TIMEOUT:
reason = 'IDLE TIMEOUT'
elif msg.reason == ofp.OFPRR_HARD_TIMEOUT:
reason = 'HARD TIMEOUT'
elif msg.reason == ofp.OFPRR_DELETE:
reason = 'DELETE'
elif msg.reason == ofp.OFPRR_GROUP_DELETE:
reason = 'GROUP DELETE'
else:
reason = 'unknown'
self.logger.debug('OFPFlowRemoved received: '
'cookie=%d priority=%d reason=%s table_id=%d '
'duration_sec=%d duration_nsec=%d '
'idle_timeout=%d hard_timeout=%d '
'packet_count=%d byte_count=%d match.fields=%s',
msg.cookie, msg.priority, reason, msg.table_id,
msg.duration_sec, msg.duration_nsec,
msg.idle_timeout, msg.hard_timeout,
msg.packet_count, msg.byte_count, msg.match)
"""
def __init__(self, datapath, cookie=None, priority=None, reason=None,
table_id=None, duration_sec=None, duration_nsec=None,
idle_timeout=None, hard_timeout=None, packet_count=None,
byte_count=None, match=None):
super(OFPFlowRemoved, self).__init__(datapath)
self.cookie = cookie
self.priority = priority
self.reason = reason
self.table_id = table_id
self.duration_sec = duration_sec
self.duration_nsec = duration_nsec
self.idle_timeout = idle_timeout
self.hard_timeout = hard_timeout
self.packet_count = packet_count
self.byte_count = byte_count
self.match = match
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPFlowRemoved, cls).parser(datapath, version, msg_type,
msg_len, xid, buf)
(msg.cookie, msg.priority, msg.reason,
msg.table_id, msg.duration_sec, msg.duration_nsec,
msg.idle_timeout, msg.hard_timeout, msg.packet_count,
msg.byte_count) = struct.unpack_from(
ofproto_v1_3.OFP_FLOW_REMOVED_PACK_STR0,
msg.buf, ofproto_v1_3.OFP_HEADER_SIZE)
offset = (ofproto_v1_3.OFP_FLOW_REMOVED_SIZE -
ofproto_v1_3.OFP_MATCH_SIZE)
msg.match = OFPMatch.parser(msg.buf, offset)
return msg
class OFPPort(ofproto_parser.namedtuple('OFPPort', (
'port_no', 'hw_addr', 'name', 'config', 'state', 'curr',
'advertised', 'supported', 'peer', 'curr_speed', 'max_speed'))):
_TYPE = {
'ascii': [
'hw_addr',
],
'utf-8': [
# OF spec is unclear about the encoding of name.
# we assumes UTF-8, which is used by OVS.
'name',
]
}
@classmethod
def parser(cls, buf, offset):
port = struct.unpack_from(ofproto_v1_3.OFP_PORT_PACK_STR, buf, offset)
port = list(port)
i = cls._fields.index('hw_addr')
port[i] = addrconv.mac.bin_to_text(port[i])
i = cls._fields.index('name')
port[i] = port[i].rstrip('\0')
ofpport = cls(*port)
ofpport.length = ofproto_v1_3.OFP_PORT_SIZE
return ofpport
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_PORT_STATUS)
class OFPPortStatus(MsgBase):
"""
Port status message
The switch notifies controller of change of ports.
================ ======================================================
Attribute Description
================ ======================================================
reason One of the following values.
OFPPR_ADD
OFPPR_DELETE
OFPPR_MODIFY
desc instance of ``OFPPort``
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPPortStatus, MAIN_DISPATCHER)
def port_status_handler(self, ev):
msg = ev.msg
dp = msg.datapath
ofp = dp.ofproto
if msg.reason == ofp.OFPPR_ADD:
reason = 'ADD'
elif msg.reason == ofp.OFPPR_DELETE:
reason = 'DELETE'
elif msg.reason == ofp.OFPPR_MODIFY:
reason = 'MODIFY'
else:
reason = 'unknown'
self.logger.debug('OFPPortStatus received: reason=%s desc=%s',
reason, msg.desc)
"""
def __init__(self, datapath, reason=None, desc=None):
super(OFPPortStatus, self).__init__(datapath)
self.reason = reason
self.desc = desc
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPPortStatus, cls).parser(datapath, version, msg_type,
msg_len, xid, buf)
msg.reason = struct.unpack_from(
ofproto_v1_3.OFP_PORT_STATUS_PACK_STR, msg.buf,
ofproto_v1_3.OFP_HEADER_SIZE)[0]
msg.desc = OFPPort.parser(msg.buf,
ofproto_v1_3.OFP_PORT_STATUS_DESC_OFFSET)
return msg
@_set_msg_type(ofproto_v1_3.OFPT_PACKET_OUT)
class OFPPacketOut(MsgBase):
"""
Packet-Out message
The controller uses this message to send a packet out throught the
switch.
================ ======================================================
Attribute Description
================ ======================================================
buffer_id ID assigned by datapath (OFP_NO_BUFFER if none)
in_port Packet's input port or ``OFPP_CONTROLLER``
actions list of OpenFlow action class
data Packet data
================ ======================================================
Example::
def send_packet_out(self, datapath, buffer_id, in_port):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
actions = [ofp_parser.OFPActionOutput(ofp.OFPP_FLOOD, 0)]
req = ofp_parser.OFPPacketOut(datapath, buffer_id,
in_port, actions)
datapath.send_msg(req)
"""
def __init__(self, datapath, buffer_id=None, in_port=None, actions=None,
data=None, actions_len=None):
assert in_port is not None
super(OFPPacketOut, self).__init__(datapath)
self.buffer_id = buffer_id
self.in_port = in_port
self.actions_len = 0
self.actions = actions
self.data = data
def _serialize_body(self):
self.actions_len = 0
offset = ofproto_v1_3.OFP_PACKET_OUT_SIZE
for a in self.actions:
a.serialize(self.buf, offset)
offset += a.len
self.actions_len += a.len
if self.data is not None:
assert self.buffer_id == 0xffffffff
self.buf += self.data
msg_pack_into(ofproto_v1_3.OFP_PACKET_OUT_PACK_STR,
self.buf, ofproto_v1_3.OFP_HEADER_SIZE,
self.buffer_id, self.in_port, self.actions_len)
@_set_msg_type(ofproto_v1_3.OFPT_FLOW_MOD)
class OFPFlowMod(MsgBase):
"""
Modify Flow entry message
The controller sends this message to modify the flow table.
================ ======================================================
Attribute Description
================ ======================================================
cookie Opaque controller-issued identifier
cookie_mask Mask used to restrict the cookie bits that must match
when the command is ``OPFFC_MODIFY*`` or
``OFPFC_DELETE*``
table_id ID of the table to put the flow in
command One of the following values.
OFPFC_ADD
OFPFC_MODIFY
OFPFC_MODIFY_STRICT
OFPFC_DELETE
OFPFC_DELETE_STRICT
idle_timeout Idle time before discarding (seconds)
hard_timeout Max time before discarding (seconds)
priority Priority level of flow entry
buffer_id Buffered packet to apply to (or OFP_NO_BUFFER)
out_port For ``OFPFC_DELETE*`` commands, require matching
entries to include this as an output port
out_group For ``OFPFC_DELETE*`` commands, require matching
entries to include this as an output group
flags One of the following values.
OFPFF_SEND_FLOW_REM
OFPFF_CHECK_OVERLAP
OFPFF_RESET_COUNTS
OFPFF_NO_PKT_COUNTS
OFPFF_NO_BYT_COUNTS
match Instance of ``OFPMatch``
instructions list of ``OFPInstruction*`` instance
================ ======================================================
Example::
def send_flow_mod(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
cookie = cookie_mask = 0
table_id = 0
idle_timeout = hard_timeout = 0
priority = 32768
buffer_id = ofp.OFP_NO_BUFFER
match = ofp_parser.OFPMatch(in_port=1, eth_dst='ff:ff:ff:ff:ff:ff')
actions = [ofp_parser.OFPActionOutput(ofp.OFPP_NORMAL, 0)]
inst = [ofp_parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS,
actions)]
req = ofp_parser.OFPFlowMod(datapath, cookie, cookie_mask,
table_id, ofp.OFPFC_ADD,
idle_timeout, hard_timeout,
priority, buffer_id,
ofp.OFPP_ANY, ofp.OFPG_ANY,
ofp.OFPFF_SEND_FLOW_REM,
match, inst)
datapath.send_msg(req)
"""
def __init__(self, datapath, cookie=0, cookie_mask=0, table_id=0,
command=ofproto_v1_3.OFPFC_ADD,
idle_timeout=0, hard_timeout=0, priority=0,
buffer_id=ofproto_v1_3.OFP_NO_BUFFER,
out_port=0, out_group=0, flags=0,
match=None,
instructions=[]):
super(OFPFlowMod, self).__init__(datapath)
self.cookie = cookie
self.cookie_mask = cookie_mask
self.table_id = table_id
self.command = command
self.idle_timeout = idle_timeout
self.hard_timeout = hard_timeout
self.priority = priority
self.buffer_id = buffer_id
self.out_port = out_port
self.out_group = out_group
self.flags = flags
if match is None:
match = OFPMatch()
self.match = match
self.instructions = instructions
def _serialize_body(self):
msg_pack_into(ofproto_v1_3.OFP_FLOW_MOD_PACK_STR0, self.buf,
ofproto_v1_3.OFP_HEADER_SIZE,
self.cookie, self.cookie_mask, self.table_id,
self.command, self.idle_timeout, self.hard_timeout,
self.priority, self.buffer_id, self.out_port,
self.out_group, self.flags)
offset = (ofproto_v1_3.OFP_FLOW_MOD_SIZE -
ofproto_v1_3.OFP_MATCH_SIZE)
match_len = self.match.serialize(self.buf, offset)
offset += match_len
for inst in self.instructions:
inst.serialize(self.buf, offset)
offset += inst.len
class OFPInstruction(object):
_INSTRUCTION_TYPES = {}
@staticmethod
def register_instruction_type(types):
def _register_instruction_type(cls):
for type_ in types:
OFPInstruction._INSTRUCTION_TYPES[type_] = cls
return cls
return _register_instruction_type
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from('!HH', buf, offset)
cls_ = cls._INSTRUCTION_TYPES.get(type_)
return cls_.parser(buf, offset)
@OFPInstruction.register_instruction_type([ofproto_v1_3.OFPIT_GOTO_TABLE])
class OFPInstructionGotoTable(StringifyMixin):
"""
Goto table instruction
This instruction indicates the next table in the processing pipeline.
================ ======================================================
Attribute Description
================ ======================================================
table_id Next table
================ ======================================================
"""
def __init__(self, table_id, type_=None, len_=None):
super(OFPInstructionGotoTable, self).__init__()
self.type = ofproto_v1_3.OFPIT_GOTO_TABLE
self.len = ofproto_v1_3.OFP_INSTRUCTION_GOTO_TABLE_SIZE
self.table_id = table_id
@classmethod
def parser(cls, buf, offset):
(type_, len_, table_id) = struct.unpack_from(
ofproto_v1_3.OFP_INSTRUCTION_GOTO_TABLE_PACK_STR,
buf, offset)
return cls(table_id)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_INSTRUCTION_GOTO_TABLE_PACK_STR,
buf, offset, self.type, self.len, self.table_id)
@OFPInstruction.register_instruction_type([ofproto_v1_3.OFPIT_WRITE_METADATA])
class OFPInstructionWriteMetadata(StringifyMixin):
"""
Write metadata instruction
This instruction writes the masked metadata value into the metadata field.
================ ======================================================
Attribute Description
================ ======================================================
metadata Metadata value to write
metadata_mask Metadata write bitmask
================ ======================================================
"""
def __init__(self, metadata, metadata_mask, len_=None):
super(OFPInstructionWriteMetadata, self).__init__()
self.type = ofproto_v1_3.OFPIT_WRITE_METADATA
self.len = ofproto_v1_3.OFP_INSTRUCTION_WRITE_METADATA_SIZE
self.metadata = metadata
self.metadata_mask = metadata_mask
@classmethod
def parser(cls, buf, offset):
(type_, len_, metadata, metadata_mask) = struct.unpack_from(
ofproto_v1_3.OFP_INSTRUCTION_WRITE_METADATA_PACK_STR,
buf, offset)
return cls(metadata, metadata_mask)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_INSTRUCTION_WRITE_METADATA_PACK_STR,
buf, offset, self.type, self.len, self.metadata,
self.metadata_mask)
@OFPInstruction.register_instruction_type([ofproto_v1_3.OFPIT_WRITE_ACTIONS,
ofproto_v1_3.OFPIT_APPLY_ACTIONS,
ofproto_v1_3.OFPIT_CLEAR_ACTIONS])
class OFPInstructionActions(StringifyMixin):
"""
Actions instruction
This instruction writes/applies/clears the actions.
================ ======================================================
Attribute Description
================ ======================================================
type One of following values.
OFPIT_WRITE_ACTIONS
OFPIT_APPLY_ACTIONS
OFPIT_CLEAR_ACTIONS
actions list of OpenFlow action class
================ ======================================================
``type`` attribute corresponds to ``type_`` parameter of __init__.
"""
def __init__(self, type_, actions=None, len_=None):
super(OFPInstructionActions, self).__init__()
self.type = type_
self.actions = actions
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_INSTRUCTION_ACTIONS_PACK_STR,
buf, offset)
offset += ofproto_v1_3.OFP_INSTRUCTION_ACTIONS_SIZE
actions = []
actions_len = len_ - ofproto_v1_3.OFP_INSTRUCTION_ACTIONS_SIZE
while actions_len > 0:
a = OFPAction.parser(buf, offset)
actions.append(a)
actions_len -= a.len
offset += a.len
inst = cls(type_, actions)
inst.len = len_
return inst
def serialize(self, buf, offset):
action_offset = offset + ofproto_v1_3.OFP_INSTRUCTION_ACTIONS_SIZE
if self.actions:
for a in self.actions:
a.serialize(buf, action_offset)
action_offset += a.len
self.len = action_offset - offset
pad_len = utils.round_up(self.len, 8) - self.len
ofproto_parser.msg_pack_into("%dx" % pad_len, buf, action_offset)
self.len += pad_len
msg_pack_into(ofproto_v1_3.OFP_INSTRUCTION_ACTIONS_PACK_STR,
buf, offset, self.type, self.len)
@OFPInstruction.register_instruction_type([ofproto_v1_3.OFPIT_METER])
class OFPInstructionMeter(StringifyMixin):
"""
Meter instruction
This instruction applies the meter.
================ ======================================================
Attribute Description
================ ======================================================
meter_id Meter instance
================ ======================================================
"""
_base_attributes = ['type', 'len']
def __init__(self, meter_id):
super(OFPInstructionMeter, self).__init__()
self.type = ofproto_v1_3.OFPIT_METER
self.len = ofproto_v1_3.OFP_INSTRUCTION_METER_SIZE
self.meter_id = meter_id
@classmethod
def parser(cls, buf, offset):
(type_, len_, meter_id) = struct.unpack_from(
ofproto_v1_3.OFP_INSTRUCTION_METER_PACK_STR,
buf, offset)
return cls(meter_id)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_INSTRUCTION_METER_PACK_STR,
buf, offset, self.type, self.len, self.meter_id)
class OFPActionHeader(StringifyMixin):
def __init__(self, type_, len_):
self.type = type_
self.len = len_
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_HEADER_PACK_STR,
buf, offset, self.type, self.len)
class OFPAction(OFPActionHeader):
_ACTION_TYPES = {}
@staticmethod
def register_action_type(type_, len_):
def _register_action_type(cls):
cls.cls_action_type = type_
cls.cls_action_len = len_
OFPAction._ACTION_TYPES[cls.cls_action_type] = cls
return cls
return _register_action_type
def __init__(self):
cls = self.__class__
super(OFPAction, self).__init__(cls.cls_action_type,
cls.cls_action_len)
@classmethod
def parser(cls, buf, offset):
type_, len_ = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_HEADER_PACK_STR, buf, offset)
cls_ = cls._ACTION_TYPES.get(type_)
assert cls_ is not None
return cls_.parser(buf, offset)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_OUTPUT,
ofproto_v1_3.OFP_ACTION_OUTPUT_SIZE)
class OFPActionOutput(OFPAction):
"""
Output action
This action indicates output a packet to the switch port.
================ ======================================================
Attribute Description
================ ======================================================
port Output port
max_len Max length to send to controller
================ ======================================================
"""
def __init__(self, port, max_len=ofproto_v1_3.OFPCML_MAX,
type_=None, len_=None):
super(OFPActionOutput, self).__init__()
self.port = port
self.max_len = max_len
@classmethod
def parser(cls, buf, offset):
type_, len_, port, max_len = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_OUTPUT_PACK_STR, buf, offset)
return cls(port, max_len)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_OUTPUT_PACK_STR, buf,
offset, self.type, self.len, self.port, self.max_len)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_GROUP,
ofproto_v1_3.OFP_ACTION_GROUP_SIZE)
class OFPActionGroup(OFPAction):
"""
Group action
This action indicates the group used to process the packet.
================ ======================================================
Attribute Description
================ ======================================================
group_id Group identifier
================ ======================================================
"""
def __init__(self, group_id, type_=None, len_=None):
super(OFPActionGroup, self).__init__()
self.group_id = group_id
@classmethod
def parser(cls, buf, offset):
(type_, len_, group_id) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_GROUP_PACK_STR, buf, offset)
return cls(group_id)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_GROUP_PACK_STR, buf,
offset, self.type, self.len, self.group_id)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_SET_QUEUE,
ofproto_v1_3.OFP_ACTION_SET_QUEUE_SIZE)
class OFPActionSetQueue(OFPAction):
"""
Set queue action
This action sets the queue id that will be used to map a flow to an
already-configured queue on a port.
================ ======================================================
Attribute Description
================ ======================================================
queue_id Queue ID for the packets
================ ======================================================
"""
def __init__(self, queue_id, type_=None, len_=None):
super(OFPActionSetQueue, self).__init__()
self.queue_id = queue_id
@classmethod
def parser(cls, buf, offset):
(type_, len_, queue_id) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_SET_QUEUE_PACK_STR, buf, offset)
return cls(queue_id)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_SET_QUEUE_PACK_STR, buf,
offset, self.type, self.len, self.queue_id)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_SET_MPLS_TTL,
ofproto_v1_3.OFP_ACTION_MPLS_TTL_SIZE)
class OFPActionSetMplsTtl(OFPAction):
"""
Set MPLS TTL action
This action sets the MPLS TTL.
================ ======================================================
Attribute Description
================ ======================================================
mpls_ttl MPLS TTL
================ ======================================================
"""
def __init__(self, mpls_ttl, type_=None, len_=None):
super(OFPActionSetMplsTtl, self).__init__()
self.mpls_ttl = mpls_ttl
@classmethod
def parser(cls, buf, offset):
(type_, len_, mpls_ttl) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_MPLS_TTL_PACK_STR, buf, offset)
return cls(mpls_ttl)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_MPLS_TTL_PACK_STR, buf,
offset, self.type, self.len, self.mpls_ttl)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_DEC_MPLS_TTL,
ofproto_v1_3.OFP_ACTION_HEADER_SIZE)
class OFPActionDecMplsTtl(OFPAction):
"""
Decrement MPLS TTL action
This action decrements the MPLS TTL.
"""
def __init__(self, type_=None, len_=None):
super(OFPActionDecMplsTtl, self).__init__()
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_HEADER_PACK_STR, buf, offset)
return cls()
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_SET_NW_TTL,
ofproto_v1_3.OFP_ACTION_NW_TTL_SIZE)
class OFPActionSetNwTtl(OFPAction):
"""
Set IP TTL action
This action sets the IP TTL.
================ ======================================================
Attribute Description
================ ======================================================
nw_ttl IP TTL
================ ======================================================
"""
def __init__(self, nw_ttl, type_=None, len_=None):
super(OFPActionSetNwTtl, self).__init__()
self.nw_ttl = nw_ttl
@classmethod
def parser(cls, buf, offset):
(type_, len_, nw_ttl) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_NW_TTL_PACK_STR, buf, offset)
return cls(nw_ttl)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_NW_TTL_PACK_STR, buf, offset,
self.type, self.len, self.nw_ttl)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_DEC_NW_TTL,
ofproto_v1_3.OFP_ACTION_HEADER_SIZE)
class OFPActionDecNwTtl(OFPAction):
"""
Decrement IP TTL action
This action decrements the IP TTL.
"""
def __init__(self, type_=None, len_=None):
super(OFPActionDecNwTtl, self).__init__()
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_HEADER_PACK_STR, buf, offset)
return cls()
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_COPY_TTL_OUT,
ofproto_v1_3.OFP_ACTION_HEADER_SIZE)
class OFPActionCopyTtlOut(OFPAction):
"""
Copy TTL Out action
This action copies the TTL from the next-to-outermost header with TTL to
the outermost header with TTL.
"""
def __init__(self, type_=None, len_=None):
super(OFPActionCopyTtlOut, self).__init__()
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_HEADER_PACK_STR, buf, offset)
return cls()
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_COPY_TTL_IN,
ofproto_v1_3.OFP_ACTION_HEADER_SIZE)
class OFPActionCopyTtlIn(OFPAction):
"""
Copy TTL In action
This action copies the TTL from the outermost header with TTL to the
next-to-outermost header with TTL.
"""
def __init__(self, type_=None, len_=None):
super(OFPActionCopyTtlIn, self).__init__()
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_HEADER_PACK_STR, buf, offset)
return cls()
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_PUSH_VLAN,
ofproto_v1_3.OFP_ACTION_PUSH_SIZE)
class OFPActionPushVlan(OFPAction):
"""
Push VLAN action
This action pushes a new VLAN tag to the packet.
================ ======================================================
Attribute Description
================ ======================================================
ethertype Ether type
================ ======================================================
"""
def __init__(self, ethertype, type_=None, len_=None):
super(OFPActionPushVlan, self).__init__()
self.ethertype = ethertype
@classmethod
def parser(cls, buf, offset):
(type_, len_, ethertype) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_PUSH_PACK_STR, buf, offset)
return cls(ethertype)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_PUSH_PACK_STR, buf, offset,
self.type, self.len, self.ethertype)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_PUSH_MPLS,
ofproto_v1_3.OFP_ACTION_PUSH_SIZE)
class OFPActionPushMpls(OFPAction):
"""
Push MPLS action
This action pushes a new MPLS header to the packet.
================ ======================================================
Attribute Description
================ ======================================================
ethertype Ether type
================ ======================================================
"""
def __init__(self, ethertype, type_=None, len_=None):
super(OFPActionPushMpls, self).__init__()
self.ethertype = ethertype
@classmethod
def parser(cls, buf, offset):
(type_, len_, ethertype) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_PUSH_PACK_STR, buf, offset)
return cls(ethertype)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_PUSH_PACK_STR, buf, offset,
self.type, self.len, self.ethertype)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_POP_VLAN,
ofproto_v1_3.OFP_ACTION_HEADER_SIZE)
class OFPActionPopVlan(OFPAction):
"""
Pop VLAN action
This action pops the outermost VLAN tag from the packet.
"""
def __init__(self, type_=None, len_=None):
super(OFPActionPopVlan, self).__init__()
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_HEADER_PACK_STR, buf, offset)
return cls()
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_POP_MPLS,
ofproto_v1_3.OFP_ACTION_POP_MPLS_SIZE)
class OFPActionPopMpls(OFPAction):
"""
Pop MPLS action
This action pops the MPLS header from the packet.
"""
def __init__(self, ethertype, type_=None, len_=None):
super(OFPActionPopMpls, self).__init__()
self.ethertype = ethertype
@classmethod
def parser(cls, buf, offset):
(type_, len_, ethertype) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_POP_MPLS_PACK_STR, buf, offset)
return cls(ethertype)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_POP_MPLS_PACK_STR, buf, offset,
self.type, self.len, self.ethertype)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_SET_FIELD,
ofproto_v1_3.OFP_ACTION_SET_FIELD_SIZE)
class OFPActionSetField(OFPAction):
"""
Set field action
This action modifies a header field in the packet.
================ ======================================================
Attribute Description
================ ======================================================
field Instance of ``OFPMatchField``
================ ======================================================
"""
def __init__(self, field=None, **kwargs):
# old api
# OFPActionSetField(field)
# new api
# OFPActionSetField(eth_src="00:00:00:00:00")
super(OFPActionSetField, self).__init__()
if isinstance(field, OFPMatchField):
# old api compat
assert len(kwargs) == 0
self.field = field
else:
# new api
assert len(kwargs) == 1
key = kwargs.keys()[0]
value = kwargs[key]
assert isinstance(key, (str, unicode))
assert not isinstance(value, tuple) # no mask
self.key = key
self.value = value
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_SET_FIELD_PACK_STR, buf, offset)
(n, value, mask, _len) = ofproto_v1_3.oxm_parse(buf, offset + 4)
k, uv = ofproto_v1_3.oxm_to_user(n, value, mask)
action = cls(**{k: uv})
action.len = len_
# old api compat
action.field = OFPMatchField.parser(buf, offset + 4)
return action
def serialize(self, buf, offset):
# old api compat
if self._composed_with_old_api():
return self.serialize_old(buf, offset)
n, value, mask = ofproto_v1_3.oxm_from_user(self.key, self.value)
len_ = ofproto_v1_3.oxm_serialize(n, value, mask, buf, offset + 4)
self.len = utils.round_up(4 + len_, 8)
msg_pack_into('!HH', buf, offset, self.type, self.len)
pad_len = self.len - (4 + len_)
ofproto_parser.msg_pack_into("%dx" % pad_len, buf, offset + 4 + len_)
# XXX old api compat
def serialize_old(self, buf, offset):
len_ = ofproto_v1_3.OFP_ACTION_SET_FIELD_SIZE + self.field.oxm_len()
self.len = utils.round_up(len_, 8)
pad_len = self.len - len_
msg_pack_into('!HH', buf, offset, self.type, self.len)
self.field.serialize(buf, offset + 4)
offset += len_
ofproto_parser.msg_pack_into("%dx" % pad_len, buf, offset)
# XXX old api compat
def _composed_with_old_api(self):
return not hasattr(self, 'value')
def to_jsondict(self):
# XXX old api compat
if self._composed_with_old_api():
# copy object first because serialize_old is destructive
o2 = OFPActionSetField(self.field)
# serialize and parse to fill new fields
buf = bytearray()
o2.serialize(buf, 0)
o = OFPActionSetField.parser(str(buf), 0)
else:
o = self
return {
self.__class__.__name__: {
'field': ofproto_v1_3.oxm_to_jsondict(self.key, self.value)
}
}
@classmethod
def from_jsondict(cls, dict_):
k, v = ofproto_v1_3.oxm_from_jsondict(dict_['field'])
o = OFPActionSetField(**{k: v})
# XXX old api compat
# serialize and parse to fill old attributes
buf = bytearray()
o.serialize(buf, 0)
return OFPActionSetField.parser(str(buf), 0)
# XXX old api compat
def __str__(self):
# XXX old api compat
if self._composed_with_old_api():
# copy object first because serialize_old is destructive
o2 = OFPActionSetField(self.field)
# serialize and parse to fill new fields
buf = bytearray()
o2.serialize(buf, 0)
o = OFPActionSetField.parser(str(buf), 0)
else:
o = self
return super(OFPActionSetField, o).__str__()
__repr__ = __str__
def stringify_attrs(self):
yield (self.key, self.value)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_PUSH_PBB,
ofproto_v1_3.OFP_ACTION_PUSH_SIZE)
class OFPActionPushPbb(OFPAction):
"""
Push PBB action
This action pushes a new PBB header to the packet.
================ ======================================================
Attribute Description
================ ======================================================
ethertype Ether type
================ ======================================================
"""
def __init__(self, ethertype, type_=None, len_=None):
super(OFPActionPushPbb, self).__init__()
self.ethertype = ethertype
@classmethod
def parser(cls, buf, offset):
(type_, len_, ethertype) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_PUSH_PACK_STR, buf, offset)
return cls(ethertype)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_PUSH_PACK_STR, buf, offset,
self.type, self.len, self.ethertype)
@OFPAction.register_action_type(ofproto_v1_3.OFPAT_POP_PBB,
ofproto_v1_3.OFP_ACTION_HEADER_SIZE)
class OFPActionPopPbb(OFPAction):
"""
Pop PBB action
This action pops the outermost PBB service instance header from
the packet.
"""
def __init__(self, type_=None, len_=None):
super(OFPActionPopPbb, self).__init__()
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_HEADER_PACK_STR, buf, offset)
return cls()
@classmethod
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_HEADER_PACK_STR, buf, offset)
return cls()
@OFPAction.register_action_type(
ofproto_v1_3.OFPAT_EXPERIMENTER,
ofproto_v1_3.OFP_ACTION_EXPERIMENTER_HEADER_SIZE)
class OFPActionExperimenter(OFPAction):
"""
Experimenter action
This action is an extensible action for the experimenter.
================ ======================================================
Attribute Description
================ ======================================================
experimenter Experimenter ID
================ ======================================================
"""
def __init__(self, experimenter, type_=None, len_=None):
super(OFPActionExperimenter, self).__init__()
self.experimenter = experimenter
@classmethod
def parser(cls, buf, offset):
(type_, len_, experimenter) = struct.unpack_from(
ofproto_v1_3.OFP_ACTION_EXPERIMENTER_HEADER_PACK_STR, buf, offset)
return cls(experimenter)
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_ACTION_EXPERIMENTER_HEADER_PACK_STR,
buf, offset, self.type, self.len, self.experimenter)
class OFPBucket(StringifyMixin):
def __init__(self, weight, watch_port, watch_group, actions, len_=None):
super(OFPBucket, self).__init__()
self.weight = weight
self.watch_port = watch_port
self.watch_group = watch_group
self.actions = actions
@classmethod
def parser(cls, buf, offset):
(len_, weight, watch_port, watch_group) = struct.unpack_from(
ofproto_v1_3.OFP_BUCKET_PACK_STR, buf, offset)
msg = cls(weight, watch_port, watch_group, [])
msg.len = len_
length = ofproto_v1_3.OFP_BUCKET_SIZE
offset += ofproto_v1_3.OFP_BUCKET_SIZE
while length < msg.len:
action = OFPAction.parser(buf, offset)
msg.actions.append(action)
offset += action.len
length += action.len
return msg
def serialize(self, buf, offset):
action_offset = offset + ofproto_v1_3.OFP_BUCKET_SIZE
action_len = 0
for a in self.actions:
a.serialize(buf, action_offset)
action_offset += a.len
action_len += a.len
self.len = utils.round_up(ofproto_v1_3.OFP_BUCKET_SIZE + action_len, 8)
msg_pack_into(ofproto_v1_3.OFP_BUCKET_PACK_STR, buf, offset,
self.len, self.weight, self.watch_port,
self.watch_group)
@_set_msg_type(ofproto_v1_3.OFPT_GROUP_MOD)
class OFPGroupMod(MsgBase):
"""
Modify group entry message
The controller sends this message to modify the group table.
================ ======================================================
Attribute Description
================ ======================================================
command One of the following values.
OFPFC_ADD
OFPFC_MODIFY
OFPFC_DELETE
type One of the following values.
OFPGT_ALL
OFPGT_SELECT
OFPGT_INDIRECT
OFPGT_FF
group_id Group identifier
buckets list of ``OFPBucket``
================ ======================================================
``type`` attribute corresponds to ``type_`` parameter of __init__.
Example::
def send_group_mod(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
port = 1
max_len = 2000
actions = [ofp_parser.OFPActionOutput(port, max_len)]
weight = 100
watch_port = 0
watch_group = 0
buckets = [ofp_parser.OFPBucket(weight, watch_port, watch_group,
actions)]
group_id = 1
req = ofp_parser.OFPGroupMod(datapath, ofp.OFPFC_ADD,
ofp.OFPGT_SELECT, group_id, buckets)
datapath.send_msg(req)
"""
def __init__(self, datapath, command, type_, group_id, buckets):
super(OFPGroupMod, self).__init__(datapath)
self.command = command
self.type = type_
self.group_id = group_id
self.buckets = buckets
def _serialize_body(self):
msg_pack_into(ofproto_v1_3.OFP_GROUP_MOD_PACK_STR, self.buf,
ofproto_v1_3.OFP_HEADER_SIZE,
self.command, self.type, self.group_id)
offset = ofproto_v1_3.OFP_GROUP_MOD_SIZE
for b in self.buckets:
b.serialize(self.buf, offset)
offset += b.len
@_set_msg_type(ofproto_v1_3.OFPT_PORT_MOD)
class OFPPortMod(MsgBase):
"""
Port modification message
The controller sneds this message to modify the behavior of the port.
================ ======================================================
Attribute Description
================ ======================================================
port_no Port number to modify
hw_addr The hardware address that must be the same as hw_addr
of ``OFPPort`` of ``OFPSwitchFeatures``
config Bitmap of configuration flags.
OFPPC_PORT_DOWN
OFPPC_NO_RECV
OFPPC_NO_FWD
OFPPC_NO_PACKET_IN
mask Bitmap of configuration flags above to be changed
advertise Bitmap of the following flags.
OFPPF_10MB_HD
OFPPF_10MB_FD
OFPPF_100MB_HD
OFPPF_100MB_FD
OFPPF_1GB_HD
OFPPF_1GB_FD
OFPPF_10GB_FD
OFPPF_40GB_FD
OFPPF_100GB_FD
OFPPF_1TB_FD
OFPPF_OTHER
OFPPF_COPPER
OFPPF_FIBER
OFPPF_AUTONEG
OFPPF_PAUSE
OFPPF_PAUSE_ASYM
================ ======================================================
Example::
def send_port_mod(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
port_no = 3
hw_addr = 'fa:c8:e8:76:1d:7e'
config = 0
mask = (ofp.OFPPC_PORT_DOWN | ofp.OFPPC_NO_RECV |
ofp.OFPPC_NO_FWD | ofp.OFPPC_NO_PACKET_IN)
advertise = (ofp.OFPPF_10MB_HD | ofp.OFPPF_100MB_FD |
ofp.OFPPF_1GB_FD | ofp.OFPPF_COPPER |
ofp.OFPPF_AUTONEG | ofp.OFPPF_PAUSE |
ofp.OFPPF_PAUSE_ASYM)
req = ofp_parser.OFPPortMod(datapath, port_no, hw_addr, config,
mask, advertise)
datapath.send_msg(req)
"""
_TYPE = {
'ascii': [
'hw_addr',
]
}
def __init__(self, datapath, port_no, hw_addr, config, mask, advertise):
super(OFPPortMod, self).__init__(datapath)
self.port_no = port_no
self.hw_addr = hw_addr
self.config = config
self.mask = mask
self.advertise = advertise
def _serialize_body(self):
msg_pack_into(ofproto_v1_3.OFP_PORT_MOD_PACK_STR, self.buf,
ofproto_v1_3.OFP_HEADER_SIZE,
self.port_no, addrconv.mac.text_to_bin(self.hw_addr),
self.config,
self.mask, self.advertise)
@_set_msg_type(ofproto_v1_3.OFPT_METER_MOD)
class OFPMeterMod(MsgBase):
"""
Meter modification message
The controller sends this message to modify the meter.
================ ======================================================
Attribute Description
================ ======================================================
command One of the following values.
OFPMC_ADD
OFPMC_MODIFY
OFPMC_DELETE
flags One of the following flags.
OFPMF_KBPS
OFPMF_PKTPS
OFPMF_BURST
OFPMF_STATS
meter_id Meter instance
bands list of the following class instance.
OFPMeterBandDrop
OFPMeterBandDscpRemark
OFPMeterBandExperimenter
================ ======================================================
"""
def __init__(self, datapath, command, flags, meter_id, bands):
super(OFPMeterMod, self).__init__(datapath)
self.command = command
self.flags = flags
self.meter_id = meter_id
self.bands = bands
def _serialize_body(self):
msg_pack_into(ofproto_v1_3.OFP_METER_MOD_PACK_STR, self.buf,
ofproto_v1_3.OFP_HEADER_SIZE,
self.command, self.flags, self.meter_id)
offset = ofproto_v1_3.OFP_METER_MOD_SIZE
for b in self.bands:
b.serialize(self.buf, offset)
offset += b.len
@_set_msg_type(ofproto_v1_3.OFPT_TABLE_MOD)
class OFPTableMod(MsgBase):
"""
Flow table configuration message
The controller sends this message to configure table state.
================ ======================================================
Attribute Description
================ ======================================================
table_id ID of the table (OFPTT_ALL indicates all tables)
config Bitmap of the following flags.
OFPTC_DEPRECATED_MASK (3)
================ ======================================================
Example::
def send_table_mod(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPTableMod(datapath, 1, 3)
datapath.send_msg(req)
"""
def __init__(self, datapath, table_id, config):
super(OFPTableMod, self).__init__(datapath)
self.table_id = table_id
self.config = config
def _serialize_body(self):
msg_pack_into(ofproto_v1_3.OFP_TABLE_MOD_PACK_STR, self.buf,
ofproto_v1_3.OFP_HEADER_SIZE,
self.table_id, self.config)
def _set_stats_type(stats_type, stats_body_cls):
def _set_cls_stats_type(cls):
cls.cls_stats_type = stats_type
cls.cls_stats_body_cls = stats_body_cls
return cls
return _set_cls_stats_type
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPMultipartRequest(MsgBase):
def __init__(self, datapath, flags):
super(OFPMultipartRequest, self).__init__(datapath)
self.type = self.__class__.cls_stats_type
self.flags = flags
def _serialize_stats_body(self):
pass
def _serialize_body(self):
msg_pack_into(ofproto_v1_3.OFP_MULTIPART_REQUEST_PACK_STR,
self.buf, ofproto_v1_3.OFP_HEADER_SIZE,
self.type, self.flags)
self._serialize_stats_body()
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPMultipartReply(MsgBase):
_STATS_MSG_TYPES = {}
@staticmethod
def register_stats_type(body_single_struct=False):
def _register_stats_type(cls):
assert cls.cls_stats_type is not None
assert cls.cls_stats_type not in OFPMultipartReply._STATS_MSG_TYPES
assert cls.cls_stats_body_cls is not None
cls.cls_body_single_struct = body_single_struct
OFPMultipartReply._STATS_MSG_TYPES[cls.cls_stats_type] = cls
return cls
return _register_stats_type
def __init__(self, datapath, body=None, flags=None):
super(OFPMultipartReply, self).__init__(datapath)
self.body = body
self.flags = flags
@classmethod
def parser_stats_body(cls, buf, msg_len, offset):
body_cls = cls.cls_stats_body_cls
body = []
while offset < msg_len:
entry = body_cls.parser(buf, offset)
body.append(entry)
offset += entry.length
if cls.cls_body_single_struct:
return body[0]
return body
@classmethod
def parser_stats(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = MsgBase.parser.__func__(
cls, datapath, version, msg_type, msg_len, xid, buf)
msg.body = msg.parser_stats_body(msg.buf, msg.msg_len,
ofproto_v1_3.OFP_MULTIPART_REPLY_SIZE)
return msg
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
type_, flags = struct.unpack_from(
ofproto_v1_3.OFP_MULTIPART_REPLY_PACK_STR, buffer(buf),
ofproto_v1_3.OFP_HEADER_SIZE)
stats_type_cls = cls._STATS_MSG_TYPES.get(type_)
msg = super(OFPMultipartReply, stats_type_cls).parser(
datapath, version, msg_type, msg_len, xid, buf)
msg.type = type_
msg.flags = flags
offset = ofproto_v1_3.OFP_MULTIPART_REPLY_SIZE
body = []
while offset < msg_len:
b = stats_type_cls.cls_stats_body_cls.parser(msg.buf, offset)
body.append(b)
offset += b.length if hasattr(b, 'length') else b.len
if stats_type_cls.cls_body_single_struct:
msg.body = body[0]
else:
msg.body = body
return msg
class OFPDescStats(ofproto_parser.namedtuple('OFPDescStats', (
'mfr_desc', 'hw_desc', 'sw_desc', 'serial_num', 'dp_desc'))):
_TYPE = {
'ascii': [
'mfr_desc',
'hw_desc',
'sw_desc',
'serial_num',
'dp_desc',
]
}
@classmethod
def parser(cls, buf, offset):
desc = struct.unpack_from(ofproto_v1_3.OFP_DESC_PACK_STR,
buf, offset)
desc = list(desc)
desc = map(lambda x: x.rstrip('\0'), desc)
stats = cls(*desc)
stats.length = ofproto_v1_3.OFP_DESC_SIZE
return stats
@_set_stats_type(ofproto_v1_3.OFPMP_DESC, OFPDescStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPDescStatsRequest(OFPMultipartRequest):
"""
Description statistics request message
The controller uses this message to query description of the switch.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
================ ======================================================
Example::
def send_desc_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPDescStatsRequest(datapath, 0)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, type_=None):
super(OFPDescStatsRequest, self).__init__(datapath, flags)
@OFPMultipartReply.register_stats_type(body_single_struct=True)
@_set_stats_type(ofproto_v1_3.OFPMP_DESC, OFPDescStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPDescStatsReply(OFPMultipartReply):
"""
Description statistics reply message
The switch responds with this message to a description statistics
request.
================ ======================================================
Attribute Description
================ ======================================================
body Instance of ``OFPDescStats``
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPDescStatsReply, MAIN_DISPATCHER)
def desc_stats_reply_handler(self, ev):
body = ev.msg.body
self.logger.debug('DescStats: mfr_desc=%s hw_desc=%s sw_desc=%s '
'serial_num=%s dp_desc=%s',
body.mfr_desc, body.hw_desc, body.sw_desc,
body.serial_num, body.dp_desc)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPDescStatsReply, self).__init__(datapath, **kwargs)
class OFPFlowStats(StringifyMixin):
def __init__(self, table_id=None, duration_sec=None, duration_nsec=None,
priority=None, idle_timeout=None, hard_timeout=None,
flags=None, cookie=None, packet_count=None,
byte_count=None, match=None, instructions=None,
length=None):
super(OFPFlowStats, self).__init__()
self.length = 0
self.table_id = table_id
self.duration_sec = duration_sec
self.duration_nsec = duration_nsec
self.priority = priority
self.idle_timeout = idle_timeout
self.hard_timeout = hard_timeout
self.flags = flags
self.cookie = cookie
self.packet_count = packet_count
self.byte_count = byte_count
self.match = match
self.instructions = instructions
@classmethod
def parser(cls, buf, offset):
flow_stats = cls()
(flow_stats.length, flow_stats.table_id,
flow_stats.duration_sec, flow_stats.duration_nsec,
flow_stats.priority, flow_stats.idle_timeout,
flow_stats.hard_timeout, flow_stats.flags,
flow_stats.cookie, flow_stats.packet_count,
flow_stats.byte_count) = struct.unpack_from(
ofproto_v1_3.OFP_FLOW_STATS_0_PACK_STR, buf, offset)
offset += ofproto_v1_3.OFP_FLOW_STATS_0_SIZE
flow_stats.match = OFPMatch.parser(buf, offset)
match_length = utils.round_up(flow_stats.match.length, 8)
inst_length = (flow_stats.length - (ofproto_v1_3.OFP_FLOW_STATS_SIZE -
ofproto_v1_3.OFP_MATCH_SIZE +
match_length))
offset += match_length
instructions = []
while inst_length > 0:
inst = OFPInstruction.parser(buf, offset)
instructions.append(inst)
offset += inst.len
inst_length -= inst.len
flow_stats.instructions = instructions
return flow_stats
class OFPFlowStatsRequestBase(OFPMultipartRequest):
def __init__(self, datapath, flags, table_id, out_port, out_group,
cookie, cookie_mask, match):
super(OFPFlowStatsRequestBase, self).__init__(datapath, flags)
self.table_id = table_id
self.out_port = out_port
self.out_group = out_group
self.cookie = cookie
self.cookie_mask = cookie_mask
self.match = match
def _serialize_stats_body(self):
offset = ofproto_v1_3.OFP_MULTIPART_REQUEST_SIZE
msg_pack_into(ofproto_v1_3.OFP_FLOW_STATS_REQUEST_0_PACK_STR,
self.buf, offset, self.table_id, self.out_port,
self.out_group, self.cookie, self.cookie_mask)
offset += ofproto_v1_3.OFP_FLOW_STATS_REQUEST_0_SIZE
self.match.serialize(self.buf, offset)
@_set_stats_type(ofproto_v1_3.OFPMP_FLOW, OFPFlowStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPFlowStatsRequest(OFPFlowStatsRequestBase):
"""
Individual flow statistics request message
The controller uses this message to query individual flow statistics.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
table_id ID of table to read
out_port Require matching entries to include this as an output
port
out_group Require matching entries to include this as an output
group
cookie Require matching entries to contain this cookie value
cookie_mask Mask used to restrict the cookie bits that must match
match Instance of ``OFPMatch``
================ ======================================================
Example::
def send_flow_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
cookie = cookie_mask = 0
match = ofp_parser.OFPMatch(in_port=1)
req = ofp_parser.OFPFlowStatsRequest(datapath, 0,
ofp.OFPTT_ALL,
ofp.OFPP_ANY, ofp.OFPG_ANY,
cookie, cookie_mask,
match)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags=0, table_id=ofproto_v1_3.OFPTT_ALL,
out_port=ofproto_v1_3.OFPP_ANY,
out_group=ofproto_v1_3.OFPG_ANY,
cookie=0, cookie_mask=0, match=None, type_=None):
if match is None:
match = OFPMatch()
super(OFPFlowStatsRequest, self).__init__(datapath, flags, table_id,
out_port, out_group,
cookie, cookie_mask, match)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_FLOW, OFPFlowStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPFlowStatsReply(OFPMultipartReply):
"""
Individual flow statistics reply message
The switch responds with this message to an individual flow statistics
request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPFlowStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPFlowStatsReply, MAIN_DISPATCHER)
def flow_stats_reply_handler(self, ev):
flows = []
for stat in ev.msg.body:
flows.append('table_id=%s '
'duration_sec=%d duration_nsec=%d '
'priority=%d '
'idle_timeout=%d hard_timeout=%d flags=0x%04x '
'cookie=%d packet_count=%d byte_count=%d '
'match=%s instructions=%s' %
(stat.table_id,
stat.duration_sec, stat.duration_nsec,
stat.priority,
stat.idle_timeout, stat.hard_timeout, stat.flags,
stat.cookie, stat.packet_count, stat.byte_count,
stat.match, stat.instructions))
self.logger.debug('FlowStats: %s', flows)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPFlowStatsReply, self).__init__(datapath, **kwargs)
class OFPAggregateStats(ofproto_parser.namedtuple('OFPAggregateStats', (
'packet_count', 'byte_count', 'flow_count'))):
@classmethod
def parser(cls, buf, offset):
agg = struct.unpack_from(
ofproto_v1_3.OFP_AGGREGATE_STATS_REPLY_PACK_STR, buf, offset)
stats = cls(*agg)
stats.length = ofproto_v1_3.OFP_AGGREGATE_STATS_REPLY_SIZE
return stats
@_set_stats_type(ofproto_v1_3.OFPMP_AGGREGATE, OFPAggregateStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPAggregateStatsRequest(OFPFlowStatsRequestBase):
"""
Aggregate flow statistics request message
The controller uses this message to query aggregate flow statictics.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
table_id ID of table to read
out_port Require matching entries to include this as an output
port
out_group Require matching entries to include this as an output
group
cookie Require matching entries to contain this cookie value
cookie_mask Mask used to restrict the cookie bits that must match
match Instance of ``OFPMatch``
================ ======================================================
Example::
def send_aggregate_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
cookie = cookie_mask = 0
match = ofp_parser.OFPMatch(in_port=1)
req = ofp_parser.OFPAggregateStatsRequest(datapath, 0,
ofp.OFPTT_ALL,
ofp.OFPP_ANY,
ofp.OFPG_ANY,
cookie, cookie_mask,
match)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, table_id, out_port, out_group,
cookie, cookie_mask, match, type_=None):
super(OFPAggregateStatsRequest, self).__init__(datapath,
flags,
table_id,
out_port,
out_group,
cookie,
cookie_mask,
match)
@OFPMultipartReply.register_stats_type(body_single_struct=True)
@_set_stats_type(ofproto_v1_3.OFPMP_AGGREGATE, OFPAggregateStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPAggregateStatsReply(OFPMultipartReply):
"""
Aggregate flow statistics reply message
The switch responds with this message to an aggregate flow statistics
request.
================ ======================================================
Attribute Description
================ ======================================================
body Instance of ``OFPAggregateStats``
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPAggregateStatsReply, MAIN_DISPATCHER)
def aggregate_stats_reply_handler(self, ev):
body = ev.msg.body
self.logger.debug('AggregateStats: packet_count=%d byte_count=%d '
'flow_count=%d',
body.packet_count, body.byte_count,
body.flow_count)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPAggregateStatsReply, self).__init__(datapath, **kwargs)
class OFPTableStats(ofproto_parser.namedtuple('OFPTableStats', (
'table_id', 'active_count', 'lookup_count',
'matched_count'))):
@classmethod
def parser(cls, buf, offset):
tbl = struct.unpack_from(ofproto_v1_3.OFP_TABLE_STATS_PACK_STR,
buf, offset)
stats = cls(*tbl)
stats.length = ofproto_v1_3.OFP_TABLE_STATS_SIZE
return stats
@_set_stats_type(ofproto_v1_3.OFPMP_TABLE, OFPTableStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPTableStatsRequest(OFPMultipartRequest):
"""
Table statistics request message
The controller uses this message to query flow table statictics.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
================ ======================================================
Example::
def send_table_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPTableStatsRequest(datapath, 0)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, type_=None):
super(OFPTableStatsRequest, self).__init__(datapath, flags)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_TABLE, OFPTableStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPTableStatsReply(OFPMultipartReply):
"""
Table statistics reply message
The switch responds with this message to a table statistics request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPTableStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPTableStatsReply, MAIN_DISPATCHER)
def table_stats_reply_handler(self, ev):
tables = []
for stat in ev.msg.body:
tables.append('table_id=%d active_count=%d lookup_count=%d '
' matched_count=%d' %
(stat.table_id, stat.active_count,
stat.lookup_count, stat.matched_count))
self.logger.debug('TableStats: %s', tables)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPTableStatsReply, self).__init__(datapath, **kwargs)
class OFPPortStats(ofproto_parser.namedtuple('OFPPortStats', (
'port_no', 'rx_packets', 'tx_packets', 'rx_bytes', 'tx_bytes',
'rx_dropped', 'tx_dropped', 'rx_errors', 'tx_errors',
'rx_frame_err', 'rx_over_err', 'rx_crc_err', 'collisions',
'duration_sec', 'duration_nsec'))):
@classmethod
def parser(cls, buf, offset):
port = struct.unpack_from(ofproto_v1_3.OFP_PORT_STATS_PACK_STR,
buf, offset)
stats = cls(*port)
stats.length = ofproto_v1_3.OFP_PORT_STATS_SIZE
return stats
@_set_stats_type(ofproto_v1_3.OFPMP_PORT_STATS, OFPPortStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPPortStatsRequest(OFPMultipartRequest):
"""
Port statistics request message
The controller uses this message to query information about ports
statistics.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
port_no Port number to read (OFPP_ANY to all ports)
================ ======================================================
Example::
def send_port_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPPortStatsRequest(datapath, 0, ofp.OFPP_ANY)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, port_no, type_=None):
super(OFPPortStatsRequest, self).__init__(datapath, flags)
self.port_no = port_no
def _serialize_stats_body(self):
msg_pack_into(ofproto_v1_3.OFP_PORT_STATS_REQUEST_PACK_STR,
self.buf,
ofproto_v1_3.OFP_MULTIPART_REQUEST_SIZE,
self.port_no)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_PORT_STATS, OFPPortStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPPortStatsReply(OFPMultipartReply):
"""
Port statistics reply message
The switch responds with this message to a port statistics request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPPortStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPPortStatsReply, MAIN_DISPATCHER)
def port_stats_reply_handler(self, ev):
ports = []
for stat in ev.msg.body:
ports.append('port_no=%d '
'rx_packets=%d tx_packets=%d '
'rx_bytes=%d tx_bytes=%d '
'rx_dropped=%d tx_dropped=%d '
'rx_errors=%d tx_errors=%d '
'rx_frame_err=%d rx_over_err=%d rx_crc_err=%d '
'collisions=%d duration_sec=%d duration_nsec=%d' %
(stat.port_no,
stat.rx_packets, stat.tx_packets,
stat.rx_bytes, stat.tx_bytes,
stat.rx_dropped, stat.tx_dropped,
stat.rx_errors, stat.tx_errors,
stat.rx_frame_err, stat.rx_over_err,
stat.rx_crc_err, stat.collisions,
stat.duration_sec, stat.duration_nsec))
self.logger.debug('PortStats: %s', ports)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPPortStatsReply, self).__init__(datapath, **kwargs)
class OFPQueueStats(ofproto_parser.namedtuple('OFPQueueStats', (
'port_no', 'queue_id', 'tx_bytes', 'tx_packets', 'tx_errors',
'duration_sec', 'duration_nsec'))):
@classmethod
def parser(cls, buf, offset):
queue = struct.unpack_from(ofproto_v1_3.OFP_QUEUE_STATS_PACK_STR,
buf, offset)
stats = cls(*queue)
stats.length = ofproto_v1_3.OFP_QUEUE_STATS_SIZE
return stats
@_set_stats_type(ofproto_v1_3.OFPMP_QUEUE, OFPQueueStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPQueueStatsRequest(OFPMultipartRequest):
"""
Queue statistics request message
The controller uses this message to query queue statictics.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
port_no Port number to read
queue_id ID of queue to read
================ ======================================================
Example::
def send_queue_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPQueueStatsRequest(datapath, 0, ofp.OFPP_ANY,
ofp.OFPQ_ALL)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, port_no, queue_id, type_=None):
super(OFPQueueStatsRequest, self).__init__(datapath, flags)
self.port_no = port_no
self.queue_id = queue_id
def _serialize_stats_body(self):
msg_pack_into(ofproto_v1_3.OFP_QUEUE_STATS_REQUEST_PACK_STR,
self.buf,
ofproto_v1_3.OFP_MULTIPART_REQUEST_SIZE,
self.port_no, self.queue_id)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_QUEUE, OFPQueueStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPQueueStatsReply(OFPMultipartReply):
"""
Queue statistics reply message
The switch responds with this message to an aggregate flow statistics
request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPQueueStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPQueueStatsReply, MAIN_DISPATCHER)
def queue_stats_reply_handler(self, ev):
queues = []
for stat in ev.msg.body:
queues.append('port_no=%d queue_id=%d '
'tx_bytes=%d tx_packets=%d tx_errors=%d '
'duration_sec=%d duration_nsec=%d' %
(stat.port_no, stat.queue_id,
stat.tx_bytes, stat.tx_packets, stat.tx_errors,
stat.duration_sec, stat.duration_nsec))
self.logger.debug('QueueStats: %s', queues)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPQueueStatsReply, self).__init__(datapath, **kwargs)
class OFPBucketCounter(StringifyMixin):
def __init__(self, packet_count, byte_count):
super(OFPBucketCounter, self).__init__()
self.packet_count = packet_count
self.byte_count = byte_count
@classmethod
def parser(cls, buf, offset):
packet_count, byte_count = struct.unpack_from(
ofproto_v1_3.OFP_BUCKET_COUNTER_PACK_STR, buf, offset)
return cls(packet_count, byte_count)
class OFPGroupStats(StringifyMixin):
def __init__(self, length=None, group_id=None, ref_count=None,
packet_count=None, byte_count=None, duration_sec=None,
duration_nsec=None, bucket_stats=None):
super(OFPGroupStats, self).__init__()
self.length = length
self.group_id = group_id
self.ref_count = ref_count
self.packet_count = packet_count
self.byte_count = byte_count
self.duration_sec = duration_sec
self.duration_nsec = duration_nsec
self.bucket_stats = bucket_stats
@classmethod
def parser(cls, buf, offset):
group = struct.unpack_from(ofproto_v1_3.OFP_GROUP_STATS_PACK_STR,
buf, offset)
group_stats = cls(*group)
group_stats.bucket_stats = []
total_len = group_stats.length + offset
offset += ofproto_v1_3.OFP_GROUP_STATS_SIZE
while total_len > offset:
b = OFPBucketCounter.parser(buf, offset)
group_stats.bucket_stats.append(b)
offset += ofproto_v1_3.OFP_BUCKET_COUNTER_SIZE
return group_stats
@_set_stats_type(ofproto_v1_3.OFPMP_GROUP, OFPGroupStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPGroupStatsRequest(OFPMultipartRequest):
"""
Group statistics request message
The controller uses this message to query statistics of one or more
groups.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
group_id ID of group to read (OFPG_ALL to all groups)
================ ======================================================
Example::
def send_group_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPGroupStatsRequest(datapath, 0, ofp.OFPG_ALL)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, group_id, type_=None):
super(OFPGroupStatsRequest, self).__init__(datapath, flags)
self.group_id = group_id
def _serialize_stats_body(self):
msg_pack_into(ofproto_v1_3.OFP_GROUP_STATS_REQUEST_PACK_STR,
self.buf,
ofproto_v1_3.OFP_MULTIPART_REQUEST_SIZE,
self.group_id)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_GROUP, OFPGroupStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPGroupStatsReply(OFPMultipartReply):
"""
Group statistics reply message
The switch responds with this message to a group statistics request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPGroupStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPGroupStatsReply, MAIN_DISPATCHER)
def group_stats_reply_handler(self, ev):
groups = []
for stat in ev.msg.body:
groups.append('length=%d group_id=%d '
'ref_count=%d packet_count=%d byte_count=%d '
'duration_sec=%d duration_nsec=%d' %
(stat.length, stat.group_id,
stat.ref_count, stat.packet_count,
stat.byte_count, stat.duration_sec,
stat.duration_nsec))
self.logger.debug('GroupStats: %s', groups)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPGroupStatsReply, self).__init__(datapath, **kwargs)
class OFPGroupDescStats(StringifyMixin):
def __init__(self, type_=None, group_id=None, buckets=None, length=None):
super(OFPGroupDescStats, self).__init__()
self.type = type_
self.group_id = group_id
self.buckets = buckets
@classmethod
def parser(cls, buf, offset):
stats = cls()
(stats.length, stats.type, stats.group_id) = struct.unpack_from(
ofproto_v1_3.OFP_GROUP_DESC_STATS_PACK_STR, buf, offset)
offset += ofproto_v1_3.OFP_GROUP_DESC_STATS_SIZE
stats.buckets = []
length = ofproto_v1_3.OFP_GROUP_DESC_STATS_SIZE
while length < stats.length:
bucket = OFPBucket.parser(buf, offset)
stats.buckets.append(bucket)
offset += bucket.len
length += bucket.len
return stats
@_set_stats_type(ofproto_v1_3.OFPMP_GROUP_DESC, OFPGroupDescStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPGroupDescStatsRequest(OFPMultipartRequest):
"""
Group description request message
The controller uses this message to list the set of groups on a switch.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
================ ======================================================
Example::
def send_group_desc_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPGroupDescStatsRequest(datapath, 0)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, type_=None):
super(OFPGroupDescStatsRequest, self).__init__(datapath, flags)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_GROUP_DESC, OFPGroupDescStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPGroupDescStatsReply(OFPMultipartReply):
"""
Group description reply message
The switch responds with this message to a group description request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPGroupDescStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPGroupDescStatsReply, MAIN_DISPATCHER)
def group_desc_stats_reply_handler(self, ev):
descs = []
for stat in ev.msg.body:
descs.append('length=%d type=%d group_id=%d '
'buckets=%s' %
(stat.length, stat.type, stat.group_id,
stat.bucket))
self.logger.debug('GroupDescStats: %s', groups)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPGroupDescStatsReply, self).__init__(datapath, **kwargs)
class OFPGroupFeaturesStats(ofproto_parser.namedtuple('OFPGroupFeaturesStats',
('types', 'capabilities', 'max_groups',
'actions'))):
@classmethod
def parser(cls, buf, offset):
group_features = struct.unpack_from(
ofproto_v1_3.OFP_GROUP_FEATURES_PACK_STR, buf, offset)
types = group_features[0]
capabilities = group_features[1]
max_groups = list(group_features[2:6])
actions = list(group_features[6:10])
stats = cls(types, capabilities, max_groups, actions)
stats.length = ofproto_v1_3.OFP_GROUP_FEATURES_SIZE
return stats
@_set_stats_type(ofproto_v1_3.OFPMP_GROUP_FEATURES, OFPGroupFeaturesStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPGroupFeaturesStatsRequest(OFPMultipartRequest):
"""
Group features request message
The controller uses this message to list the capabilities of groups on
a switch.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
================ ======================================================
Example::
def send_group_features_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPGroupFeaturesStatsRequest(datapath, 0)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, type_=None):
super(OFPGroupFeaturesStatsRequest, self).__init__(datapath, flags)
@OFPMultipartReply.register_stats_type(body_single_struct=True)
@_set_stats_type(ofproto_v1_3.OFPMP_GROUP_FEATURES, OFPGroupFeaturesStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPGroupFeaturesStatsReply(OFPMultipartReply):
"""
Group features reply message
The switch responds with this message to a group features request.
================ ======================================================
Attribute Description
================ ======================================================
body Instance of ``OFPGroupFeaturesStats``
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPGroupFeaturesStatsReply, MAIN_DISPATCHER)
def group_features_stats_reply_handler(self, ev):
body = ev.msg.body
self.logger.debug('GroupFeaturesStats: types=%d '
'capabilities=0x%08x max_groups=%s '
'actions=%s',
body.types, body.capabilities,
body.max_groups, body.actions)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPGroupFeaturesStatsReply, self).__init__(datapath, **kwargs)
class OFPMeterBandStats(StringifyMixin):
def __init__(self, packet_band_count, byte_band_count):
super(OFPMeterBandStats, self).__init__()
self.packet_band_count = packet_band_count
self.byte_band_count = byte_band_count
@classmethod
def parser(cls, buf, offset):
band_stats = struct.unpack_from(
ofproto_v1_3.OFP_METER_BAND_STATS_PACK_STR, buf, offset)
return cls(*band_stats)
class OFPMeterStats(StringifyMixin):
def __init__(self, meter_id=None, flow_count=None, packet_in_count=None,
byte_in_count=None, duration_sec=None, duration_nsec=None,
band_stats=None, len_=None):
super(OFPMeterStats, self).__init__()
self.meter_id = meter_id
self.len = 0
self.flow_count = flow_count
self.packet_in_count = packet_in_count
self.byte_in_count = byte_in_count
self.duration_sec = duration_sec
self.duration_nsec = duration_nsec
self.band_stats = band_stats
@classmethod
def parser(cls, buf, offset):
meter_stats = cls()
(meter_stats.meter_id, meter_stats.len,
meter_stats.flow_count, meter_stats.packet_in_count,
meter_stats.byte_in_count, meter_stats.duration_sec,
meter_stats.duration_nsec) = struct.unpack_from(
ofproto_v1_3.OFP_METER_STATS_PACK_STR, buf, offset)
offset += ofproto_v1_3.OFP_METER_STATS_SIZE
meter_stats.band_stats = []
length = ofproto_v1_3.OFP_METER_STATS_SIZE
while length < meter_stats.len:
band_stats = OFPMeterBandStats.parser(buf, offset)
meter_stats.band_stats.append(band_stats)
offset += ofproto_v1_3.OFP_METER_BAND_STATS_SIZE
length += ofproto_v1_3.OFP_METER_BAND_STATS_SIZE
return meter_stats
@_set_stats_type(ofproto_v1_3.OFPMP_METER, OFPMeterStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPMeterStatsRequest(OFPMultipartRequest):
"""
Meter statistics request message
The controller uses this message to query statistics for one or more
meters.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
meter_id ID of meter to read (OFPM_ALL to all meters)
================ ======================================================
Example::
def send_meter_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPMeterStatsRequest(datapath, 0, ofp.OFPM_ALL)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, meter_id, type_=None):
super(OFPMeterStatsRequest, self).__init__(datapath, flags)
self.meter_id = meter_id
def _serialize_stats_body(self):
msg_pack_into(ofproto_v1_3.OFP_METER_MULTIPART_REQUEST_PACK_STR,
self.buf,
ofproto_v1_3.OFP_MULTIPART_REQUEST_SIZE,
self.meter_id)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_METER, OFPMeterStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPMeterStatsReply(OFPMultipartReply):
"""
Meter statistics reply message
The switch responds with this message to a meter statistics request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPMeterStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPMeterStatsReply, MAIN_DISPATCHER)
def meter_stats_reply_handler(self, ev):
meters = []
for stat in ev.msg.body:
meters.append('meter_id=0x%08x len=%d flow_count=%d '
'packet_in_count=%d byte_in_count=%d '
'duration_sec=%d duration_nsec=%d '
'band_stats=%s' %
(stat.meter_id, stat.len, stat.flow_count,
stat.packet_in_count, stat.byte_in_count,
stat.duration_sec, stat.duration_nsec,
stat.band_stats))
self.logger.debug('MeterStats: %s', meters)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPMeterStatsReply, self).__init__(datapath, **kwargs)
class OFPMeterBand(StringifyMixin):
def __init__(self, type_, len_):
super(OFPMeterBand, self).__init__()
self.type = type_
self.len = len_
class OFPMeterBandHeader(OFPMeterBand):
_METER_BAND = {}
@staticmethod
def register_meter_band_type(type_, len_):
def _register_meter_band_type(cls):
OFPMeterBandHeader._METER_BAND[type_] = cls
cls.cls_meter_band_type = type_
cls.cls_meter_band_len = len_
return cls
return _register_meter_band_type
def __init__(self):
cls = self.__class__
super(OFPMeterBandHeader, self).__init__(cls.cls_meter_band_type,
cls.cls_meter_band_len)
@classmethod
def parser(cls, buf, offset):
type_, len_, _rate, _burst_size = struct.unpack_from(
ofproto_v1_3.OFP_METER_BAND_HEADER_PACK_STR, buf, offset)
cls_ = cls._METER_BAND[type_]
assert cls_.cls_meter_band_len == len_
return cls_.parser(buf, offset)
@OFPMeterBandHeader.register_meter_band_type(
ofproto_v1_3.OFPMBT_DROP, ofproto_v1_3.OFP_METER_BAND_DROP_SIZE)
class OFPMeterBandDrop(OFPMeterBandHeader):
def __init__(self, rate, burst_size, type_=None, len_=None):
super(OFPMeterBandDrop, self).__init__()
self.rate = rate
self.burst_size = burst_size
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_METER_BAND_DROP_PACK_STR, buf, offset,
self.type, self.len, self.rate, self.burst_size)
@classmethod
def parser(cls, buf, offset):
type_, len_, rate, burst_size = struct.unpack_from(
ofproto_v1_3.OFP_METER_BAND_DROP_PACK_STR, buf, offset)
assert cls.cls_meter_band_type == type_
assert cls.cls_meter_band_len == len_
return cls(rate, burst_size)
@OFPMeterBandHeader.register_meter_band_type(
ofproto_v1_3.OFPMBT_DSCP_REMARK,
ofproto_v1_3.OFP_METER_BAND_DSCP_REMARK_SIZE)
class OFPMeterBandDscpRemark(OFPMeterBandHeader):
def __init__(self, rate, burst_size, prec_level, type_=None, len_=None):
super(OFPMeterBandDscpRemark, self).__init__()
self.rate = rate
self.burst_size = burst_size
self.prec_level = prec_level
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_METER_BAND_DSCP_REMARK_PACK_STR, buf,
offset, self.type, self.len, self.rate,
self.burst_size, self.prec_level)
@classmethod
def parser(cls, buf, offset):
type_, len_, rate, burst_size, prec_level = struct.unpack_from(
ofproto_v1_3.OFP_METER_BAND_DSCP_REMARK_PACK_STR, buf, offset)
assert cls.cls_meter_band_type == type_
assert cls.cls_meter_band_len == len_
return cls(rate, burst_size, prec_level)
@OFPMeterBandHeader.register_meter_band_type(
ofproto_v1_3.OFPMBT_EXPERIMENTER,
ofproto_v1_3.OFP_METER_BAND_EXPERIMENTER_SIZE)
class OFPMeterBandExperimenter(OFPMeterBandHeader):
def __init__(self, rate, burst_size, experimenter, type_=None, len_=None):
super(OFPMeterBandExperimenter, self).__init__()
self.rate = rate
self.burst_size = burst_size
self.experimenter = experimenter
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_METER_BAND_EXPERIMENTER_PACK_STR, buf,
offset, self.type, self.len, self.rate,
self.burst_size, self.experimenter)
@classmethod
def parser(cls, buf, offset):
type_, len_, rate, burst_size, experimenter = struct.unpack_from(
ofproto_v1_3.OFP_METER_BAND_EXPERIMENTER_PACK_STR, buf, offset)
assert cls.cls_meter_band_type == type_
assert cls.cls_meter_band_len == len_
return cls(rate, burst_size, experimenter)
class OFPMeterConfigStats(StringifyMixin):
def __init__(self, flags=None, meter_id=None, bands=None, length=None):
super(OFPMeterConfigStats, self).__init__()
self.length = None
self.flags = flags
self.meter_id = meter_id
self.bands = bands
@classmethod
def parser(cls, buf, offset):
meter_config = cls()
(meter_config.length, meter_config.flags,
meter_config.meter_id) = struct.unpack_from(
ofproto_v1_3.OFP_METER_CONFIG_PACK_STR, buf, offset)
offset += ofproto_v1_3.OFP_METER_CONFIG_SIZE
meter_config.bands = []
length = ofproto_v1_3.OFP_METER_CONFIG_SIZE
while length < meter_config.length:
band = OFPMeterBandHeader.parser(buf, offset)
meter_config.bands.append(band)
offset += band.len
length += band.len
return meter_config
@_set_stats_type(ofproto_v1_3.OFPMP_METER_CONFIG, OFPMeterConfigStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPMeterConfigStatsRequest(OFPMultipartRequest):
"""
Meter configuration statistics request message
The controller uses this message to query configuration for one or more
meters.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
meter_id ID of meter to read (OFPM_ALL to all meters)
================ ======================================================
Example::
def send_meter_config_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPMeterConfigStatsRequest(datapath, 0,
ofp.OFPM_ALL)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, meter_id, type_=None):
super(OFPMeterConfigStatsRequest, self).__init__(datapath, flags)
self.meter_id = meter_id
def _serialize_stats_body(self):
msg_pack_into(ofproto_v1_3.OFP_METER_MULTIPART_REQUEST_PACK_STR,
self.buf,
ofproto_v1_3.OFP_MULTIPART_REQUEST_SIZE,
self.meter_id)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_METER_CONFIG, OFPMeterConfigStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPMeterConfigStatsReply(OFPMultipartReply):
"""
Meter configuration statistics reply message
The switch responds with this message to a meter configuration
statistics request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPMeterConfigStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPMeterConfigStatsReply, MAIN_DISPATCHER)
def meter_config_stats_reply_handler(self, ev):
configs = []
for stat in ev.msg.body:
configs.append('length=%d flags=0x%04x meter_id=0x%08x '
'bands=%s' %
(stat.length, stat.flags, stat.meter_id,
stat.bands))
self.logger.debug('MeterConfigStats: %s', configs)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPMeterConfigStatsReply, self).__init__(datapath, **kwargs)
class OFPMeterFeaturesStats(ofproto_parser.namedtuple('OFPMeterFeaturesStats',
('max_meter', 'band_types', 'capabilities',
'max_band', 'max_color'))):
@classmethod
def parser(cls, buf, offset):
meter_features = struct.unpack_from(
ofproto_v1_3.OFP_METER_FEATURES_PACK_STR, buf, offset)
stats = cls(*meter_features)
stats.length = ofproto_v1_3.OFP_METER_FEATURES_SIZE
return stats
@_set_stats_type(ofproto_v1_3.OFPMP_METER_FEATURES, OFPMeterFeaturesStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPMeterFeaturesStatsRequest(OFPMultipartRequest):
"""
Meter features statistics request message
The controller uses this message to query the set of features of the
metering subsystem.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
================ ======================================================
Example::
def send_meter_features_stats_request(self, datapath):
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPMeterFeaturesStatsRequest(datapath, 0)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, type_=None):
super(OFPMeterFeaturesStatsRequest, self).__init__(datapath, flags)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_METER_FEATURES, OFPMeterFeaturesStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPMeterFeaturesStatsReply(OFPMultipartReply):
"""
Meter features statistics reply message
The switch responds with this message to a meter features statistics
request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPMeterFeaturesStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPMeterFeaturesStatsReply, MAIN_DISPATCHER)
def meter_features_stats_reply_handler(self, ev):
features = []
for stat in ev.msg.body:
features.append('max_meter=%d band_types=0x%08x '
'capabilities=0x%08x max_band=%d '
'max_color=%d' %
(stat.max_meter, stat.band_types,
stat.capabilities, stat.max_band,
stat.max_color))
self.logger.debug('MeterFeaturesStats: %s', configs)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPMeterFeaturesStatsReply, self).__init__(datapath, **kwargs)
class OFPTableFeaturesStats(StringifyMixin):
_TYPE = {
'utf-8': [
# OF spec is unclear about the encoding of name.
# we assumes UTF-8.
'name',
]
}
def __init__(self, table_id=None, name=None, metadata_match=None,
metadata_write=None, config=None, max_entries=None,
properties=None, length=None):
super(OFPTableFeaturesStats, self).__init__()
self.length = None
self.table_id = table_id
self.name = name
self.metadata_match = metadata_match
self.metadata_write = metadata_write
self.config = config
self.max_entries = max_entries
self.properties = properties
@classmethod
def parser(cls, buf, offset):
table_features = cls()
(table_features.length, table_features.table_id,
name, table_features.metadata_match,
table_features.metadata_write, table_features.config,
table_features.max_entries
) = struct.unpack_from(ofproto_v1_3.OFP_TABLE_FEATURES_PACK_STR,
buf, offset)
table_features.name = name.rstrip('\0')
props = []
rest = buf[offset + ofproto_v1_3.OFP_TABLE_FEATURES_SIZE:
offset + table_features.length]
while rest:
p, rest = OFPTableFeatureProp.parse(rest)
props.append(p)
table_features.properties = props
return table_features
def serialize(self):
# fixup
bin_props = bytearray()
for p in self.properties:
bin_props += p.serialize()
self.length = ofproto_v1_3.OFP_TABLE_FEATURES_SIZE + len(bin_props)
buf = bytearray()
msg_pack_into(ofproto_v1_3.OFP_TABLE_FEATURES_PACK_STR, buf, 0,
self.length, self.table_id, self.name,
self.metadata_match, self.metadata_write,
self.config, self.max_entries)
return buf + bin_props
class OFPTableFeatureProp(StringifyMixin):
_PACK_STR = '!HH' # type, length
_TYPES = {} # OFPTFPT_ -> class
def __init__(self, type_, length=None):
self.type = type_
self.length = length
@classmethod
def register_type(cls, type_):
def _register_type(subcls):
cls._TYPES[type_] = subcls
return subcls
return _register_type
@classmethod
def parse(cls, buf):
(type_, length,) = struct.unpack_from(cls._PACK_STR, buffer(buf), 0)
bin_prop = buf[struct.calcsize(cls._PACK_STR):length]
rest = buf[utils.round_up(length, 8):]
try:
subcls = cls._TYPES[type_]
except KeyError:
subcls = OFPTableFeaturePropUnknown
kwargs = subcls._parse_prop(bin_prop)
kwargs['type_'] = type_
kwargs['length'] = length
return subcls(**kwargs), rest
def serialize(self):
# fixup
bin_prop = self._serialize_prop()
self.length = struct.calcsize(self._PACK_STR) + len(bin_prop)
buf = bytearray()
msg_pack_into(self._PACK_STR, buf, 0, self.type, self.length)
pad_len = utils.round_up(self.length, 8) - self.length
return buf + bin_prop + pad_len * '\0'
class OFPTableFeaturePropUnknown(OFPTableFeatureProp):
def __init__(self, type_, length=None, data=None):
super(OFPTableFeaturePropUnknown, self).__init__(type_, length)
self.data = data
@classmethod
def _parse_prop(cls, buf):
return {'data': buf}
def _serialize_prop(self):
return self.data
# Implementation note: While OpenFlow 1.3.2 shares the same ofp_instruction
# for flow_mod and table_features, we have separate classes. We named this
# class to match with OpenFlow 1.4's name. (ofp_instruction_id)
class OFPInstructionId(StringifyMixin):
_PACK_STR = '!HH' # type, len
def __init__(self, type_, len_=None):
self.type = type_
self.len = len_
# XXX experimenter
@classmethod
def parse(cls, buf):
(type_, len_,) = struct.unpack_from(cls._PACK_STR, buffer(buf), 0)
rest = buf[len_:]
return cls(type_=type_, len_=len_), rest
def serialize(self):
# fixup
self.len = struct.calcsize(self._PACK_STR)
buf = bytearray()
msg_pack_into(self._PACK_STR, buf, 0, self.type, self.len)
return buf
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_INSTRUCTIONS)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_INSTRUCTIONS_MISS)
class OFPTableFeaturePropInstructions(OFPTableFeatureProp):
def __init__(self, type_, instruction_ids=[], length=None):
super(OFPTableFeaturePropInstructions, self).__init__(type_, length)
self.instruction_ids = instruction_ids
@classmethod
def _parse_prop(cls, buf):
rest = buf
ids = []
while rest:
i, rest = OFPInstructionId.parse(rest)
ids.append(i)
return {
'instruction_ids': ids,
}
def _serialize_prop(self):
bin_ids = bytearray()
for i in self.instruction_ids:
bin_ids += i.serialize()
return bin_ids
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_NEXT_TABLES)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_NEXT_TABLES_MISS)
class OFPTableFeaturePropNextTables(OFPTableFeatureProp):
_TABLE_ID_PACK_STR = '!B'
def __init__(self, type_, table_ids=[], length=None):
super(OFPTableFeaturePropNextTables, self).__init__(type_, length)
self.table_ids = table_ids
@classmethod
def _parse_prop(cls, buf):
rest = buf
ids = []
while rest:
(i,) = struct.unpack_from(cls._TABLE_ID_PACK_STR, buffer(rest), 0)
rest = rest[struct.calcsize(cls._TABLE_ID_PACK_STR):]
ids.append(i)
return {
'table_ids': ids,
}
def _serialize_prop(self):
bin_ids = bytearray()
for i in self.table_ids:
bin_id = bytearray()
msg_pack_into(self._TABLE_ID_PACK_STR, bin_id, 0, i)
bin_ids += bin_id
return bin_ids
# Implementation note: While OpenFlow 1.3.2 shares the same ofp_action_header
# for flow_mod and table_features, we have separate classes. We named this
# class to match with OpenFlow 1.4's name. (ofp_action_id)
class OFPActionId(StringifyMixin):
# XXX
# ofp_action_header should have trailing pad bytes.
# however, i guess it's a specification bug as:
# - the spec explicitly says non-experimenter actions are 4 bytes
# - linc/of_protocol doesn't use them
# - OpenFlow 1.4 changed to use a separate structure
_PACK_STR = '!HH' # type, len
def __init__(self, type_, len_=None):
self.type = type_
self.len = len_
# XXX experimenter
@classmethod
def parse(cls, buf):
(type_, len_,) = struct.unpack_from(cls._PACK_STR, buffer(buf), 0)
rest = buf[len_:]
return cls(type_=type_, len_=len_), rest
def serialize(self):
# fixup
self.len = struct.calcsize(self._PACK_STR)
buf = bytearray()
msg_pack_into(self._PACK_STR, buf, 0, self.type, self.len)
return buf
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_WRITE_ACTIONS)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_WRITE_ACTIONS_MISS)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_APPLY_ACTIONS)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_APPLY_ACTIONS_MISS)
class OFPTableFeaturePropActions(OFPTableFeatureProp):
def __init__(self, type_, action_ids=[], length=None):
super(OFPTableFeaturePropActions, self).__init__(type_, length)
self.action_ids = action_ids
@classmethod
def _parse_prop(cls, buf):
rest = buf
ids = []
while rest:
i, rest = OFPActionId.parse(rest)
ids.append(i)
return {
'action_ids': ids,
}
def _serialize_prop(self):
bin_ids = bytearray()
for i in self.action_ids:
bin_ids += i.serialize()
return bin_ids
# Implementation note: OFPOxmId is specific to this implementation.
# It does not have a corresponding structure in the specification.
# (the specification uses plain uint32_t for them.)
#
# i have taken a look at some of software switch implementations
# but they all look broken or incomplete. according to the spec,
# oxm_hasmask should be 1 if a switch supports masking for the type.
# the right value for oxm_length is not clear from the spec.
# ofsoftswitch13
# oxm_hasmask always 0
# oxm_length same as ofp_match etc (as without mask)
# linc/of_protocol
# oxm_hasmask always 0
# oxm_length always 0
# ovs:
# table-feature is not implemented
class OFPOxmId(StringifyMixin):
_PACK_STR = '!I' # oxm header
_TYPE = {
'ascii': [
'type',
],
}
def __init__(self, type_, hasmask=False, length=None):
self.type = type_
self.hasmask = hasmask
self.length = length
# XXX experimenter
@classmethod
def parse(cls, buf):
(oxm,) = struct.unpack_from(cls._PACK_STR, buffer(buf), 0)
(type_, _v) = ofproto_v1_3.oxm_to_user(oxm >> 9, None, None)
hasmask = ofproto_v1_3.oxm_tlv_header_extract_hasmask(oxm)
length = oxm & 0xff # XXX see the comment on OFPOxmId
rest = buf[4:] # XXX see the comment on OFPOxmId
return cls(type_=type_, hasmask=hasmask, length=length), rest
def serialize(self):
# fixup
self.length = 0 # XXX see the comment on OFPOxmId
(n, _v, _m) = ofproto_v1_3.oxm_from_user(self.type, None)
oxm = (n << 9) | (self.hasmask << 8) | self.length
buf = bytearray()
msg_pack_into(self._PACK_STR, buf, 0, oxm)
return buf
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_MATCH)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_WILDCARDS)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_WRITE_SETFIELD)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_WRITE_SETFIELD_MISS)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_APPLY_SETFIELD)
@OFPTableFeatureProp.register_type(ofproto_v1_3.OFPTFPT_APPLY_SETFIELD_MISS)
class OFPTableFeaturePropOxm(OFPTableFeatureProp):
def __init__(self, type_, oxm_ids=[], length=None):
super(OFPTableFeaturePropOxm, self).__init__(type_, length)
self.oxm_ids = oxm_ids
@classmethod
def _parse_prop(cls, buf):
rest = buf
ids = []
while rest:
i, rest = OFPOxmId.parse(rest)
ids.append(i)
return {
'oxm_ids': ids,
}
def _serialize_prop(self):
bin_ids = bytearray()
for i in self.oxm_ids:
bin_ids += i.serialize()
return bin_ids
# XXX ofproto_v1_3.OFPTFPT_EXPERIMENTER
# XXX ofproto_v1_3.OFPTFPT_EXPERIMENTER_MISS
@_set_stats_type(ofproto_v1_3.OFPMP_TABLE_FEATURES, OFPTableFeaturesStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPTableFeaturesStatsRequest(OFPMultipartRequest):
"""
Table features statistics request message
The controller uses this message to query table features.
This message is currently unimplemented.
"""
def __init__(self, datapath, flags,
body=[],
properties=[], type_=None):
super(OFPTableFeaturesStatsRequest, self).__init__(datapath, flags)
self.body = body
def _serialize_stats_body(self):
bin_body = bytearray()
for p in self.body:
bin_body += p.serialize()
self.buf += bin_body
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_TABLE_FEATURES, OFPTableFeaturesStats)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPTableFeaturesStatsReply(OFPMultipartReply):
"""
Table features statistics reply message
The switch responds with this message to a table features statistics
request.
This implmentation is still incomplete.
Namely, this implementation does not parse ``properties`` list and
always reports it empty.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPTableFeaturesStats`` instance
================ ======================================================
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPTableFeaturesStatsReply, self).__init__(datapath, **kwargs)
@_set_stats_type(ofproto_v1_3.OFPMP_PORT_DESC, OFPPort)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REQUEST)
class OFPPortDescStatsRequest(OFPMultipartRequest):
"""
Port description request message
The controller uses this message to query description of all the ports.
================ ======================================================
Attribute Description
================ ======================================================
flags Zero or ``OFPMPF_REQ_MORE``
================ ======================================================
Example::
def send_port_desc_stats_request(self, datapath):
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPPortDescStatsRequest(datapath, 0)
datapath.send_msg(req)
"""
def __init__(self, datapath, flags, type_=None):
super(OFPPortDescStatsRequest, self).__init__(datapath, flags)
@OFPMultipartReply.register_stats_type()
@_set_stats_type(ofproto_v1_3.OFPMP_PORT_DESC, OFPPort)
@_set_msg_type(ofproto_v1_3.OFPT_MULTIPART_REPLY)
class OFPPortDescStatsReply(OFPMultipartReply):
"""
Port description reply message
The switch responds with this message to a port description request.
================ ======================================================
Attribute Description
================ ======================================================
body List of ``OFPPortDescStats`` instance
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPPortDescStatsReply, MAIN_DISPATCHER)
def port_desc_stats_reply_handler(self, ev):
ports = []
for p in ev.msg.body:
ports.append('port_no=%d hw_addr=%s name=%s config=0x%08x '
'state=0x%08x curr=0x%08x advertised=0x%08x '
'supported=0x%08x peer=0x%08x curr_speed=%d '
'max_speed=%d' %
(p.port_no, p.hw_addr,
p.name, p.config,
p.state, p.curr, p.advertised,
p.supported, p.peer, p.curr_speed,
p.max_speed))
self.logger.debug('OFPPortDescStatsReply received: %s', ports)
"""
def __init__(self, datapath, type_=None, **kwargs):
super(OFPPortDescStatsReply, self).__init__(datapath, **kwargs)
# TODO: OFPMP_EXPERIMENTER
@_set_msg_type(ofproto_v1_3.OFPT_BARRIER_REQUEST)
class OFPBarrierRequest(MsgBase):
"""
Barrier request message
The controller sends this message to ensure message dependencies have
been met or receive notifications for completed operations.
Example::
def send_barrier_request(self, datapath):
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPBarrierRequest(datapath)
datapath.send_msg(req)
"""
def __init__(self, datapath):
super(OFPBarrierRequest, self).__init__(datapath)
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_BARRIER_REPLY)
class OFPBarrierReply(MsgBase):
"""
Barrier reply message
The switch responds with this message to a barrier request.
Example::
@set_ev_cls(ofp_event.EventOFPBarrierReply, MAIN_DISPATCHER)
def barrier_reply_handler(self, ev):
self.logger.debug('OFPBarrierReply received')
"""
def __init__(self, datapath):
super(OFPBarrierReply, self).__init__(datapath)
@_set_msg_type(ofproto_v1_3.OFPT_QUEUE_GET_CONFIG_REQUEST)
class OFPQueueGetConfigRequest(MsgBase):
"""
Queue configuration request message
================ ======================================================
Attribute Description
================ ======================================================
port Port to be queried (OFPP_ANY to all configured queues)
================ ======================================================
Example::
def send_queue_get_config_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPQueueGetConfigRequest(datapath, ofp.OFPP_ANY)
datapath.send_msg(req)
"""
def __init__(self, datapath, port):
super(OFPQueueGetConfigRequest, self).__init__(datapath)
self.port = port
def _serialize_body(self):
msg_pack_into(ofproto_v1_3.OFP_QUEUE_GET_CONFIG_REQUEST_PACK_STR,
self.buf, ofproto_v1_3.OFP_HEADER_SIZE, self.port)
class OFPQueuePropHeader(StringifyMixin):
def __init__(self, property_, len_):
self.property = property_
self.len = len_
def serialize(self, buf, offset):
msg_pack_into(ofproto_v1_3.OFP_QUEUE_PROP_HEADER_PACK_STR,
buf, offset, self.property, self.len)
class OFPQueueProp(OFPQueuePropHeader):
_QUEUE_PROP_PROPERTIES = {}
@staticmethod
def register_queue_property(property_, len_):
def _register_queue_property(cls):
cls.cls_property = property_
cls.cls_len = len_
OFPQueueProp._QUEUE_PROP_PROPERTIES[cls.cls_property] = cls
return cls
return _register_queue_property
def __init__(self):
cls = self.__class__
super(OFPQueueProp, self).__init__(cls.cls_property,
cls.cls_len)
@classmethod
def parser(cls, buf, offset):
(property_, len_) = struct.unpack_from(
ofproto_v1_3.OFP_QUEUE_PROP_HEADER_PACK_STR,
buf, offset)
cls_ = cls._QUEUE_PROP_PROPERTIES.get(property_)
offset += ofproto_v1_3.OFP_QUEUE_PROP_HEADER_SIZE
return cls_.parser(buf, offset)
@OFPQueueProp.register_queue_property(
ofproto_v1_3.OFPQT_MIN_RATE,
ofproto_v1_3.OFP_QUEUE_PROP_MIN_RATE_SIZE)
class OFPQueuePropMinRate(OFPQueueProp):
def __init__(self, rate, property_=None, len_=None):
super(OFPQueuePropMinRate, self).__init__()
self.rate = rate
@classmethod
def parser(cls, buf, offset):
(rate,) = struct.unpack_from(
ofproto_v1_3.OFP_QUEUE_PROP_MIN_RATE_PACK_STR, buf, offset)
return cls(rate)
@OFPQueueProp.register_queue_property(
ofproto_v1_3.OFPQT_MAX_RATE,
ofproto_v1_3.OFP_QUEUE_PROP_MAX_RATE_SIZE)
class OFPQueuePropMaxRate(OFPQueueProp):
def __init__(self, rate, property_=None, len_=None):
super(OFPQueuePropMaxRate, self).__init__()
self.rate = rate
@classmethod
def parser(cls, buf, offset):
(rate,) = struct.unpack_from(
ofproto_v1_3.OFP_QUEUE_PROP_MAX_RATE_PACK_STR, buf, offset)
return cls(rate)
# TODO: add ofp_queue_prop_experimenter
class OFPPacketQueue(StringifyMixin):
def __init__(self, queue_id, port, properties, len_=None):
super(OFPPacketQueue, self).__init__()
self.queue_id = queue_id
self.port = port
self.len = len_
self.properties = properties
@classmethod
def parser(cls, buf, offset):
(queue_id, port, len_) = struct.unpack_from(
ofproto_v1_3.OFP_PACKET_QUEUE_PACK_STR, buf, offset)
length = ofproto_v1_3.OFP_PACKET_QUEUE_SIZE
offset += ofproto_v1_3.OFP_PACKET_QUEUE_SIZE
properties = []
while length < len_:
queue_prop = OFPQueueProp.parser(buf, offset)
properties.append(queue_prop)
offset += queue_prop.len
length += queue_prop.len
o = cls(queue_id, port, properties)
o.len = len_
return o
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_QUEUE_GET_CONFIG_REPLY)
class OFPQueueGetConfigReply(MsgBase):
"""
Queue configuration reply message
The switch responds with this message to a queue configuration request.
================ ======================================================
Attribute Description
================ ======================================================
queues list of ``OFPPacketQueue`` instance
port Port which was queried
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPQueueGetConfigReply, MAIN_DISPATCHER)
def queue_get_config_reply_handler(self, ev):
msg = ev.msg
self.logger.debug('OFPQueueGetConfigReply received: '
'port=%s queues=%s',
msg.port, msg.queues)
"""
def __init__(self, datapath, queues=None, port=None):
super(OFPQueueGetConfigReply, self).__init__(datapath)
self.queues = queues
self.port = port
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPQueueGetConfigReply, cls).parser(datapath, version,
msg_type,
msg_len, xid, buf)
(msg.port,) = struct.unpack_from(
ofproto_v1_3.OFP_QUEUE_GET_CONFIG_REPLY_PACK_STR, msg.buf,
ofproto_v1_3.OFP_HEADER_SIZE)
msg.queues = []
offset = ofproto_v1_3.OFP_QUEUE_GET_CONFIG_REPLY_SIZE
while offset < msg_len:
queue = OFPPacketQueue.parser(msg.buf, offset)
msg.queues.append(queue)
offset += queue.len
return msg
@_set_msg_type(ofproto_v1_3.OFPT_ROLE_REQUEST)
class OFPRoleRequest(MsgBase):
"""
Role request message
The controller uses this message to change its role.
================ ======================================================
Attribute Description
================ ======================================================
role One of the following values.
OFPCR_ROLE_NOCHANGE
OFPCR_ROLE_EQUAL
OFPCR_ROLE_MASTER
OFPCR_ROLE_SLAVE
generation_id Master Election Generation ID
================ ======================================================
Example::
def send_role_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPRoleRequest(datapath, ofp.OFPCR_ROLE_EQUAL, 0)
datapath.send_msg(req)
"""
def __init__(self, datapath, role=None, generation_id=None):
super(OFPRoleRequest, self).__init__(datapath)
self.role = role
self.generation_id = generation_id
def _serialize_body(self):
assert self.role is not None
assert self.generation_id is not None
msg_pack_into(ofproto_v1_3.OFP_ROLE_REQUEST_PACK_STR,
self.buf, ofproto_v1_3.OFP_HEADER_SIZE,
self.role, self.generation_id)
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_ROLE_REPLY)
class OFPRoleReply(MsgBase):
"""
Role reply message
The switch responds with this message to a role request.
================ ======================================================
Attribute Description
================ ======================================================
role One of the following values.
OFPCR_ROLE_NOCHANGE
OFPCR_ROLE_EQUAL
OFPCR_ROLE_MASTER
OFPCR_ROLE_SLAVE
generation_id Master Election Generation ID
================ ======================================================
Example::
@set_ev_cls(ofp_event.EventOFPRoleReply, MAIN_DISPATCHER)
def role_reply_handler(self, ev):
msg = ev.msg
ofp = dp.ofproto
if msg.role == ofp.OFPCR_ROLE_NOCHANGE:
role = 'NOCHANGE'
elif msg.role == ofp.OFPCR_ROLE_EQUAL:
role = 'EQUAL'
elif msg.role == ofp.OFPCR_ROLE_MASTER:
role = 'MASTER'
elif msg.role == ofp.OFPCR_ROLE_SLAVE:
role = 'SLAVE'
else:
role = 'unknown'
self.logger.debug('OFPRoleReply received: '
'role=%s generation_id=%d',
role, msg.generation_id)
"""
def __init__(self, datapath, role=None, generation_id=None):
super(OFPRoleReply, self).__init__(datapath)
self.role = role
self.generation_id = generation_id
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPRoleReply, cls).parser(datapath, version,
msg_type, msg_len, xid,
buf)
(msg.role, msg.generation_id) = struct.unpack_from(
ofproto_v1_3.OFP_ROLE_REQUEST_PACK_STR, msg.buf,
ofproto_v1_3.OFP_HEADER_SIZE)
return msg
@_set_msg_type(ofproto_v1_3.OFPT_GET_ASYNC_REQUEST)
class OFPGetAsyncRequest(MsgBase):
"""
Get asynchronous configuration request message
The controller uses this message to query the asynchronous message.
Example::
def send_get_async_request(self, datapath):
ofp_parser = datapath.ofproto_parser
req = ofp_parser.OFPGetAsyncRequest(datapath)
datapath.send_msg(req)
"""
def __init__(self, datapath):
super(OFPGetAsyncRequest, self).__init__(datapath)
@_register_parser
@_set_msg_type(ofproto_v1_3.OFPT_GET_ASYNC_REPLY)
class OFPGetAsyncReply(MsgBase):
"""
Get asynchronous configuration reply message
The switch responds with this message to a get asynchronous configuration
request.
================== ====================================================
Attribute Description
================== ====================================================
packet_in_mask 2-element array: element 0, when the controller has a
OFPCR_ROLE_EQUAL or OFPCR_ROLE_MASTER role. element 1,
OFPCR_ROLE_SLAVE role controller.
Bitmasks of following values.
OFPR_NO_MATCH
OFPR_ACTION
OFPR_INVALID_TTL
port_status_mask 2-element array.
Bitmasks of following values.
OFPPR_ADD
OFPPR_DELETE
OFPPR_MODIFY
flow_removed_mask 2-element array.
Bitmasks of following values.
OFPRR_IDLE_TIMEOUT
OFPRR_HARD_TIMEOUT
OFPRR_DELETE
OFPRR_GROUP_DELETE
================== ====================================================
Example::
@set_ev_cls(ofp_event.EventOFPGetAsyncReply, MAIN_DISPATCHER)
def get_async_reply_handler(self, ev):
msg = ev.msg
self.logger.debug('OFPGetAsyncReply received: '
'packet_in_mask=0x%08x:0x%08x '
'port_status_mask=0x%08x:0x%08x '
'flow_removed_mask=0x%08x:0x%08x',
msg.packet_in_mask[0],
msg.packet_in_mask[1],
msg.port_status_mask[0],
msg.port_status_mask[1],
msg.flow_removed_mask[0],
msg.flow_removed_mask[1])
"""
def __init__(self, datapath, packet_in_mask=None, port_status_mask=None,
flow_removed_mask=None):
super(OFPGetAsyncReply, self).__init__(datapath)
self.packet_in_mask = packet_in_mask
self.port_status_mask = port_status_mask
self.flow_removed_mask = flow_removed_mask
@classmethod
def parser(cls, datapath, version, msg_type, msg_len, xid, buf):
msg = super(OFPGetAsyncReply, cls).parser(datapath, version,
msg_type, msg_len,
xid, buf)
(packet_in_mask_m, packet_in_mask_s,
port_status_mask_m, port_status_mask_s,
flow_removed_mask_m, flow_removed_mask_s) = struct.unpack_from(
ofproto_v1_3.OFP_ASYNC_CONFIG_PACK_STR, msg.buf,
ofproto_v1_3.OFP_HEADER_SIZE)
msg.packet_in_mask = [packet_in_mask_m, packet_in_mask_s]
msg.port_status_mask = [port_status_mask_m, port_status_mask_s]
msg.flow_removed_mask = [flow_removed_mask_m, flow_removed_mask_s]
return msg
@_set_msg_type(ofproto_v1_3.OFPT_SET_ASYNC)
class OFPSetAsync(MsgBase):
"""
Set asynchronous configuration message
The controller sends this message to set the asynchronous messages that
it wants to receive on a given OpneFlow channel.
================== ====================================================
Attribute Description
================== ====================================================
packet_in_mask 2-element array: element 0, when the controller has a
OFPCR_ROLE_EQUAL or OFPCR_ROLE_MASTER role. element 1,
OFPCR_ROLE_SLAVE role controller.
Bitmasks of following values.
OFPR_NO_MATCH
OFPR_ACTION
OFPR_INVALID_TTL
port_status_mask 2-element array.
Bitmasks of following values.
OFPPR_ADD
OFPPR_DELETE
OFPPR_MODIFY
flow_removed_mask 2-element array.
Bitmasks of following values.
OFPRR_IDLE_TIMEOUT
OFPRR_HARD_TIMEOUT
OFPRR_DELETE
OFPRR_GROUP_DELETE
================== ====================================================
Example::
def send_set_async(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
packet_in_mask = ofp.OFPR_ACTION | ofp.OFPR_INVALID_TTL
port_status_mask = (ofp.OFPPR_ADD | ofp.OFPPR_DELETE |
ofp.OFPPR_MODIFY)
flow_removed_mask = (ofp.OFPRR_IDLE_TIMEOUT |
ofp.OFPRR_HARD_TIMEOUT |
ofp.OFPRR_DELETE)
req = ofp_parser.OFPSetAsync(datapath,
[packet_in_mask, 0],
[port_status_mask, 0],
[flow_removed_mask, 0])
datapath.send_msg(req)
"""
def __init__(self, datapath,
packet_in_mask, port_status_mask, flow_removed_mask):
super(OFPSetAsync, self).__init__(datapath)
self.packet_in_mask = packet_in_mask
self.port_status_mask = port_status_mask
self.flow_removed_mask = flow_removed_mask
def _serialize_body(self):
msg_pack_into(ofproto_v1_3.OFP_ASYNC_CONFIG_PACK_STR, self.buf,
ofproto_v1_3.OFP_HEADER_SIZE,
self.packet_in_mask[0], self.packet_in_mask[1],
self.port_status_mask[0], self.port_status_mask[1],
self.flow_removed_mask[0], self.flow_removed_mask[1])
| apache-2.0 |
Neozaru/depot_tools | third_party/gsutil/gslib/commands/mv.py | 51 | 6213 | # Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from gslib.command import Command
from gslib.command import COMMAND_NAME
from gslib.command import COMMAND_NAME_ALIASES
from gslib.command import CONFIG_REQUIRED
from gslib.command import FILE_URIS_OK
from gslib.command import MAX_ARGS
from gslib.command import MIN_ARGS
from gslib.command import PROVIDER_URIS_OK
from gslib.command import SUPPORTED_SUB_ARGS
from gslib.command import URIS_START_ARG
from gslib.exception import CommandException
from gslib.help_provider import HELP_NAME
from gslib.help_provider import HELP_NAME_ALIASES
from gslib.help_provider import HELP_ONE_LINE_SUMMARY
from gslib.help_provider import HELP_TEXT
from gslib.help_provider import HelpType
from gslib.help_provider import HELP_TYPE
from gslib.util import NO_MAX
_detailed_help_text = ("""
<B>SYNOPSIS</B>
gsutil mv [-p] src_uri dst_uri
- or -
gsutil mv [-p] uri... dst_uri
<B>DESCRIPTION</B>
The gsutil mv command allows you to move data between your local file
system and the cloud, move data within the cloud, and move data between
cloud storage providers. For example, to move all objects from a
bucket to a local directory you could use:
gsutil mv gs://my_bucket dir
Similarly, to move all objects from a local directory to a bucket you could
use:
gsutil mv ./dir gs://my_bucket
<B>RENAMING BUCKET SUBDIRECTORIES</B>
You can use the gsutil mv command to rename subdirectories. For example,
the command:
gsutil mv gs://my_bucket/olddir gs://my_bucket/newdir
would rename all objects and subdirectories under gs://my_bucket/olddir to be
under gs://my_bucket/newdir, otherwise preserving the subdirectory structure.
If you do a rename as specified above and you want to preserve ACLs, you
should use the -p option (see OPTIONS).
Note that when using mv to rename bucket subdirectories you cannot specify
the source URI using wildcards. You need to spell out the complete name:
gsutil mv gs://my_bucket/olddir gs://my_bucket/newdir
If you have a large number of files to move you might want to use the
gsutil -m option, to perform a multi-threaded/multi-processing move:
gsutil -m mv gs://my_bucket/olddir gs://my_bucket/newdir
<B>NON-ATOMIC OPERATION</B>
Unlike the case with many file systems, the gsutil mv command does not
perform a single atomic operation. Rather, it performs a copy from source
to destination followed by removing the source for each object.
<B>OPTIONS</B>
-p Causes ACL to be preserved when moving in the cloud. Note that
this option has performance and cost implications, because it
is essentially performing three requests (getacl, cp, setacl).
(The performance issue can be mitigated to some degree by
using gsutil -m cp to cause multi-threaded/multi-processing
copying.)
""")
class MvCommand(Command):
"""Implementation of gsutil mv command.
Note that there is no atomic rename operation - this command is simply
a shorthand for 'cp' followed by 'rm'.
"""
# Command specification (processed by parent class).
command_spec = {
# Name of command.
COMMAND_NAME : 'mv',
# List of command name aliases.
COMMAND_NAME_ALIASES : ['move', 'ren', 'rename'],
# Min number of args required by this command.
MIN_ARGS : 2,
# Max number of args required by this command, or NO_MAX.
MAX_ARGS : NO_MAX,
# Getopt-style string specifying acceptable sub args.
SUPPORTED_SUB_ARGS : 'pv',
# True if file URIs acceptable for this command.
FILE_URIS_OK : True,
# True if provider-only URIs acceptable for this command.
PROVIDER_URIS_OK : False,
# Index in args of first URI arg.
URIS_START_ARG : 0,
# True if must configure gsutil before running command.
CONFIG_REQUIRED : True,
}
help_spec = {
# Name of command or auxiliary help info for which this help applies.
HELP_NAME : 'mv',
# List of help name aliases.
HELP_NAME_ALIASES : ['move', 'rename'],
# Type of help:
HELP_TYPE : HelpType.COMMAND_HELP,
# One line summary of this help.
HELP_ONE_LINE_SUMMARY : 'Move/rename objects and/or subdirectories',
# The full help text.
HELP_TEXT : _detailed_help_text,
}
# Command entry point.
def RunCommand(self):
# Check each source arg up, refusing to delete a bucket src URI (force users
# to explicitly do that as a separate operation).
for arg_to_check in self.args[0:-1]:
if self.suri_builder.StorageUri(arg_to_check).names_bucket():
raise CommandException('You cannot move a source bucket using the mv '
'command. If you meant to move\nall objects in '
'the bucket, you can use a command like:\n'
'\tgsutil mv %s/* %s' %
(arg_to_check, self.args[-1]))
# Insert command-line opts in front of args so they'll be picked up by cp
# and rm commands (e.g., for -p option). Use undocumented (internal
# use-only) cp -M option, which causes each original object to be deleted
# after successfully copying to its destination, and also causes naming
# behavior consistent with Unix mv naming behavior (see comments in
# _ConstructDstUri in cp.py).
unparsed_args = ['-M']
if self.recursion_requested:
unparsed_args.append('-R')
unparsed_args.extend(self.unparsed_args)
self.command_runner.RunNamedCommand('cp', unparsed_args, self.headers,
self.debug, self.parallel_operations)
return 0
| bsd-3-clause |
kevin8909/xjerp | openerp/addons/document/test_cindex.py | 444 | 1553 | #!/usr/bin/python
import sys
import os
import glob
import time
import logging
from optparse import OptionParser
logging.basicConfig(level=logging.DEBUG)
parser = OptionParser()
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
parser.add_option("-C", "--content",
action="store_true", dest="docontent", default=False,
help="Disect content, rather than the file.")
parser.add_option("--delay",
action="store_true", dest="delay", default=False,
help="delay after the operation, to inspect child processes")
(options, args) = parser.parse_args()
import content_index, std_index
from content_index import cntIndex
for fname in args:
try:
if options.docontent:
fp = open(fname,'rb')
content = fp.read()
fp.close()
res = cntIndex.doIndex(content, fname, None, None, True)
else:
res = cntIndex.doIndex(None, fname, None, fname,True)
if options.verbose:
for line in res[:5]:
print line
if options.delay:
time.sleep(30)
except Exception,e:
import traceback
tb_s = reduce(lambda x, y: x+y, traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback))
except KeyboardInterrupt:
print "Keyboard interrupt"
#eof
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
vipul-sharma20/oh-mainline | vendor/packages/Django/docs/_ext/djangodocs.py | 18 | 7624 | """
Sphinx plugins for Django documentation.
"""
import json
import os
import re
from docutils import nodes, transforms
from sphinx import addnodes, roles, __version__ as sphinx_ver
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.writers.html import SmartyPantsHTMLTranslator
from sphinx.util.console import bold
from sphinx.util.compat import Directive
# RE for option descriptions without a '--' prefix
simple_option_desc_re = re.compile(
r'([-_a-zA-Z0-9]+)(\s*.*?)(?=,\s+(?:/|-|--)|$)')
def setup(app):
app.add_crossref_type(
directivename = "setting",
rolename = "setting",
indextemplate = "pair: %s; setting",
)
app.add_crossref_type(
directivename = "templatetag",
rolename = "ttag",
indextemplate = "pair: %s; template tag"
)
app.add_crossref_type(
directivename = "templatefilter",
rolename = "tfilter",
indextemplate = "pair: %s; template filter"
)
app.add_crossref_type(
directivename = "fieldlookup",
rolename = "lookup",
indextemplate = "pair: %s; field lookup type",
)
app.add_description_unit(
directivename = "django-admin",
rolename = "djadmin",
indextemplate = "pair: %s; django-admin command",
parse_node = parse_django_admin_node,
)
app.add_description_unit(
directivename = "django-admin-option",
rolename = "djadminopt",
indextemplate = "pair: %s; django-admin command-line option",
parse_node = parse_django_adminopt_node,
)
app.add_config_value('django_next_version', '0.0', True)
app.add_directive('versionadded', VersionDirective)
app.add_directive('versionchanged', VersionDirective)
app.add_builder(DjangoStandaloneHTMLBuilder)
class VersionDirective(Directive):
has_content = True
required_arguments = 1
optional_arguments = 1
final_argument_whitespace = True
option_spec = {}
def run(self):
env = self.state.document.settings.env
ret = []
node = addnodes.versionmodified()
ret.append(node)
if self.arguments[0] == env.config.django_next_version:
node['version'] = "Development version"
else:
node['version'] = self.arguments[0]
node['type'] = self.name
if len(self.arguments) == 2:
inodes, messages = self.state.inline_text(self.arguments[1], self.lineno+1)
node.extend(inodes)
if self.content:
self.state.nested_parse(self.content, self.content_offset, node)
ret = ret + messages
env.note_versionchange(node['type'], node['version'], node, self.lineno)
return ret
class DjangoHTMLTranslator(SmartyPantsHTMLTranslator):
"""
Django-specific reST to HTML tweaks.
"""
# Don't use border=1, which docutils does by default.
def visit_table(self, node):
self.context.append(self.compact_p)
self.compact_p = True
self._table_row_index = 0 # Needed by Sphinx
self.body.append(self.starttag(node, 'table', CLASS='docutils'))
def depart_table(self, node):
self.compact_p = self.context.pop()
self.body.append('</table>\n')
def visit_desc_parameterlist(self, node):
self.body.append('(') # by default sphinx puts <big> around the "("
self.first_param = 1
self.optional_param_level = 0
self.param_separator = node.child_text_separator
self.required_params_left = sum([isinstance(c, addnodes.desc_parameter)
for c in node.children])
def depart_desc_parameterlist(self, node):
self.body.append(')')
if sphinx_ver < '1.0.8':
#
# Don't apply smartypants to literal blocks
#
def visit_literal_block(self, node):
self.no_smarty += 1
SmartyPantsHTMLTranslator.visit_literal_block(self, node)
def depart_literal_block(self, node):
SmartyPantsHTMLTranslator.depart_literal_block(self, node)
self.no_smarty -= 1
#
# Turn the "new in version" stuff (versionadded/versionchanged) into a
# better callout -- the Sphinx default is just a little span,
# which is a bit less obvious that I'd like.
#
# FIXME: these messages are all hardcoded in English. We need to change
# that to accommodate other language docs, but I can't work out how to make
# that work.
#
version_text = {
'deprecated': 'Deprecated in Django %s',
'versionchanged': 'Changed in Django %s',
'versionadded': 'New in Django %s',
}
def visit_versionmodified(self, node):
self.body.append(
self.starttag(node, 'div', CLASS=node['type'])
)
title = "%s%s" % (
self.version_text[node['type']] % node['version'],
len(node) and ":" or "."
)
self.body.append('<span class="title">%s</span> ' % title)
def depart_versionmodified(self, node):
self.body.append("</div>\n")
# Give each section a unique ID -- nice for custom CSS hooks
def visit_section(self, node):
old_ids = node.get('ids', [])
node['ids'] = ['s-' + i for i in old_ids]
node['ids'].extend(old_ids)
SmartyPantsHTMLTranslator.visit_section(self, node)
node['ids'] = old_ids
def parse_django_admin_node(env, sig, signode):
command = sig.split(' ')[0]
env._django_curr_admin_command = command
title = "django-admin.py %s" % sig
signode += addnodes.desc_name(title, title)
return sig
def parse_django_adminopt_node(env, sig, signode):
"""A copy of sphinx.directives.CmdoptionDesc.parse_signature()"""
from sphinx.domains.std import option_desc_re
count = 0
firstname = ''
for m in option_desc_re.finditer(sig):
optname, args = m.groups()
if count:
signode += addnodes.desc_addname(', ', ', ')
signode += addnodes.desc_name(optname, optname)
signode += addnodes.desc_addname(args, args)
if not count:
firstname = optname
count += 1
if not count:
for m in simple_option_desc_re.finditer(sig):
optname, args = m.groups()
if count:
signode += addnodes.desc_addname(', ', ', ')
signode += addnodes.desc_name(optname, optname)
signode += addnodes.desc_addname(args, args)
if not count:
firstname = optname
count += 1
if not firstname:
raise ValueError
return firstname
class DjangoStandaloneHTMLBuilder(StandaloneHTMLBuilder):
"""
Subclass to add some extra things we need.
"""
name = 'djangohtml'
def finish(self):
super(DjangoStandaloneHTMLBuilder, self).finish()
self.info(bold("writing templatebuiltins.js..."))
xrefs = self.env.domaindata["std"]["objects"]
templatebuiltins = {
"ttags": [n for ((t, n), (l, a)) in xrefs.items()
if t == "templatetag" and l == "ref/templates/builtins"],
"tfilters": [n for ((t, n), (l, a)) in xrefs.items()
if t == "templatefilter" and l == "ref/templates/builtins"],
}
outfilename = os.path.join(self.outdir, "templatebuiltins.js")
with open(outfilename, 'wb') as fp:
fp.write('var django_template_builtins = ')
json.dump(templatebuiltins, fp)
fp.write(';\n')
| agpl-3.0 |
idegtiarov/ceilometer | ceilometer/tests/unit/test_decoupled_pipeline.py | 5 | 11947 | #
# Copyright 2014 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import yaml
from ceilometer import pipeline
from ceilometer import sample
from ceilometer.tests import pipeline_base
class TestDecoupledPipeline(pipeline_base.BasePipelineTestCase):
def _setup_pipeline_cfg(self):
source = {'name': 'test_source',
'interval': 5,
'counters': ['a'],
'resources': [],
'sinks': ['test_sink']}
sink = {'name': 'test_sink',
'transformers': [{'name': 'update', 'parameters': {}}],
'publishers': ['test://']}
self.pipeline_cfg = {'sources': [source], 'sinks': [sink]}
def _augment_pipeline_cfg(self):
self.pipeline_cfg['sources'].append({
'name': 'second_source',
'interval': 5,
'counters': ['b'],
'resources': [],
'sinks': ['second_sink']
})
self.pipeline_cfg['sinks'].append({
'name': 'second_sink',
'transformers': [{
'name': 'update',
'parameters':
{
'append_name': '_new',
}
}],
'publishers': ['new'],
})
def _break_pipeline_cfg(self):
self.pipeline_cfg['sources'].append({
'name': 'second_source',
'interval': 5,
'counters': ['b'],
'resources': [],
'sinks': ['second_sink']
})
self.pipeline_cfg['sinks'].append({
'name': 'second_sink',
'transformers': [{
'name': 'update',
'parameters':
{
'append_name': '_new',
}
}],
'publishers': ['except'],
})
def _dup_pipeline_name_cfg(self):
self.pipeline_cfg['sources'].append({
'name': 'test_source',
'interval': 5,
'counters': ['b'],
'resources': [],
'sinks': ['test_sink']
})
def _set_pipeline_cfg(self, field, value):
if field in self.pipeline_cfg['sources'][0]:
self.pipeline_cfg['sources'][0][field] = value
else:
self.pipeline_cfg['sinks'][0][field] = value
def _extend_pipeline_cfg(self, field, value):
if field in self.pipeline_cfg['sources'][0]:
self.pipeline_cfg['sources'][0][field].extend(value)
else:
self.pipeline_cfg['sinks'][0][field].extend(value)
def _unset_pipeline_cfg(self, field):
if field in self.pipeline_cfg['sources'][0]:
del self.pipeline_cfg['sources'][0][field]
else:
del self.pipeline_cfg['sinks'][0][field]
def test_source_no_sink(self):
del self.pipeline_cfg['sinks']
self._exception_create_pipelinemanager()
def test_source_no_meters_or_counters(self):
del self.pipeline_cfg['sources'][0]['counters']
self._exception_create_pipelinemanager()
def test_source_dangling_sink(self):
self.pipeline_cfg['sources'].append({
'name': 'second_source',
'interval': 5,
'counters': ['b'],
'resources': [],
'sinks': ['second_sink']
})
self._exception_create_pipelinemanager()
def test_sink_no_source(self):
del self.pipeline_cfg['sources']
self._exception_create_pipelinemanager()
def test_source_with_multiple_sinks(self):
counter_cfg = ['a', 'b']
self._set_pipeline_cfg('counters', counter_cfg)
self.pipeline_cfg['sinks'].append({
'name': 'second_sink',
'transformers': [{
'name': 'update',
'parameters':
{
'append_name': '_new',
}
}],
'publishers': ['new'],
})
self.pipeline_cfg['sources'][0]['sinks'].append('second_sink')
pipeline_manager = pipeline.PipelineManager(self.pipeline_cfg,
self.transformer_manager)
with pipeline_manager.publisher(None) as p:
p([self.test_counter])
self.test_counter = sample.Sample(
name='b',
type=self.test_counter.type,
volume=self.test_counter.volume,
unit=self.test_counter.unit,
user_id=self.test_counter.user_id,
project_id=self.test_counter.project_id,
resource_id=self.test_counter.resource_id,
timestamp=self.test_counter.timestamp,
resource_metadata=self.test_counter.resource_metadata,
)
with pipeline_manager.publisher(None) as p:
p([self.test_counter])
self.assertEqual(2, len(pipeline_manager.pipelines))
self.assertEqual('test_source:test_sink',
str(pipeline_manager.pipelines[0]))
self.assertEqual('test_source:second_sink',
str(pipeline_manager.pipelines[1]))
test_publisher = pipeline_manager.pipelines[0].publishers[0]
new_publisher = pipeline_manager.pipelines[1].publishers[0]
for publisher, sfx in [(test_publisher, '_update'),
(new_publisher, '_new')]:
self.assertEqual(2, len(publisher.samples))
self.assertEqual(2, publisher.calls)
self.assertEqual('a' + sfx, getattr(publisher.samples[0], "name"))
self.assertEqual('b' + sfx, getattr(publisher.samples[1], "name"))
def test_multiple_sources_with_single_sink(self):
self.pipeline_cfg['sources'].append({
'name': 'second_source',
'interval': 5,
'counters': ['b'],
'resources': [],
'sinks': ['test_sink']
})
pipeline_manager = pipeline.PipelineManager(self.pipeline_cfg,
self.transformer_manager)
with pipeline_manager.publisher(None) as p:
p([self.test_counter])
self.test_counter = sample.Sample(
name='b',
type=self.test_counter.type,
volume=self.test_counter.volume,
unit=self.test_counter.unit,
user_id=self.test_counter.user_id,
project_id=self.test_counter.project_id,
resource_id=self.test_counter.resource_id,
timestamp=self.test_counter.timestamp,
resource_metadata=self.test_counter.resource_metadata,
)
with pipeline_manager.publisher(None) as p:
p([self.test_counter])
self.assertEqual(2, len(pipeline_manager.pipelines))
self.assertEqual('test_source:test_sink',
str(pipeline_manager.pipelines[0]))
self.assertEqual('second_source:test_sink',
str(pipeline_manager.pipelines[1]))
test_publisher = pipeline_manager.pipelines[0].publishers[0]
another_publisher = pipeline_manager.pipelines[1].publishers[0]
for publisher in [test_publisher, another_publisher]:
self.assertEqual(2, len(publisher.samples))
self.assertEqual(2, publisher.calls)
self.assertEqual('a_update', getattr(publisher.samples[0], "name"))
self.assertEqual('b_update', getattr(publisher.samples[1], "name"))
transformed_samples = self.TransformerClass.samples
self.assertEqual(2, len(transformed_samples))
self.assertEqual(['a', 'b'],
[getattr(s, 'name') for s in transformed_samples])
def _do_test_rate_of_change_in_boilerplate_pipeline_cfg(self, index,
meters, units):
with open('etc/ceilometer/pipeline.yaml') as fap:
data = fap.read()
pipeline_cfg = yaml.safe_load(data)
for s in pipeline_cfg['sinks']:
s['publishers'] = ['test://']
pipeline_manager = pipeline.PipelineManager(pipeline_cfg,
self.transformer_manager)
pipe = pipeline_manager.pipelines[index]
self._do_test_rate_of_change_mapping(pipe, meters, units)
def test_rate_of_change_boilerplate_disk_read_cfg(self):
meters = ('disk.read.bytes', 'disk.read.requests')
units = ('B', 'request')
self._do_test_rate_of_change_in_boilerplate_pipeline_cfg(3,
meters,
units)
def test_rate_of_change_boilerplate_disk_write_cfg(self):
meters = ('disk.write.bytes', 'disk.write.requests')
units = ('B', 'request')
self._do_test_rate_of_change_in_boilerplate_pipeline_cfg(3,
meters,
units)
def test_rate_of_change_boilerplate_network_incoming_cfg(self):
meters = ('network.incoming.bytes', 'network.incoming.packets')
units = ('B', 'packet')
self._do_test_rate_of_change_in_boilerplate_pipeline_cfg(4,
meters,
units)
def test_rate_of_change_boilerplate_per_disk_device_read_cfg(self):
meters = ('disk.device.read.bytes', 'disk.device.read.requests')
units = ('B', 'request')
self._do_test_rate_of_change_in_boilerplate_pipeline_cfg(3,
meters,
units)
def test_rate_of_change_boilerplate_per_disk_device_write_cfg(self):
meters = ('disk.device.write.bytes', 'disk.device.write.requests')
units = ('B', 'request')
self._do_test_rate_of_change_in_boilerplate_pipeline_cfg(3,
meters,
units)
def test_rate_of_change_boilerplate_network_outgoing_cfg(self):
meters = ('network.outgoing.bytes', 'network.outgoing.packets')
units = ('B', 'packet')
self._do_test_rate_of_change_in_boilerplate_pipeline_cfg(4,
meters,
units)
def test_duplicated_sinks_names(self):
self.pipeline_cfg['sinks'].append({
'name': 'test_sink',
'publishers': ['except'],
})
self.assertRaises(pipeline.PipelineException,
pipeline.PipelineManager,
self.pipeline_cfg,
self.transformer_manager)
def test_duplicated_source_names(self):
self.pipeline_cfg['sources'].append({
'name': 'test_source',
'interval': 5,
'counters': ['a'],
'resources': [],
'sinks': ['test_sink']
})
self.assertRaises(pipeline.PipelineException,
pipeline.PipelineManager,
self.pipeline_cfg,
self.transformer_manager)
| apache-2.0 |
faulkner/prospector | tests/profiles/test_profile.py | 3 | 3942 | import os
from unittest import TestCase
from prospector.profiles.profile import ProspectorProfile
class ProfileTestBase(TestCase):
def setUp(self):
self._profile_path = [
os.path.join(os.path.dirname(__file__), 'profiles'),
os.path.join(os.path.dirname(__file__), '../../prospector/profiles/profiles')
]
def _file_content(self, name):
path = os.path.join(self._profile_path, name)
with open(path) as f:
return f.read()
class TestProfileParsing(ProfileTestBase):
def test_empty_disable_list(self):
"""
This test verifies that a profile can still be loaded if it contains
an empty 'pylint.disable' list
"""
profile = ProspectorProfile.load('empty_disable_list', self._profile_path, allow_shorthand=False)
self.assertEqual([], profile.pylint['disable'])
def test_empty_profile(self):
"""
Verifies that a completely empty profile can still be parsed and have
default values
"""
profile = ProspectorProfile.load('empty_profile', self._profile_path, allow_shorthand=False)
self.assertEqual([], profile.pylint['disable'])
def test_ignores(self):
profile = ProspectorProfile.load('ignores', self._profile_path)
self.assertEqual(['^tests/', '/migrations/'].sort(), profile.ignore_patterns.sort())
def test_disable_tool(self):
profile = ProspectorProfile.load('pylint_disabled', self._profile_path)
self.assertFalse(profile.is_tool_enabled('pylint'))
self.assertTrue(profile.is_tool_enabled('pep8') is None)
class TestProfileInheritance(ProfileTestBase):
def _example_path(self, testname):
return os.path.join(os.path.dirname(__file__), 'profiles', 'inheritance', testname)
def _load(self, testname):
profile_path = self._profile_path + [self._example_path(testname)]
return ProspectorProfile.load('start', profile_path)
def test_simple_inheritance(self):
profile = ProspectorProfile.load('inherittest3', self._profile_path, allow_shorthand=False)
disable = profile.pylint['disable']
disable.sort()
self.assertEqual(['I0002', 'I0003', 'raw-checker-failed'], disable)
def test_disable_tool_inheritance(self):
profile = ProspectorProfile.load('pep8_and_pylint_disabled', self._profile_path)
self.assertFalse(profile.is_tool_enabled('pylint'))
self.assertFalse(profile.is_tool_enabled('pep8'))
def test_precedence(self):
profile = self._load('precedence')
self.assertTrue(profile.is_tool_enabled('pylint'))
self.assertTrue('expression-not-assigned' in profile.get_disabled_messages('pylint'))
def test_strictness_equivalence(self):
profile = self._load('strictness_equivalence')
medium_strictness = ProspectorProfile.load('strictness_medium', self._profile_path)
self.assertListEqual(sorted(profile.pylint['disable']), sorted(medium_strictness.pylint['disable']))
def test_shorthand_inheritance(self):
profile = self._load('shorthand_inheritance')
high_strictness = ProspectorProfile.load('strictness_high', self._profile_path,
# don't implicitly add things
allow_shorthand=False,
# but do include the profiles that the start.yaml will
forced_inherits=['doc_warnings', 'no_member_warnings']
)
self.assertDictEqual(profile.pylint, high_strictness.pylint)
self.assertDictEqual(profile.pep8, high_strictness.pep8)
self.assertDictEqual(profile.pyflakes, high_strictness.pyflakes)
def test_pep8_inheritance(self):
profile = self._load('pep8')
self.assertTrue(profile.is_tool_enabled('pep8'))
| gpl-2.0 |
leighpauls/k2cro4 | third_party/python_26/Lib/fractions.py | 53 | 20073 | # Originally contributed by Sjoerd Mullender.
# Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
"""Rational, infinite-precision, real numbers."""
from __future__ import division
import math
import numbers
import operator
import re
__all__ = ['Fraction', 'gcd']
Rational = numbers.Rational
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
_RATIONAL_FORMAT = re.compile(r"""
\A\s* # optional whitespace at the start, then
(?P<sign>[-+]?) # an optional sign, then
(?=\d|\.\d) # lookahead for digit or .digit
(?P<num>\d*) # numerator (possibly empty)
(?: # followed by an optional
/(?P<denom>\d+) # / and denominator
| # or
\.(?P<decimal>\d*) # decimal point and fractional part
)?
\s*\Z # and optional whitespace to finish
""", re.VERBOSE)
class Fraction(Rational):
"""This class implements rational numbers.
Fraction(8, 6) will produce a rational number equivalent to
4/3. Both arguments must be Integral. The numerator defaults to 0
and the denominator defaults to 1 so that Fraction(3) == 3 and
Fraction() == 0.
Fractions can also be constructed from strings of the form
'[-+]?[0-9]+((/|.)[0-9]+)?', optionally surrounded by spaces.
"""
__slots__ = ('_numerator', '_denominator')
# We're immutable, so use __new__ not __init__
def __new__(cls, numerator=0, denominator=1):
"""Constructs a Fraction.
Takes a string like '3/2' or '1.5', another Fraction, or a
numerator/denominator pair.
"""
self = super(Fraction, cls).__new__(cls)
if type(numerator) not in (int, long) and denominator == 1:
if isinstance(numerator, basestring):
# Handle construction from strings.
input = numerator
m = _RATIONAL_FORMAT.match(input)
if m is None:
raise ValueError('Invalid literal for Fraction: %r' % input)
numerator = m.group('num')
decimal = m.group('decimal')
if decimal:
# The literal is a decimal number.
numerator = int(numerator + decimal)
denominator = 10**len(decimal)
else:
# The literal is an integer or fraction.
numerator = int(numerator)
# Default denominator to 1.
denominator = int(m.group('denom') or 1)
if m.group('sign') == '-':
numerator = -numerator
elif isinstance(numerator, Rational):
# Handle copies from other rationals. Integrals get
# caught here too, but it doesn't matter because
# denominator is already 1.
other_rational = numerator
numerator = other_rational.numerator
denominator = other_rational.denominator
if denominator == 0:
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
numerator = operator.index(numerator)
denominator = operator.index(denominator)
g = gcd(numerator, denominator)
self._numerator = numerator // g
self._denominator = denominator // g
return self
@classmethod
def from_float(cls, f):
"""Converts a finite float to a rational number, exactly.
Beware that Fraction.from_float(0.3) != Fraction(3, 10).
"""
if isinstance(f, numbers.Integral):
return cls(f)
elif not isinstance(f, float):
raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
(cls.__name__, f, type(f).__name__))
if math.isnan(f) or math.isinf(f):
raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
return cls(*f.as_integer_ratio())
@classmethod
def from_decimal(cls, dec):
"""Converts a finite Decimal instance to a rational number, exactly."""
from decimal import Decimal
if isinstance(dec, numbers.Integral):
dec = Decimal(int(dec))
elif not isinstance(dec, Decimal):
raise TypeError(
"%s.from_decimal() only takes Decimals, not %r (%s)" %
(cls.__name__, dec, type(dec).__name__))
if not dec.is_finite():
# Catches infinities and nans.
raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
sign, digits, exp = dec.as_tuple()
digits = int(''.join(map(str, digits)))
if sign:
digits = -digits
if exp >= 0:
return cls(digits * 10 ** exp)
else:
return cls(digits, 10 ** -exp)
def limit_denominator(self, max_denominator=1000000):
"""Closest Fraction to self with denominator at most max_denominator.
>>> Fraction('3.141592653589793').limit_denominator(10)
Fraction(22, 7)
>>> Fraction('3.141592653589793').limit_denominator(100)
Fraction(311, 99)
>>> Fraction(1234, 5678).limit_denominator(10000)
Fraction(1234, 5678)
"""
# Algorithm notes: For any real number x, define a *best upper
# approximation* to x to be a rational number p/q such that:
#
# (1) p/q >= x, and
# (2) if p/q > r/s >= x then s > q, for any rational r/s.
#
# Define *best lower approximation* similarly. Then it can be
# proved that a rational number is a best upper or lower
# approximation to x if, and only if, it is a convergent or
# semiconvergent of the (unique shortest) continued fraction
# associated to x.
#
# To find a best rational approximation with denominator <= M,
# we find the best upper and lower approximations with
# denominator <= M and take whichever of these is closer to x.
# In the event of a tie, the bound with smaller denominator is
# chosen. If both denominators are equal (which can happen
# only when max_denominator == 1 and self is midway between
# two integers) the lower bound---i.e., the floor of self, is
# taken.
if max_denominator < 1:
raise ValueError("max_denominator should be at least 1")
if self._denominator <= max_denominator:
return Fraction(self)
p0, q0, p1, q1 = 0, 1, 1, 0
n, d = self._numerator, self._denominator
while True:
a = n//d
q2 = q0+a*q1
if q2 > max_denominator:
break
p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
n, d = d, n-a*d
k = (max_denominator-q0)//q1
bound1 = Fraction(p0+k*p1, q0+k*q1)
bound2 = Fraction(p1, q1)
if abs(bound2 - self) <= abs(bound1-self):
return bound2
else:
return bound1
@property
def numerator(a):
return a._numerator
@property
def denominator(a):
return a._denominator
def __repr__(self):
"""repr(self)"""
return ('Fraction(%s, %s)' % (self._numerator, self._denominator))
def __str__(self):
"""str(self)"""
if self._denominator == 1:
return str(self._numerator)
else:
return '%s/%s' % (self._numerator, self._denominator)
def _operator_fallbacks(monomorphic_operator, fallback_operator):
"""Generates forward and reverse operators given a purely-rational
operator and a function from the operator module.
Use this like:
__op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
In general, we want to implement the arithmetic operations so
that mixed-mode operations either call an implementation whose
author knew about the types of both arguments, or convert both
to the nearest built in type and do the operation there. In
Fraction, that means that we define __add__ and __radd__ as:
def __add__(self, other):
# Both types have numerators/denominator attributes,
# so do the operation directly
if isinstance(other, (int, long, Fraction)):
return Fraction(self.numerator * other.denominator +
other.numerator * self.denominator,
self.denominator * other.denominator)
# float and complex don't have those operations, but we
# know about those types, so special case them.
elif isinstance(other, float):
return float(self) + other
elif isinstance(other, complex):
return complex(self) + other
# Let the other type take over.
return NotImplemented
def __radd__(self, other):
# radd handles more types than add because there's
# nothing left to fall back to.
if isinstance(other, Rational):
return Fraction(self.numerator * other.denominator +
other.numerator * self.denominator,
self.denominator * other.denominator)
elif isinstance(other, Real):
return float(other) + float(self)
elif isinstance(other, Complex):
return complex(other) + complex(self)
return NotImplemented
There are 5 different cases for a mixed-type addition on
Fraction. I'll refer to all of the above code that doesn't
refer to Fraction, float, or complex as "boilerplate". 'r'
will be an instance of Fraction, which is a subtype of
Rational (r : Fraction <: Rational), and b : B <:
Complex. The first three involve 'r + b':
1. If B <: Fraction, int, float, or complex, we handle
that specially, and all is well.
2. If Fraction falls back to the boilerplate code, and it
were to return a value from __add__, we'd miss the
possibility that B defines a more intelligent __radd__,
so the boilerplate should return NotImplemented from
__add__. In particular, we don't handle Rational
here, even though we could get an exact answer, in case
the other type wants to do something special.
3. If B <: Fraction, Python tries B.__radd__ before
Fraction.__add__. This is ok, because it was
implemented with knowledge of Fraction, so it can
handle those instances before delegating to Real or
Complex.
The next two situations describe 'b + r'. We assume that b
didn't know about Fraction in its implementation, and that it
uses similar boilerplate code:
4. If B <: Rational, then __radd_ converts both to the
builtin rational type (hey look, that's us) and
proceeds.
5. Otherwise, __radd__ tries to find the nearest common
base ABC, and fall back to its builtin type. Since this
class doesn't subclass a concrete type, there's no
implementation to fall back to, so we need to try as
hard as possible to return an actual value, or the user
will get a TypeError.
"""
def forward(a, b):
if isinstance(b, (int, long, Fraction)):
return monomorphic_operator(a, b)
elif isinstance(b, float):
return fallback_operator(float(a), b)
elif isinstance(b, complex):
return fallback_operator(complex(a), b)
else:
return NotImplemented
forward.__name__ = '__' + fallback_operator.__name__ + '__'
forward.__doc__ = monomorphic_operator.__doc__
def reverse(b, a):
if isinstance(a, Rational):
# Includes ints.
return monomorphic_operator(a, b)
elif isinstance(a, numbers.Real):
return fallback_operator(float(a), float(b))
elif isinstance(a, numbers.Complex):
return fallback_operator(complex(a), complex(b))
else:
return NotImplemented
reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
reverse.__doc__ = monomorphic_operator.__doc__
return forward, reverse
def _add(a, b):
"""a + b"""
return Fraction(a.numerator * b.denominator +
b.numerator * a.denominator,
a.denominator * b.denominator)
__add__, __radd__ = _operator_fallbacks(_add, operator.add)
def _sub(a, b):
"""a - b"""
return Fraction(a.numerator * b.denominator -
b.numerator * a.denominator,
a.denominator * b.denominator)
__sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
def _mul(a, b):
"""a * b"""
return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
__mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
def _div(a, b):
"""a / b"""
return Fraction(a.numerator * b.denominator,
a.denominator * b.numerator)
__truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
__div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
def __floordiv__(a, b):
"""a // b"""
# Will be math.floor(a / b) in 3.0.
div = a / b
if isinstance(div, Rational):
# trunc(math.floor(div)) doesn't work if the rational is
# more precise than a float because the intermediate
# rounding may cross an integer boundary.
return div.numerator // div.denominator
else:
return math.floor(div)
def __rfloordiv__(b, a):
"""a // b"""
# Will be math.floor(a / b) in 3.0.
div = a / b
if isinstance(div, Rational):
# trunc(math.floor(div)) doesn't work if the rational is
# more precise than a float because the intermediate
# rounding may cross an integer boundary.
return div.numerator // div.denominator
else:
return math.floor(div)
def __mod__(a, b):
"""a % b"""
div = a // b
return a - b * div
def __rmod__(b, a):
"""a % b"""
div = a // b
return a - b * div
def __pow__(a, b):
"""a ** b
If b is not an integer, the result will be a float or complex
since roots are generally irrational. If b is an integer, the
result will be rational.
"""
if isinstance(b, Rational):
if b.denominator == 1:
power = b.numerator
if power >= 0:
return Fraction(a._numerator ** power,
a._denominator ** power)
else:
return Fraction(a._denominator ** -power,
a._numerator ** -power)
else:
# A fractional power will generally produce an
# irrational number.
return float(a) ** float(b)
else:
return float(a) ** b
def __rpow__(b, a):
"""a ** b"""
if b._denominator == 1 and b._numerator >= 0:
# If a is an int, keep it that way if possible.
return a ** b._numerator
if isinstance(a, Rational):
return Fraction(a.numerator, a.denominator) ** b
if b._denominator == 1:
return a ** b._numerator
return a ** float(b)
def __pos__(a):
"""+a: Coerces a subclass instance to Fraction"""
return Fraction(a._numerator, a._denominator)
def __neg__(a):
"""-a"""
return Fraction(-a._numerator, a._denominator)
def __abs__(a):
"""abs(a)"""
return Fraction(abs(a._numerator), a._denominator)
def __trunc__(a):
"""trunc(a)"""
if a._numerator < 0:
return -(-a._numerator // a._denominator)
else:
return a._numerator // a._denominator
def __hash__(self):
"""hash(self)
Tricky because values that are exactly representable as a
float must have the same hash as that float.
"""
# XXX since this method is expensive, consider caching the result
if self._denominator == 1:
# Get integers right.
return hash(self._numerator)
# Expensive check, but definitely correct.
if self == float(self):
return hash(float(self))
else:
# Use tuple's hash to avoid a high collision rate on
# simple fractions.
return hash((self._numerator, self._denominator))
def __eq__(a, b):
"""a == b"""
if isinstance(b, Rational):
return (a._numerator == b.numerator and
a._denominator == b.denominator)
if isinstance(b, numbers.Complex) and b.imag == 0:
b = b.real
if isinstance(b, float):
return a == a.from_float(b)
else:
# XXX: If b.__eq__ is implemented like this method, it may
# give the wrong answer after float(a) changes a's
# value. Better ways of doing this are welcome.
return float(a) == b
def _subtractAndCompareToZero(a, b, op):
"""Helper function for comparison operators.
Subtracts b from a, exactly if possible, and compares the
result with 0 using op, in such a way that the comparison
won't recurse. If the difference raises a TypeError, returns
NotImplemented instead.
"""
if isinstance(b, numbers.Complex) and b.imag == 0:
b = b.real
if isinstance(b, float):
b = a.from_float(b)
try:
# XXX: If b <: Real but not <: Rational, this is likely
# to fall back to a float. If the actual values differ by
# less than MIN_FLOAT, this could falsely call them equal,
# which would make <= inconsistent with ==. Better ways of
# doing this are welcome.
diff = a - b
except TypeError:
return NotImplemented
if isinstance(diff, Rational):
return op(diff.numerator, 0)
return op(diff, 0)
def __lt__(a, b):
"""a < b"""
return a._subtractAndCompareToZero(b, operator.lt)
def __gt__(a, b):
"""a > b"""
return a._subtractAndCompareToZero(b, operator.gt)
def __le__(a, b):
"""a <= b"""
return a._subtractAndCompareToZero(b, operator.le)
def __ge__(a, b):
"""a >= b"""
return a._subtractAndCompareToZero(b, operator.ge)
def __nonzero__(a):
"""a != 0"""
return a._numerator != 0
# support for pickling, copy, and deepcopy
def __reduce__(self):
return (self.__class__, (str(self),))
def __copy__(self):
if type(self) == Fraction:
return self # I'm immutable; therefore I am my own clone
return self.__class__(self._numerator, self._denominator)
def __deepcopy__(self, memo):
if type(self) == Fraction:
return self # My components are also immutable
return self.__class__(self._numerator, self._denominator)
| bsd-3-clause |
maljac/odoomrp-wip | machine_manager/models/machinery.py | 14 | 5549 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
##############################################################################
from openerp import models, fields, _
class Machinery(models.Model):
_name = "machinery"
_description = "Holds records of Machines"
def _def_company(self):
return self.env.user.company_id.id
name = fields.Char('Machine Name', required=True)
company = fields.Many2one('res.company', 'Company', required=True,
default=_def_company)
assetacc = fields.Many2one('account.account', string='Asset Account')
depracc = fields.Many2one('account.account', string='Depreciation Account')
year = fields.Char('Year')
model = fields.Char('Model')
product = fields.Many2one(
comodel_name='product.product', string='Associated product',
help="This product will contain information about the machine such as"
" the manufacturer.")
manufacturer = fields.Many2one(
comodel_name='res.partner', related='product.manufacturer',
readonly=True, help="Manufacturer is related to the associated product"
" defined for the machine.")
serial_char = fields.Char('Product Serial #')
serial = fields.Many2one('stock.production.lot', string='Product Serial #',
domain="[('product_id', '=', product)]")
model_type = fields.Many2one('machine.model', 'Type')
status = fields.Selection([('active', 'Active'), ('inactive', 'InActive'),
('outofservice', 'Out of Service')],
'Status', required=True, default='active')
ownership = fields.Selection([('own', 'Own'), ('lease', 'Lease'),
('rental', 'Rental')],
'Ownership', default='own', required=True)
bcyl = fields.Float('Base Cycles', digits=(16, 3),
help="Last recorded cycles")
bdate = fields.Date('Record Date',
help="Date on which the cycles is recorded")
purch_date = fields.Date('Purchase Date',
help="Machine's date of purchase")
purch_cost = fields.Float('Purchase Value', digits=(16, 2))
purch_partner = fields.Many2one('res.partner', 'Purchased From')
purch_inv = fields.Many2one('account.invoice', string='Purchase Invoice')
purch_cycles = fields.Integer('Cycles at Purchase')
actcycles = fields.Integer('Actual Cycles')
deprecperc = fields.Float('Depreciation in %', digits=(10, 2))
deprecperiod = fields.Selection([('monthly', 'Monthly'),
('quarterly', 'Quarterly'),
('halfyearly', 'Half Yearly'),
('annual', 'Yearly')], 'Depr. period',
default='annual', required=True)
primarymeter = fields.Selection([('calendar', 'Calendar'),
('cycles', 'Cycles'),
('hourmeter', 'Hour Meter')],
'Primary Meter', default='cycles',
required=True)
warrexp = fields.Date('Date', help="Expiry date for warranty of product")
warrexpcy = fields.Integer('(or) cycles',
help="Expiry cycles for warranty of product")
location = fields.Many2one('stock.location', 'Stk Location',
help="This association is necessary if you want"
" to make repair orders with the machine")
enrolldate = fields.Date('Enrollment date', required=True,
default=lambda
self: fields.Date.context_today(self))
ambit = fields.Selection([('local', 'Local'), ('national', 'National'),
('international', 'International')],
'Ambit', default='local')
card = fields.Char('Card')
cardexp = fields.Date('Card Expiration')
frame = fields.Char('Frame Number')
phone = fields.Char('Phone number')
mac = fields.Char('MAC Address')
insurance = fields.Char('Insurance Name')
policy = fields.Char('Machine policy')
users = fields.One2many('machinery.users', 'machine', 'Machine Users')
power = fields.Char('Power (Kw)')
class MachineryUsers(models.Model):
_name = 'machinery.users'
m_user = fields.Many2one('res.users', 'User')
machine = fields.Many2one('machinery', 'Machine')
start_date = fields.Date('Homologation Start Date')
end_date = fields.Date('Homologation End Date')
_sql_constraints = [
('uniq_machine_user', 'unique(machine, m_user)',
_('User already defined for the machine'))
]
| agpl-3.0 |
mjn19172/Savu | savu/test/test_utils.py | 2 | 4791 | # Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
.. module:: test_utils
:platform: Unix
:synopsis: utilities for the test framework
.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>
"""
import inspect
import tempfile
import os
import savu.plugins.utils as pu
from savu.data.structures import Data, PassThrough
from savu.data.structures import RawTimeseriesData, ProjectionData, VolumeData
def get_test_data_path(name):
"""Gets the full path to the test data
:param name: The name of the test file.
:type name: str
:returns: The full path to the example data.
"""
path = inspect.stack()[0][1]
return '/'.join(os.path.split(path)[0].split(os.sep)[:-2] +
['test_data', name])
def get_nx_tomo_test_data():
"""Gets the nx_tomo test data and returns it in the RawData Structure
:returns: a RawTimeseriesData Object containing the example data.
"""
path = get_test_data_path('24737.nxs')
raw_timeseries_data = RawTimeseriesData()
raw_timeseries_data.populate_from_nx_tomo(path)
return raw_timeseries_data
def get_projection_test_data():
"""Gets the test data and returns it in the ProjectionData Structure
:returns: a ProjectionData Object containing the example data.
"""
path = get_test_data_path('projections.h5')
projection_data = ProjectionData()
projection_data.populate_from_h5(path)
return projection_data
def get_appropriate_input_data(plugin):
data = []
if plugin.required_data_type() == RawTimeseriesData:
data.append(get_nx_tomo_test_data())
elif plugin.required_data_type() == ProjectionData:
data.append(get_projection_test_data())
elif plugin.required_data_type() == Data:
data.append(get_nx_tomo_test_data())
data.append(get_projection_test_data())
return data
def get_appropriate_output_data(plugin, data, mpi=False, file_name=None):
output = []
if plugin.output_data_type() == PassThrough:
output.append(data[0])
temp_file = file_name
if temp_file is None:
temp_file = tempfile.NamedTemporaryFile(suffix='.h5', delete=False)
temp_file = temp_file.name
if plugin.output_data_type() == RawTimeseriesData:
output.append(pu.get_raw_data(data[0], temp_file,
plugin.name, mpi,
plugin.get_output_shape(data[0])))
elif plugin.output_data_type() == ProjectionData:
output.append(pu.get_projection_data(data[0], temp_file,
plugin.name, mpi,
plugin.get_output_shape(data[0])))
elif plugin.output_data_type() == VolumeData:
output.append(pu.get_volume_data(data[0], temp_file,
plugin.name, mpi,
plugin.get_output_shape(data[0])))
elif plugin.output_data_type() == Data:
if type(data) is not list:
data = [data]
for datum in data:
if file_name is None:
temp_file = tempfile.NamedTemporaryFile(suffix='.h5',
delete=False)
temp_file = temp_file.name
if isinstance(datum, RawTimeseriesData):
output.append(pu.get_raw_data(datum, temp_file,
plugin.name, mpi,
plugin.get_output_shape(datum)))
elif isinstance(datum, ProjectionData):
output.append(pu.get_projection_data(datum, temp_file,
plugin.name, mpi,
plugin.get_output_shape(
datum)))
elif isinstance(datum, VolumeData):
output.append(pu.get_volume_data(datum, temp_file,
plugin.name, mpi,
plugin.get_output_shape(
datum)))
return output
| apache-2.0 |
ryfeus/lambda-packs | Tensorflow/source/tensorflow/contrib/quantize/python/quantize_graph.py | 7 | 4264 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""API to simulate quantization on a python graph."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.quantize.python import copy_graph
from tensorflow.contrib.quantize.python import fold_batch_norms
from tensorflow.contrib.quantize.python import quantize
from tensorflow.python.framework import ops
from tensorflow.python.ops import variables
def _create_graph(input_graph, is_training, elements=None):
"""Returns a transformed training input_graph for simulated quantization.
The forward pass has fake quantization ops inserted to simulate the error
introduced by quantization.
Args:
input_graph: The tf.Graph to be transformed.
is_training: Whether quantizing training or eval graph.
elements: (Optional) List of Tensors and Operations in input_graph whose
corresponding elements in the new graph will be returned.
Returns:
Returns a tuple(g, l) where:
g is new tf.Graph that is rewritten for simulated quantization.
l is a list of Tensors/Operations in g corresponding to the provided input
elements.
Raises:
ValueError: If elements contains an element that isn't a tf.Tensor or
tf.Operation.
"""
# TODO(suharshs): Describe the process in more detail in the doc string.
g = copy_graph.CopyGraph(input_graph)
fold_batch_norms.FoldBatchNorms(g)
quantize.Quantize(g, is_training=is_training)
return_elements = []
if elements is None:
elements = []
for element in elements:
if isinstance(element, (ops.Tensor, variables.Variable)):
return_elements.append(g.get_tensor_by_name(element.name))
elif isinstance(element, ops.Operation):
return_elements.append(g.get_operation_by_name(element.name))
else:
raise ValueError(
'elements must consist of Tensor or Operation objects, got: ',
str(element))
return g, return_elements
def create_training_graph(input_graph, elements=None):
"""Returns a transformed training input_graph for simulated quantization.
The forward pass has fake quantization ops inserted to simulate the error
introduced by quantization.
Args:
input_graph: The tf.Graph to be transformed.
elements: (Optional) List of Tensors and Operations in input_graph whose
corresponding elements in the new graph will be returned.
Returns:
Returns a tuple(g, l) where:
g is new tf.Graph that is rewritten for simulated quantization.
l is a list of Tensors/Operations in g corresponding to the provided input
elements.
Raises:
ValueError: If elements contains an element that isn't a tf.Tensor or
tf.Operation.
"""
return _create_graph(input_graph, True, elements)
def create_eval_graph(input_graph, elements=None):
"""Returns a transformed eval input_graph for simulated quantization.
The forward pass has fake quantization ops inserted to simulate the error
introduced by quantization.
Args:
input_graph: The tf.Graph to be transformed.
elements: (Optional) List of Tensors and Operations in input_graph whose
corresponding elements in the new graph will be returned.
Returns:
Returns a tuple(g, l) where:
g is new tf.Graph that is rewritten for simulated quantization.
l is a list of Tensors/Operations in g corresponding to the provided input
elements.
Raises:
ValueError: If elements contains an element that isn't a tf.Tensor or
tf.Operation.
"""
return _create_graph(input_graph, False, elements)
| mit |
devoid/nova | nova/tests/api/openstack/compute/plugins/v3/test_access_ips.py | 20 | 12698 | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import webob
from nova.api.openstack.compute.plugins.v3 import access_ips
from nova.api.openstack import wsgi
from nova import test
from nova.tests.api.openstack import fakes
class AccessIPsExtTest(test.NoDBTestCase):
def setUp(self):
super(AccessIPsExtTest, self).setUp()
self.access_ips_ext = access_ips.AccessIPs(None)
def _test(self, func):
server_dict = {access_ips.AccessIPs.v4_key: '1.1.1.1',
access_ips.AccessIPs.v6_key: 'fe80::'}
create_kwargs = {}
func(server_dict, create_kwargs)
self.assertEqual(create_kwargs, {'access_ip_v4': '1.1.1.1',
'access_ip_v6': 'fe80::'})
def _test_with_ipv4_only(self, func):
server_dict = {access_ips.AccessIPs.v4_key: '1.1.1.1'}
create_kwargs = {}
func(server_dict, create_kwargs)
self.assertEqual(create_kwargs, {'access_ip_v4': '1.1.1.1'})
def _test_with_ipv6_only(self, func):
server_dict = {access_ips.AccessIPs.v6_key: 'fe80::'}
create_kwargs = {}
func(server_dict, create_kwargs)
self.assertEqual(create_kwargs, {'access_ip_v6': 'fe80::'})
def _test_without_ipv4_and_ipv6(self, func):
server_dict = {}
create_kwargs = {}
func(server_dict, create_kwargs)
self.assertEqual(create_kwargs, {})
def _test_with_invalid_ipv4(self, func):
server_dict = {access_ips.AccessIPs.v4_key: '1.1.1.1.1.1'}
create_kwargs = {}
self.assertRaises(webob.exc.HTTPBadRequest,
func,
server_dict,
create_kwargs)
def _test_with_invalid_ipv6(self, func):
server_dict = {access_ips.AccessIPs.v6_key: 'fe80:::::::'}
create_kwargs = {}
self.assertRaises(webob.exc.HTTPBadRequest,
func,
server_dict,
create_kwargs)
def _test_with_ipv4_null(self, func):
server_dict = {access_ips.AccessIPs.v4_key: None}
create_kwargs = {}
func(server_dict, create_kwargs)
self.assertEqual(create_kwargs, {'access_ip_v4': None})
def _test_with_ipv6_null(self, func):
server_dict = {access_ips.AccessIPs.v6_key: None}
create_kwargs = {}
func(server_dict, create_kwargs)
self.assertEqual(create_kwargs, {'access_ip_v6': None})
def _test_with_ipv4_blank(self, func):
server_dict = {access_ips.AccessIPs.v4_key: ''}
create_kwargs = {}
func(server_dict, create_kwargs)
self.assertEqual(create_kwargs, {'access_ip_v4': None})
def _test_with_ipv6_blank(self, func):
server_dict = {access_ips.AccessIPs.v6_key: ''}
create_kwargs = {}
func(server_dict, create_kwargs)
self.assertEqual(create_kwargs, {'access_ip_v6': None})
def test_server_create(self):
self._test(self.access_ips_ext.server_create)
def test_server_create_with_ipv4_only(self):
self._test_with_ipv4_only(self.access_ips_ext.server_create)
def test_server_create_with_ipv6_only(self):
self._test_with_ipv6_only(self.access_ips_ext.server_create)
def test_server_create_without_ipv4_and_ipv6(self):
self._test_without_ipv4_and_ipv6(self.access_ips_ext.server_create)
def test_server_create_with_invalid_ipv4(self):
self._test_with_invalid_ipv4(self.access_ips_ext.server_create)
def test_server_create_with_invalid_ipv6(self):
self._test_with_invalid_ipv6(self.access_ips_ext.server_create)
def test_server_create_with_ipv4_null(self):
self._test_with_ipv4_null(self.access_ips_ext.server_create)
def test_server_create_with_ipv6_null(self):
self._test_with_ipv6_null(self.access_ips_ext.server_create)
def test_server_create_with_ipv4_blank(self):
self._test_with_ipv4_blank(self.access_ips_ext.server_create)
def test_server_create_with_ipv6_blank(self):
self._test_with_ipv6_blank(self.access_ips_ext.server_create)
def test_server_update(self):
self._test(self.access_ips_ext.server_update)
def test_server_update_with_ipv4_only(self):
self._test_with_ipv4_only(self.access_ips_ext.server_update)
def test_server_update_with_ipv6_only(self):
self._test_with_ipv6_only(self.access_ips_ext.server_update)
def test_server_update_without_ipv4_and_ipv6(self):
self._test_without_ipv4_and_ipv6(self.access_ips_ext.server_update)
def test_server_update_with_invalid_ipv4(self):
self._test_with_invalid_ipv4(self.access_ips_ext.server_update)
def test_server_update_with_invalid_ipv6(self):
self._test_with_invalid_ipv6(self.access_ips_ext.server_update)
def test_server_update_with_ipv4_null(self):
self._test_with_ipv4_null(self.access_ips_ext.server_update)
def test_server_update_with_ipv6_null(self):
self._test_with_ipv6_null(self.access_ips_ext.server_update)
def test_server_update_with_ipv4_blank(self):
self._test_with_ipv4_blank(self.access_ips_ext.server_update)
def test_server_update_with_ipv6_blank(self):
self._test_with_ipv6_blank(self.access_ips_ext.server_update)
def test_server_rebuild(self):
self._test(self.access_ips_ext.server_rebuild)
def test_server_rebuild_with_ipv4_only(self):
self._test_with_ipv4_only(self.access_ips_ext.server_rebuild)
def test_server_rebuild_with_ipv6_only(self):
self._test_with_ipv6_only(self.access_ips_ext.server_rebuild)
def test_server_rebuild_without_ipv4_and_ipv6(self):
self._test_without_ipv4_and_ipv6(self.access_ips_ext.server_rebuild)
def test_server_rebuild_with_invalid_ipv4(self):
self._test_with_invalid_ipv4(self.access_ips_ext.server_rebuild)
def test_server_rebuild_with_invalid_ipv6(self):
self._test_with_invalid_ipv6(self.access_ips_ext.server_rebuild)
def test_server_rebuild_with_ipv4_null(self):
self._test_with_ipv4_null(self.access_ips_ext.server_rebuild)
def test_server_rebuild_with_ipv6_null(self):
self._test_with_ipv6_null(self.access_ips_ext.server_rebuild)
def test_server_rebuild_with_ipv4_blank(self):
self._test_with_ipv4_blank(self.access_ips_ext.server_rebuild)
def test_server_rebuild_with_ipv6_blank(self):
self._test_with_ipv6_blank(self.access_ips_ext.server_rebuild)
class AccessIPsControllerTest(test.NoDBTestCase):
def setUp(self):
super(AccessIPsControllerTest, self).setUp()
self.controller = access_ips.AccessIPsController()
def _test_with_access_ips(self, func, kwargs={'id': 'fake'}):
req = wsgi.Request({'nova.context':
fakes.FakeRequestContext('fake_user', 'fake',
is_admin=True)})
instance = {'uuid': 'fake',
'access_ip_v4': '1.1.1.1',
'access_ip_v6': 'fe80::'}
req.cache_db_instance(instance)
resp_obj = wsgi.ResponseObject(
{"server": {'id': 'fake'}})
func(req, resp_obj, **kwargs)
self.assertEqual(resp_obj.obj['server'][access_ips.AccessIPs.v4_key],
'1.1.1.1')
self.assertEqual(resp_obj.obj['server'][access_ips.AccessIPs.v6_key],
'fe80::')
def _test_without_access_ips(self, func, kwargs={'id': 'fake'}):
req = wsgi.Request({'nova.context':
fakes.FakeRequestContext('fake_user', 'fake',
is_admin=True)})
instance = {'uuid': 'fake',
'access_ip_v4': None,
'access_ip_v6': None}
req.cache_db_instance(instance)
resp_obj = wsgi.ResponseObject(
{"server": {'id': 'fake'}})
func(req, resp_obj, **kwargs)
self.assertEqual(resp_obj.obj['server'][access_ips.AccessIPs.v4_key],
'')
self.assertEqual(resp_obj.obj['server'][access_ips.AccessIPs.v6_key],
'')
def test_create(self):
self._test_with_access_ips(self.controller.create, {'body': {}})
def test_create_without_access_ips(self):
self._test_with_access_ips(self.controller.create, {'body': {}})
def test_create_with_reservation_id(self):
req = wsgi.Request({'nova.context':
fakes.FakeRequestContext('fake_user', 'fake',
is_admin=True)})
expected_res = {'servers_reservation': {'reservation_id': 'test'}}
body = copy.deepcopy(expected_res)
resp_obj = wsgi.ResponseObject(body)
self.controller.create(req, resp_obj, body)
self.assertEqual(expected_res, resp_obj.obj)
def test_show(self):
self._test_with_access_ips(self.controller.show)
def test_show_without_access_ips(self):
self._test_without_access_ips(self.controller.show)
def test_detail(self):
req = wsgi.Request({'nova.context':
fakes.FakeRequestContext('fake_user', 'fake',
is_admin=True)})
instance1 = {'uuid': 'fake1',
'access_ip_v4': '1.1.1.1',
'access_ip_v6': 'fe80::'}
instance2 = {'uuid': 'fake2',
'access_ip_v4': '1.1.1.2',
'access_ip_v6': 'fe81::'}
req.cache_db_instance(instance1)
req.cache_db_instance(instance2)
resp_obj = wsgi.ResponseObject(
{"servers": [{'id': 'fake1'}, {'id': 'fake2'}]})
self.controller.detail(req, resp_obj)
self.assertEqual(
resp_obj.obj['servers'][0][access_ips.AccessIPs.v4_key],
'1.1.1.1')
self.assertEqual(
resp_obj.obj['servers'][0][access_ips.AccessIPs.v6_key],
'fe80::')
self.assertEqual(
resp_obj.obj['servers'][1][access_ips.AccessIPs.v4_key],
'1.1.1.2')
self.assertEqual(
resp_obj.obj['servers'][1][access_ips.AccessIPs.v6_key],
'fe81::')
def test_detail_without_access_ips(self):
req = wsgi.Request({'nova.context':
fakes.FakeRequestContext('fake_user', 'fake',
is_admin=True)})
instance1 = {'uuid': 'fake1',
'access_ip_v4': None,
'access_ip_v6': None}
instance2 = {'uuid': 'fake2',
'access_ip_v4': None,
'access_ip_v6': None}
req.cache_db_instance(instance1)
req.cache_db_instance(instance2)
resp_obj = wsgi.ResponseObject(
{"servers": [{'id': 'fake1'}, {'id': 'fake2'}]})
self.controller.detail(req, resp_obj)
self.assertEqual(
resp_obj.obj['servers'][0][access_ips.AccessIPs.v4_key], '')
self.assertEqual(
resp_obj.obj['servers'][0][access_ips.AccessIPs.v6_key], '')
self.assertEqual(
resp_obj.obj['servers'][1][access_ips.AccessIPs.v4_key], '')
self.assertEqual(
resp_obj.obj['servers'][1][access_ips.AccessIPs.v6_key], '')
def test_update(self):
self._test_with_access_ips(self.controller.update, {'id': 'fake',
'body': {}})
def test_update_without_access_ips(self):
self._test_without_access_ips(self.controller.update, {'id': 'fake',
'body': {}})
def test_rebuild(self):
self._test_with_access_ips(self.controller.rebuild, {'id': 'fake',
'body': {}})
def test_rebuild_without_access_ips(self):
self._test_without_access_ips(self.controller.rebuild, {'id': 'fake',
'body': {}})
| apache-2.0 |
Nexenta/cinder | cinder/volume/drivers/hitachi/hbsd_basiclib.py | 29 | 9908 | # Copyright (C) 2014, Hitachi, Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import inspect
import os
import shlex
from oslo_concurrency import lockutils
from oslo_concurrency import processutils as putils
from oslo_log import log as logging
from oslo_utils import excutils
import six
from cinder import exception
from cinder.i18n import _, _LE
from cinder import utils
SMPL = 1
COPY = 2
PAIR = 3
PSUS = 4
PSUE = 5
UNKN = 0xff
FULL = 'Full copy'
THIN = 'Thin copy'
DEFAULT_TRY_RANGE = range(3)
MAX_PROCESS_WAITTIME = 86400
DEFAULT_PROCESS_WAITTIME = 900
GETSTORAGEARRAY_ONCE = 100
WARNING_ID = 300
DEFAULT_GROUP_RANGE = [0, 65535]
NAME_PREFIX = 'HBSD-'
NORMAL_VOLUME_TYPE = 'Normal'
LOCK_DIR = '/var/lock/hbsd/'
LOG = logging.getLogger(__name__)
HBSD_INFO_MSG = {
1: _('The parameter of the storage backend. '
'(config_group: %(config_group)s)'),
3: _('The storage backend can be used. (config_group: %(config_group)s)'),
4: _('The volume %(volume_id)s is managed successfully. (LDEV: %(ldev)s)'),
5: _('The volume %(volume_id)s is unmanaged successfully. '
'(LDEV: %(ldev)s)'),
}
HBSD_WARN_MSG = {
301: _('A LUN (HLUN) was not found. (LDEV: %(ldev)s)'),
302: _('Failed to specify a logical device for the volume '
'%(volume_id)s to be unmapped.'),
303: _('An iSCSI CHAP user could not be deleted. (username: %(user)s)'),
304: _('Failed to specify a logical device to be deleted. '
'(method: %(method)s, id: %(id)s)'),
305: _('The logical device for specified %(type)s %(id)s '
'was already deleted.'),
306: _('A host group could not be deleted. (port: %(port)s, '
'gid: %(gid)s, name: %(name)s)'),
307: _('An iSCSI target could not be deleted. (port: %(port)s, '
'tno: %(tno)s, alias: %(alias)s)'),
308: _('A host group could not be added. (port: %(port)s, '
'name: %(name)s)'),
309: _('An iSCSI target could not be added. '
'(port: %(port)s, alias: %(alias)s, reason: %(reason)s)'),
310: _('Failed to unmap a logical device. (LDEV: %(ldev)s, '
'reason: %(reason)s)'),
311: _('A free LUN (HLUN) was not found. Add a different host'
' group. (LDEV: %(ldev)s)'),
312: _('Failed to get a storage resource. The system will attempt '
'to get the storage resource again. (resource: %(resource)s)'),
313: _('Failed to delete a logical device. (LDEV: %(ldev)s, '
'reason: %(reason)s)'),
314: _('Failed to map a logical device. (LDEV: %(ldev)s, LUN: %(lun)s, '
'port: %(port)s, id: %(id)s)'),
315: _('Failed to perform a zero-page reclamation. '
'(LDEV: %(ldev)s, reason: %(reason)s)'),
316: _('Failed to assign the iSCSI initiator IQN. (port: %(port)s, '
'reason: %(reason)s)'),
}
HBSD_ERR_MSG = {
600: _('The command %(cmd)s failed. (ret: %(ret)s, stdout: %(out)s, '
'stderr: %(err)s)'),
601: _('A parameter is invalid. (%(param)s)'),
602: _('A parameter value is invalid. (%(meta)s)'),
603: _('Failed to acquire a resource lock. (serial: %(serial)s, '
'inst: %(inst)s, ret: %(ret)s, stderr: %(err)s)'),
604: _('Cannot set both hitachi_serial_number and hitachi_unit_name.'),
605: _('Either hitachi_serial_number or hitachi_unit_name is required.'),
615: _('A pair could not be created. The maximum number of pair is '
'exceeded. (copy method: %(copy_method)s, P-VOL: %(pvol)s)'),
616: _('A pair cannot be deleted. (P-VOL: %(pvol)s, S-VOL: %(svol)s)'),
617: _('The specified operation is not supported. The volume size '
'must be the same as the source %(type)s. (volume: %(volume_id)s)'),
618: _('The volume %(volume_id)s could not be extended. '
'The volume type must be Normal.'),
619: _('The volume %(volume_id)s to be mapped was not found.'),
624: _('The %(type)s %(id)s source to be replicated was not found.'),
631: _('Failed to create a file. (file: %(file)s, ret: %(ret)s, '
'stderr: %(err)s)'),
632: _('Failed to open a file. (file: %(file)s, ret: %(ret)s, '
'stderr: %(err)s)'),
633: _('%(file)s: Permission denied.'),
636: _('Failed to add the logical device.'),
637: _('The method %(method)s is timed out. (timeout value: %(timeout)s)'),
640: _('A pool could not be found. (pool id: %(pool_id)s)'),
641: _('The host group or iSCSI target could not be added.'),
642: _('An iSCSI CHAP user could not be added. (username: %(user)s)'),
643: _('The iSCSI CHAP user %(user)s does not exist.'),
648: _('There are no resources available for use. '
'(resource: %(resource)s)'),
649: _('The host group or iSCSI target was not found.'),
650: _('The resource %(resource)s was not found.'),
651: _('The IP Address was not found.'),
653: _('The creation of a logical device could not be '
'completed. (LDEV: %(ldev)s)'),
654: _('A volume status is invalid. (status: %(status)s)'),
655: _('A snapshot status is invalid. (status: %(status)s)'),
659: _('A host group is invalid. (host group: %(gid)s)'),
660: _('The specified %(desc)s is busy.'),
700: _('There is no designation of the %(param)s. '
'The specified storage is essential to manage the volume.'),
701: _('There is no designation of the ldev. '
'The specified ldev is essential to manage the volume.'),
702: _('The specified ldev %(ldev)s could not be managed. '
'The volume type must be DP-VOL.'),
703: _('The specified ldev %(ldev)s could not be managed. '
'The ldev size must be in multiples of gigabyte.'),
704: _('The specified ldev %(ldev)s could not be managed. '
'The ldev must not be mapping.'),
705: _('The specified ldev %(ldev)s could not be managed. '
'The ldev must not be paired.'),
706: _('The volume %(volume_id)s could not be unmanaged. '
'The volume type must be %(volume_type)s.'),
}
def set_msg(msg_id, **kwargs):
if msg_id < WARNING_ID:
msg_header = 'MSGID%04d-I:' % msg_id
msg_body = HBSD_INFO_MSG.get(msg_id)
else:
msg_header = 'MSGID%04d-W:' % msg_id
msg_body = HBSD_WARN_MSG.get(msg_id)
return '%(header)s %(body)s' % {'header': msg_header,
'body': msg_body % kwargs}
def output_err(msg_id, **kwargs):
msg = HBSD_ERR_MSG.get(msg_id) % kwargs
LOG.error(_LE("MSGID%(id)04d-E: %(msg)s"), {'id': msg_id, 'msg': msg})
return msg
def get_process_lock(file):
if not os.access(file, os.W_OK):
msg = output_err(633, file=file)
raise exception.HBSDError(message=msg)
return lockutils.InterProcessLock(file)
def create_empty_file(filename):
if not os.path.exists(filename):
try:
utils.execute('touch', filename)
except putils.ProcessExecutionError as ex:
msg = output_err(
631, file=filename, ret=ex.exit_code, err=ex.stderr)
raise exception.HBSDError(message=msg)
class FileLock(lockutils.InterProcessLock):
def __init__(self, name, lock_object):
self.lock_object = lock_object
super(FileLock, self).__init__(name)
def __enter__(self):
self.lock_object.acquire()
try:
ret = super(FileLock, self).__enter__()
except Exception:
with excutils.save_and_reraise_exception():
self.lock_object.release()
return ret
def __exit__(self, exc_type, exc_val, exc_tb):
try:
super(FileLock, self).__exit__(exc_type, exc_val, exc_tb)
finally:
self.lock_object.release()
class NopLock(object):
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
class HBSDBasicLib(object):
def __init__(self, conf=None):
self.conf = conf
def exec_command(self, cmd, args=None, printflag=True):
if printflag:
if args:
LOG.debug('cmd: %(cmd)s, args: %(args)s',
{'cmd': cmd, 'args': args})
else:
LOG.debug('cmd: %s', cmd)
cmd = [cmd]
if args:
if six.PY2 and isinstance(args, six.text_type):
cmd += shlex.split(args.encode())
else:
cmd += shlex.split(args)
try:
stdout, stderr = utils.execute(*cmd, run_as_root=True)
ret = 0
except putils.ProcessExecutionError as e:
ret = e.exit_code
stdout = e.stdout
stderr = e.stderr
LOG.debug('cmd: %s', cmd)
LOG.debug('from: %s', inspect.stack()[2])
LOG.debug('ret: %d', ret)
LOG.debug('stdout: %s', stdout.replace(os.linesep, ' '))
LOG.debug('stderr: %s', stderr.replace(os.linesep, ' '))
return ret, stdout, stderr
def set_pair_flock(self):
return NopLock()
def set_horcmgr_flock(self):
return NopLock()
def discard_zero_page(self, ldev):
pass
def output_param_to_log(self, conf):
pass
def connect_storage(self):
pass
def get_max_hostgroups(self):
pass
def restart_pair_horcm(self):
pass
| apache-2.0 |
mavit/ansible | test/units/modules/network/nxos/test_nxos_bgp_neighbor_af.py | 18 | 4920 | # (c) 2016 Red Hat Inc.
#
# 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 Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from ansible.modules.network.nxos import nxos_bgp_neighbor_af
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosBgpNeighborAfModule(TestNxosModule):
module = nxos_bgp_neighbor_af
def setUp(self):
super(TestNxosBgpNeighborAfModule, self).setUp()
self.mock_load_config = patch('ansible.modules.network.nxos.nxos_bgp_neighbor_af.load_config')
self.load_config = self.mock_load_config.start()
self.mock_get_config = patch('ansible.modules.network.nxos.nxos_bgp_neighbor_af.get_config')
self.get_config = self.mock_get_config.start()
def tearDown(self):
super(TestNxosBgpNeighborAfModule, self).tearDown()
self.mock_load_config.stop()
self.mock_get_config.stop()
def load_fixtures(self, commands=None, device=''):
self.get_config.return_value = load_fixture('nxos_bgp', 'config.cfg')
self.load_config.return_value = []
def test_nxos_bgp_neighbor_af(self):
set_module_args(dict(asn=65535, neighbor='192.0.2.3', afi='ipv4',
safi='unicast', route_reflector_client=True))
result = self.execute_module(changed=True)
self.assertEqual(result['commands'], [
'router bgp 65535', 'neighbor 192.0.2.3', 'address-family ipv4 unicast',
'route-reflector-client'
])
def test_nxos_bgp_neighbor_af_exists(self):
set_module_args(dict(asn=65535, neighbor='3.3.3.5', afi='ipv4', safi='unicast'))
self.execute_module(changed=False, commands=[])
def test_nxos_bgp_neighbor_af_absent(self):
set_module_args(dict(asn=65535, neighbor='3.3.3.5', afi='ipv4', safi='unicast', state='absent'))
self.execute_module(
changed=True, sort=False,
commands=['router bgp 65535', 'neighbor 3.3.3.5', 'no address-family ipv4 unicast']
)
def test_nxos_bgp_neighbor_af_advertise_map(self):
set_module_args(dict(asn=65535, neighbor='3.3.3.5', afi='ipv4', safi='unicast',
advertise_map_exist=['my_advertise_map', 'my_exist_map']))
self.execute_module(
changed=True, sort=False,
commands=['router bgp 65535', 'neighbor 3.3.3.5', 'address-family ipv4 unicast', 'advertise-map my_advertise_map exist-map my_exist_map']
)
def test_nxos_bgp_neighbor_af_advertise_map_non_exist(self):
set_module_args(dict(asn=65535, neighbor='3.3.3.5', afi='ipv4', safi='unicast',
advertise_map_non_exist=['my_advertise_map', 'my_non_exist_map']))
self.execute_module(
changed=True, sort=False,
commands=['router bgp 65535', 'neighbor 3.3.3.5', 'address-family ipv4 unicast', 'advertise-map my_advertise_map non-exist-map my_non_exist_map']
)
def test_nxos_bgp_neighbor_af_max_prefix_limit_default(self):
set_module_args(dict(asn=65535, neighbor='3.3.3.5', afi='ipv4',
safi='unicast', max_prefix_limit='default'))
self.execute_module(
changed=True, sort=False,
commands=['router bgp 65535', 'neighbor 3.3.3.5', 'address-family ipv4 unicast', 'no maximum-prefix']
)
def test_nxos_bgp_neighbor_af_max_prefix(self):
set_module_args(dict(asn=65535, neighbor='3.3.3.5', afi='ipv4',
safi='unicast', max_prefix_threshold=20,
max_prefix_limit=20))
self.execute_module(
changed=True, sort=False,
commands=['router bgp 65535', 'neighbor 3.3.3.5', 'address-family ipv4 unicast', 'maximum-prefix 20 20']
)
def test_nxos_bgp_neighbor_af_disable_peer_as_check(self):
set_module_args(dict(asn=65535, neighbor='3.3.3.5', afi='ipv4',
safi='unicast', disable_peer_as_check=True))
self.execute_module(
changed=True,
commands=['router bgp 65535', 'neighbor 3.3.3.5', 'address-family ipv4 unicast', 'disable-peer-as-check']
)
| gpl-3.0 |
clubcapra/Ibex | src/capra_teleop/scripts/teleop_mind.py | 1 | 1305 | #!/usr/bin/env python
PACKAGE_NAME = 'capra_teleop'
import roslib
roslib.load_manifest(PACKAGE_NAME)
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Joy
import rospkg
import socket
LINEAR_VEL = 0.1
ANGULAR_VEL = 0.1
def cmd_vel_timer(evt):
global key, cmd_vel, LINEAR_VEL, ANGULAR_VEL
msg = Twist()
if key:
key = key.lower()
if key == 'w':
print "avance"
msg.linear.x = LINEAR_VEL
elif key == "s":
print "recule"
msg.linear.x = -LINEAR_VEL
elif key == "a":
print "left"
msg.angular.z = ANGULAR_VEL
elif key == "d":
print "right"
msg.angular.z = -ANGULAR_VEL
cmd_vel.publish(msg)
def watchdog_timer(evt):
global key, last_update
if rospy.get_time() - last_update > 0.5:
key = ""
rospy.init_node(PACKAGE_NAME)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 1337))
cmd_vel = rospy.Publisher("/cmd_vel", Twist, queue_size=1)
rospy.Timer(rospy.Duration.from_sec(15.0/1000), cmd_vel_timer)
rospy.Timer(rospy.Duration.from_sec(0.1), watchdog_timer)
key = ""
last_update = 0
while not rospy.is_shutdown():
key = s.recvfrom(1)[0]
last_update = rospy.get_time()
| gpl-3.0 |
boretom/pyload-apkg | source/py-mods-prebuilt-x86-64/site-packages/thrift/TSerialization.py | 184 | 1387 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
from protocol import TBinaryProtocol
from transport import TTransport
def serialize(thrift_object,
protocol_factory=TBinaryProtocol.TBinaryProtocolFactory()):
transport = TTransport.TMemoryBuffer()
protocol = protocol_factory.getProtocol(transport)
thrift_object.write(protocol)
return transport.getvalue()
def deserialize(base,
buf,
protocol_factory=TBinaryProtocol.TBinaryProtocolFactory()):
transport = TTransport.TMemoryBuffer(buf)
protocol = protocol_factory.getProtocol(transport)
base.read(protocol)
return base
| gpl-3.0 |
chromium/chromium | build/env_dump.py | 16 | 1721 | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This script can either source a file and dump the enironment changes done by
# it, or just simply dump the current environment as JSON into a file.
import json
import optparse
import os
import pipes
import subprocess
import sys
def main():
parser = optparse.OptionParser()
parser.add_option('-f', '--output-json',
help='File to dump the environment as JSON into.')
parser.add_option(
'-d', '--dump-mode', action='store_true',
help='Dump the environment to sys.stdout and exit immediately.')
parser.disable_interspersed_args()
options, args = parser.parse_args()
if options.dump_mode:
if args or options.output_json:
parser.error('Cannot specify args or --output-json with --dump-mode.')
json.dump(dict(os.environ), sys.stdout)
else:
if not options.output_json:
parser.error('Requires --output-json option.')
envsetup_cmd = ' '.join(map(pipes.quote, args))
full_cmd = [
'bash', '-c',
'. %s > /dev/null; %s -d' % (envsetup_cmd, os.path.abspath(__file__))
]
try:
output = subprocess.check_output(full_cmd)
except Exception as e:
sys.exit('Error running %s and dumping environment.' % envsetup_cmd)
env_diff = {}
new_env = json.loads(output)
for k, val in new_env.items():
if k == '_' or (k in os.environ and os.environ[k] == val):
continue
env_diff[k] = val
with open(options.output_json, 'w') as f:
json.dump(env_diff, f)
if __name__ == '__main__':
sys.exit(main())
| bsd-3-clause |
kimimj/scrapy | tests/test_utils_trackref.py | 119 | 1784 | import six
import unittest
from scrapy.utils import trackref
from tests import mock
class Foo(trackref.object_ref):
pass
class Bar(trackref.object_ref):
pass
class TrackrefTestCase(unittest.TestCase):
def setUp(self):
trackref.live_refs.clear()
def test_format_live_refs(self):
o1 = Foo() # NOQA
o2 = Bar() # NOQA
o3 = Foo() # NOQA
self.assertEqual(
trackref.format_live_refs(),
'''\
Live References
Bar 1 oldest: 0s ago
Foo 2 oldest: 0s ago
''')
self.assertEqual(
trackref.format_live_refs(ignore=Foo),
'''\
Live References
Bar 1 oldest: 0s ago
''')
@mock.patch('sys.stdout', new_callable=six.StringIO)
def test_print_live_refs_empty(self, stdout):
trackref.print_live_refs()
self.assertEqual(stdout.getvalue(), 'Live References\n\n\n')
@mock.patch('sys.stdout', new_callable=six.StringIO)
def test_print_live_refs_with_objects(self, stdout):
o1 = Foo() # NOQA
trackref.print_live_refs()
self.assertEqual(stdout.getvalue(), '''\
Live References
Foo 1 oldest: 0s ago\n\n''')
def test_get_oldest(self):
o1 = Foo() # NOQA
o2 = Bar() # NOQA
o3 = Foo() # NOQA
self.assertIs(trackref.get_oldest('Foo'), o1)
self.assertIs(trackref.get_oldest('Bar'), o2)
self.assertIsNone(trackref.get_oldest('XXX'))
def test_iter_all(self):
o1 = Foo() # NOQA
o2 = Bar() # NOQA
o3 = Foo() # NOQA
self.assertEqual(
set(trackref.iter_all('Foo')),
{o1, o3},
)
| bsd-3-clause |
Emilgardis/falloutsnip | Vendor/IronPython/Lib/contextlib.py | 261 | 4424 | """Utilities for with-statement contexts. See PEP 343."""
import sys
from functools import wraps
from warnings import warn
__all__ = ["contextmanager", "nested", "closing"]
class GeneratorContextManager(object):
"""Helper for @contextmanager decorator."""
def __init__(self, gen):
self.gen = gen
def __enter__(self):
try:
return self.gen.next()
except StopIteration:
raise RuntimeError("generator didn't yield")
def __exit__(self, type, value, traceback):
if type is None:
try:
self.gen.next()
except StopIteration:
return
else:
raise RuntimeError("generator didn't stop")
else:
if value is None:
# Need to force instantiation so we can reliably
# tell if we get the same exception back
value = type()
try:
self.gen.throw(type, value, traceback)
raise RuntimeError("generator didn't stop after throw()")
except StopIteration, exc:
# Suppress the exception *unless* it's the same exception that
# was passed to throw(). This prevents a StopIteration
# raised inside the "with" statement from being suppressed
return exc is not value
except:
# only re-raise if it's *not* the exception that was
# passed to throw(), because __exit__() must not raise
# an exception unless __exit__() itself failed. But throw()
# has to raise the exception to signal propagation, so this
# fixes the impedance mismatch between the throw() protocol
# and the __exit__() protocol.
#
if sys.exc_info()[1] is not value:
raise
def contextmanager(func):
"""@contextmanager decorator.
Typical usage:
@contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
This makes this:
with some_generator(<arguments>) as <variable>:
<body>
equivalent to this:
<setup>
try:
<variable> = <value>
<body>
finally:
<cleanup>
"""
@wraps(func)
def helper(*args, **kwds):
return GeneratorContextManager(func(*args, **kwds))
return helper
@contextmanager
def nested(*managers):
"""Combine multiple context managers into a single nested context manager.
This function has been deprecated in favour of the multiple manager form
of the with statement.
The one advantage of this function over the multiple manager form of the
with statement is that argument unpacking allows it to be
used with a variable number of context managers as follows:
with nested(*managers):
do_something()
"""
warn("With-statements now directly support multiple context managers",
DeprecationWarning, 3)
exits = []
vars = []
exc = (None, None, None)
try:
for mgr in managers:
exit = mgr.__exit__
enter = mgr.__enter__
vars.append(enter())
exits.append(exit)
yield vars
except:
exc = sys.exc_info()
finally:
while exits:
exit = exits.pop()
try:
if exit(*exc):
exc = (None, None, None)
except:
exc = sys.exc_info()
if exc != (None, None, None):
# Don't rely on sys.exc_info() still containing
# the right information. Another exception may
# have been raised and caught by an exit method
raise exc[0], exc[1], exc[2]
class closing(object):
"""Context to automatically close something at the end of a block.
Code like this:
with closing(<module>.open(<arguments>)) as f:
<block>
is equivalent to this:
f = <module>.open(<arguments>)
try:
<block>
finally:
f.close()
"""
def __init__(self, thing):
self.thing = thing
def __enter__(self):
return self.thing
def __exit__(self, *exc_info):
self.thing.close()
| gpl-3.0 |
aurelijusb/arangodb | 3rdParty/V8-4.3.61/third_party/python_26/Lib/lib2to3/fixes/fix_urllib.py | 49 | 7484 | """Fix changes imports of urllib which are now incompatible.
This is rather similar to fix_imports, but because of the more
complex nature of the fixing for urllib, it has its own fixer.
"""
# Author: Nick Edds
# Local imports
from .fix_imports import alternates, FixImports
from .. import fixer_base
from ..fixer_util import Name, Comma, FromImport, Newline, attr_chain
MAPPING = {'urllib': [
('urllib.request',
['URLOpener', 'FancyURLOpener', 'urlretrieve',
'_urlopener', 'urlcleanup']),
('urllib.parse',
['quote', 'quote_plus', 'unquote', 'unquote_plus',
'urlencode', 'pathname2url', 'url2pathname', 'splitattr',
'splithost', 'splitnport', 'splitpasswd', 'splitport',
'splitquery', 'splittag', 'splittype', 'splituser',
'splitvalue', ]),
('urllib.error',
['ContentTooShortError'])],
'urllib2' : [
('urllib.request',
['urlopen', 'install_opener', 'build_opener',
'Request', 'OpenerDirector', 'BaseHandler',
'HTTPDefaultErrorHandler', 'HTTPRedirectHandler',
'HTTPCookieProcessor', 'ProxyHandler',
'HTTPPasswordMgr',
'HTTPPasswordMgrWithDefaultRealm',
'AbstractBasicAuthHandler',
'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler',
'AbstractDigestAuthHandler',
'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler',
'HTTPHandler', 'HTTPSHandler', 'FileHandler',
'FTPHandler', 'CacheFTPHandler',
'UnknownHandler']),
('urllib.error',
['URLError', 'HTTPError']),
]
}
# Duplicate the url parsing functions for urllib2.
MAPPING["urllib2"].append(MAPPING["urllib"][1])
def build_pattern():
bare = set()
for old_module, changes in MAPPING.items():
for change in changes:
new_module, members = change
members = alternates(members)
yield """import_name< 'import' (module=%r
| dotted_as_names< any* module=%r any* >) >
""" % (old_module, old_module)
yield """import_from< 'from' mod_member=%r 'import'
( member=%s | import_as_name< member=%s 'as' any > |
import_as_names< members=any* >) >
""" % (old_module, members, members)
yield """import_from< 'from' module_star=%r 'import' star='*' >
""" % old_module
yield """import_name< 'import'
dotted_as_name< module_as=%r 'as' any > >
""" % old_module
yield """power< module_dot=%r trailer< '.' member=%s > any* >
""" % (old_module, members)
class FixUrllib(FixImports):
def build_pattern(self):
return "|".join(build_pattern())
def transform_import(self, node, results):
"""Transform for the basic import case. Replaces the old
import name with a comma separated list of its
replacements.
"""
import_mod = results.get('module')
pref = import_mod.get_prefix()
names = []
# create a Node list of the replacement modules
for name in MAPPING[import_mod.value][:-1]:
names.extend([Name(name[0], prefix=pref), Comma()])
names.append(Name(MAPPING[import_mod.value][-1][0], prefix=pref))
import_mod.replace(names)
def transform_member(self, node, results):
"""Transform for imports of specific module elements. Replaces
the module to be imported from with the appropriate new
module.
"""
mod_member = results.get('mod_member')
pref = mod_member.get_prefix()
member = results.get('member')
# Simple case with only a single member being imported
if member:
# this may be a list of length one, or just a node
if isinstance(member, list):
member = member[0]
new_name = None
for change in MAPPING[mod_member.value]:
if member.value in change[1]:
new_name = change[0]
break
if new_name:
mod_member.replace(Name(new_name, prefix=pref))
else:
self.cannot_convert(node,
'This is an invalid module element')
# Multiple members being imported
else:
# a dictionary for replacements, order matters
modules = []
mod_dict = {}
members = results.get('members')
for member in members:
member = member.value
# we only care about the actual members
if member != ',':
for change in MAPPING[mod_member.value]:
if member in change[1]:
if change[0] in mod_dict:
mod_dict[change[0]].append(member)
else:
mod_dict[change[0]] = [member]
modules.append(change[0])
new_nodes = []
for module in modules:
elts = mod_dict[module]
names = []
for elt in elts[:-1]:
names.extend([Name(elt, prefix=pref), Comma()])
names.append(Name(elts[-1], prefix=pref))
new_nodes.append(FromImport(module, names))
if new_nodes:
nodes = []
for new_node in new_nodes[:-1]:
nodes.extend([new_node, Newline()])
nodes.append(new_nodes[-1])
node.replace(nodes)
else:
self.cannot_convert(node, 'All module elements are invalid')
def transform_dot(self, node, results):
"""Transform for calls to module members in code."""
module_dot = results.get('module_dot')
member = results.get('member')
# this may be a list of length one, or just a node
if isinstance(member, list):
member = member[0]
new_name = None
for change in MAPPING[module_dot.value]:
if member.value in change[1]:
new_name = change[0]
break
if new_name:
module_dot.replace(Name(new_name,
prefix=module_dot.get_prefix()))
else:
self.cannot_convert(node, 'This is an invalid module element')
def transform(self, node, results):
if results.get('module'):
self.transform_import(node, results)
elif results.get('mod_member'):
self.transform_member(node, results)
elif results.get('module_dot'):
self.transform_dot(node, results)
# Renaming and star imports are not supported for these modules.
elif results.get('module_star'):
self.cannot_convert(node, 'Cannot handle star imports.')
elif results.get('module_as'):
self.cannot_convert(node, 'This module is now multiple modules')
| apache-2.0 |
valsdav/plastex | plasTeX/Base/LaTeX/Entities.py | 6 | 2610 | #!/usr/bin/env python
"""
This package is dynamically generated. It loads data from the ent.xml file.
"""
import re, new, os, Accents, Characters
from xml.parsers import expat
from plasTeX import Command
g = globals()
class EntityParser(object):
""" Parser for XML entities """
accentmap = {
'\'': Accents.Acute,
'^': Accents.Circumflex,
'`': Accents.Grave,
'~': Accents.Tilde,
'"': Accents.Umlaut,
'c': Accents.c,
'v': Accents.v,
'u': Accents.u,
'k': Accents.k,
'.': Accents.Dot,
'=': Accents.Macron,
'H': Accents.H,
'r': Accents.r,
}
def __init__(self):
self.parser = expat.ParserCreate()
self.parser.StartElementHandler = self.start_element
self.parser.CharacterDataHandler = self.char_data
self.unicode = None
self.inseq = False
self.defined = {}
def parse(self, file):
self.parser.Parse(open(file).read())
self.defined.clear()
def start_element(self, name, attrs):
if name == 'char':
self.unicode = None
elif name == 'unicode':
self.unicode = int('0x%s' % attrs['value'], 16)
elif name in ['seq','mathseq']:
self.inseq = True
else:
self.inseq = False
def char_data(self, data):
if self.unicode is None:
self.inseq = False
return
if self.inseq == False:
return
# Just a macro
m = re.match(r'^\\(\w+|\W)$', data)
if m:
name = str(m.group(1)).replace('\\','\\\\')
if name not in self.defined:
g[name+'_'] = new.classobj(name+'_', (Command,),
{'unicode':unichr(self.unicode),
'macroName':name})
self.defined[name] = True
# Wingdings
m = re.match(r'^\\ding\{(\d+)\}$', data)
if m:
int(m.group(1))
Characters.ding.values[int(m.group(1))] = unichr(self.unicode)
# Accented characters
m = re.match(r'^(\\(%s)\{([^\}])\})' %
'|'.join(self.accentmap.keys()), data)
if m and m.group(1) not in self.defined:
accent = self.accentmap[m.group(2)]
accent.chars[m.group(3)] = unichr(self.unicode)
self.defined[m.group(1)] = True
self.inseq = False
# Parse the entities file
#e = EntityParser()
#e.parse(os.path.join(os.path.dirname(__file__),'ent.xml'))
| mit |
cloudstax/firecamp | vendor/lambda-python-requests/urllib3/util/url.py | 203 | 6487 | from __future__ import absolute_import
from collections import namedtuple
from ..exceptions import LocationParseError
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
# We only want to normalize urls with an HTTP(S) scheme.
# urllib3 infers URLs without a scheme (None) to be http.
NORMALIZABLE_SCHEMES = ('http', 'https', None)
class Url(namedtuple('Url', url_attrs)):
"""
Datastructure for representing an HTTP URL. Used as a return value for
:func:`parse_url`. Both the scheme and host are normalized as they are
both case-insensitive according to RFC 3986.
"""
__slots__ = ()
def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None,
query=None, fragment=None):
if path and not path.startswith('/'):
path = '/' + path
if scheme:
scheme = scheme.lower()
if host and scheme in NORMALIZABLE_SCHEMES:
host = host.lower()
return super(Url, cls).__new__(cls, scheme, auth, host, port, path,
query, fragment)
@property
def hostname(self):
"""For backwards-compatibility with urlparse. We're nice like that."""
return self.host
@property
def request_uri(self):
"""Absolute path including the query string."""
uri = self.path or '/'
if self.query is not None:
uri += '?' + self.query
return uri
@property
def netloc(self):
"""Network location including host and port"""
if self.port:
return '%s:%d' % (self.host, self.port)
return self.host
@property
def url(self):
"""
Convert self into a url
This function should more or less round-trip with :func:`.parse_url`. The
returned url may not be exactly the same as the url inputted to
:func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls
with a blank port will have : removed).
Example: ::
>>> U = parse_url('http://google.com/mail/')
>>> U.url
'http://google.com/mail/'
>>> Url('http', 'username:password', 'host.com', 80,
... '/path', 'query', 'fragment').url
'http://username:password@host.com:80/path?query#fragment'
"""
scheme, auth, host, port, path, query, fragment = self
url = ''
# We use "is not None" we want things to happen with empty strings (or 0 port)
if scheme is not None:
url += scheme + '://'
if auth is not None:
url += auth + '@'
if host is not None:
url += host
if port is not None:
url += ':' + str(port)
if path is not None:
url += path
if query is not None:
url += '?' + query
if fragment is not None:
url += '#' + fragment
return url
def __str__(self):
return self.url
def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'bar?baz', '/')
>>> split_first('foo/bar?baz', '123')
('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims.
"""
min_idx = None
min_delim = None
for d in delims:
idx = s.find(d)
if idx < 0:
continue
if min_idx is None or idx < min_idx:
min_idx = idx
min_delim = d
if min_idx is None or min_idx < 0:
return s, '', None
return s[:min_idx], s[min_idx + 1:], min_delim
def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
Partly backwards-compatible with :mod:`urlparse`.
Example::
>>> parse_url('http://google.com/mail/')
Url(scheme='http', host='google.com', port=None, path='/mail/', ...)
>>> parse_url('google.com:80')
Url(scheme=None, host='google.com', port=80, path=None, ...)
>>> parse_url('/foo?bar')
Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
"""
# While this code has overlap with stdlib's urlparse, it is much
# simplified for our needs and less annoying.
# Additionally, this implementations does silly things to be optimal
# on CPython.
if not url:
# Empty
return Url()
scheme = None
auth = None
host = None
port = None
path = None
fragment = None
query = None
# Scheme
if '://' in url:
scheme, url = url.split('://', 1)
# Find the earliest Authority Terminator
# (http://tools.ietf.org/html/rfc3986#section-3.2)
url, path_, delim = split_first(url, ['/', '?', '#'])
if delim:
# Reassemble the path
path = delim + path_
# Auth
if '@' in url:
# Last '@' denotes end of auth part
auth, url = url.rsplit('@', 1)
# IPv6
if url and url[0] == '[':
host, url = url.split(']', 1)
host += ']'
# Port
if ':' in url:
_host, port = url.split(':', 1)
if not host:
host = _host
if port:
# If given, ports must be integers. No whitespace, no plus or
# minus prefixes, no non-integer digits such as ^2 (superscript).
if not port.isdigit():
raise LocationParseError(url)
try:
port = int(port)
except ValueError:
raise LocationParseError(url)
else:
# Blank ports are cool, too. (rfc3986#section-3.2.3)
port = None
elif not host and url:
host = url
if not path:
return Url(scheme, auth, host, port, path, query, fragment)
# Fragment
if '#' in path:
path, fragment = path.split('#', 1)
# Query
if '?' in path:
path, query = path.split('?', 1)
return Url(scheme, auth, host, port, path, query, fragment)
def get_host(url):
"""
Deprecated. Use :func:`parse_url` instead.
"""
p = parse_url(url)
return p.scheme or 'http', p.hostname, p.port
| apache-2.0 |
msis/pyIbex | src/pyIbex/pySIVIA.py | 1 | 5177 | # pySIVIA.py
import pyIbex
from pyIbex import *
from vibes import *
from collections import deque
def pySIVIA(X0, ops, epsilon, **kwargs):
'''
Execute a SIVIA and generate a paving.
Parameters
----------
X0: IntervalVector
Initial box
ops: ctc or sep
Operator must be a contractor or a separatot
epsilon: double
Accuracy of the sub-Paving.
Use to end the algorithm.
color_out : string, optional
color used to draw boxes which are outide the solution set
string need to be in vibes format ex: 'k[r]' of #RRGGBBAA[#RRGGBBAA]
Only used when vibes is installed.
default value : k[r]
color_in : string, optional
color used to draw boxes which are inside the solution set
string need to be in vibes format ex: 'k[r]' of #RRGGBBAA[#RRGGBBAA]
Only used when vibes is installed.
default value : k[r]
color_maybe : string, optional
color used to draw boxes which are smaller than eps and underterminaed
string need to be in vibes format ex: 'k[r]' of #RRGGBBAA[#RRGGBBAA]
Only used when vibes is installed.
default value : k[r]
figure_name: string or None, optional
Name of the figure on which boxes are drawn
if None use the current figure
default value : None
draw_boxes: boolean, optional
if True, boxes removed by contractor are displayed
if vibes is not installed, draw_boxes is always equal to false
default value False
display_stats: boolean, optional
if True, display the number of call of the contractor, time needed by the sivia
and the total number of boxes generated.
default value: False
save_result: boolean, optinnal
default value : True
Save removed boxes with a list
use_patch : boolean, optional
if true draw the difference of boxes with a patch
natural : compute the difference of two boxes and draw each complementary part separatly
patch : compute the polygon which represents the difference of the two boxes
default patch
Return
------
return lists of boxes, one with outter boxes, inner boxes and mayBe boxes
Lists are empty if save_boxes is False
'''
if issubclass(ops.__class__, pyIbex.Ctc):
return __pySIVIA_ctc(X0, ops, epsilon, **kwargs)
elif issubclass(ops.__class__, pyIbex.Sep):
return __pySIVIA_sep(X0, ops, epsilon, **kwargs)
def drawBoxDiff(X0, X, color, use_patch=False, **kwargs):
if X0 == X: return
if not X.is_empty():
if use_patch == True:
vibes.drawBoxDiff([X0[0].lb(), X0[0].ub(), X0[1].lb(), X0[1].ub()],
[X[0].lb(), X[0].ub(), X[1].lb(), X[1].ub()], color)
else:
for b in X0.diff(X):
vibes.drawBox(b[0].lb(), b[0].ub(), b[1].lb(), b[1].ub(), color)
else:
vibes.drawBox(X0[0].lb(), X0[0].ub(), X0[1].lb(), X0[1].ub(), color)
def __pySIVIA_ctc(X0, ctc, epsilon, color_out='k[b]', color_maybe='k[y]', draw_boxes=True, save_result=True, **kwargs):
stack = deque([IntervalVector(X0)])
res_y = []; res_out = []
lf = LargestFirst(epsilon/2.0)
k = 0
while len(stack) > 0:
k = k+1
X = stack.popleft()
X0 = IntervalVector(X)
#X = __contract_and_extract(X, ctc, res_out, color_out)
ctc.contract(X)
if (draw_boxes == True):
drawBoxDiff(X0,X,color_out, **kwargs)
if save_result == True:
res_out += X0.diff(X)
if (X.is_empty()): continue
if( X.max_diam() < epsilon):
if draw_boxes == True:
vibes.drawBox(X[0].lb(), X[0].ub(),X[1].lb(), X[1].ub(), color_maybe)
if save_result == True:
res_y.append(X)
elif (X.is_empty() == False):
(X1, X2) = lf.bisect(X)
stack.append(X1)
stack.append(X2)
print('nb contraction %d / nombre de boite %d'%(k,len(res_out)+len(res_y)))
return (res_out, res_y)
def __pySIVIA_sep(X0, sep, epsilon, color_in='k[r]', color_out='k[b]', color_maybe='k[y]', draw_boxes=True, save_result=True, **kwargs):
stack = deque([IntervalVector(X0)])
res_y = []; res_in = []; res_out = []
lf = LargestFirst(epsilon/2.0)
k = 0
while len(stack) > 0:
X = stack.popleft()
k = k+1
x_in, x_out = map(IntervalVector, (X, )*2)
sep.separate(x_in, x_out)
if draw_boxes==True:
drawBoxDiff(X, x_in, color_in, **kwargs)
drawBoxDiff(X, x_out, color_out, **kwargs)
if save_result==True:
res_in += X.diff(x_in)
res_out += X.diff(x_out)
X = x_in & x_out
if (X.is_empty()): continue
if( X.max_diam() < epsilon):
if draw_boxes == True:
vibes.drawBox(X[0].lb(), X[0].ub(),X[1].lb(), X[1].ub(), color_maybe)
res_y.append(X)
elif (X.is_empty() == False):
(X1, X2) = lf.bisect(X)
stack.append(X1)
stack.append(X2)
print('nb contraction %d / nombre de boite %d'%(k,len(res_in)+len(res_out)+len(res_y)))
return (res_in , res_out, res_y)
if __name__ == '__main__':
from pyIbex import *
f = Function('x', 'y', 'x^2 + y^2')
ctc = CtcFwdBwd(f, sqr(Interval(3,4)))
sep = SepFwdBwd(f, sqr(Interval(3,4)))
params = {'color_in': 'r[g]', 'color_out':'b[#AACC00]', 'color_maybe':'k[y]', 'use_patch': False}
box = IntervalVector(2, [-5, 5])
vibes.beginDrawing()
pySIVIA(box, ctc, 0.1, draw_boxes=True, save_result=False, **params)
vibes.newFigure('test2')
pySIVIA(box, sep, 0.1, draw_boxes=True, save_result=False, **params)
vibes.endDrawing()
| lgpl-3.0 |
ccnmtl/lettuce | tests/integration/lib/Django-1.2.5/django/template/smartif.py | 331 | 6261 | """
Parser and utilities for the smart 'if' tag
"""
import operator
# Using a simple top down parser, as described here:
# http://effbot.org/zone/simple-top-down-parsing.htm.
# 'led' = left denotation
# 'nud' = null denotation
# 'bp' = binding power (left = lbp, right = rbp)
class TokenBase(object):
"""
Base class for operators and literals, mainly for debugging and for throwing
syntax errors.
"""
id = None # node/token type name
value = None # used by literals
first = second = None # used by tree nodes
def nud(self, parser):
# Null denotation - called in prefix context
raise parser.error_class(
"Not expecting '%s' in this position in if tag." % self.id
)
def led(self, left, parser):
# Left denotation - called in infix context
raise parser.error_class(
"Not expecting '%s' as infix operator in if tag." % self.id
)
def display(self):
"""
Returns what to display in error messages for this node
"""
return self.id
def __repr__(self):
out = [str(x) for x in [self.id, self.first, self.second] if x is not None]
return "(" + " ".join(out) + ")"
def infix(bp, func):
"""
Creates an infix operator, given a binding power and a function that
evaluates the node
"""
class Operator(TokenBase):
lbp = bp
def led(self, left, parser):
self.first = left
self.second = parser.expression(bp)
return self
def eval(self, context):
try:
return func(context, self.first, self.second)
except Exception:
# Templates shouldn't throw exceptions when rendering. We are
# most likely to get exceptions for things like {% if foo in bar
# %} where 'bar' does not support 'in', so default to False
return False
return Operator
def prefix(bp, func):
"""
Creates a prefix operator, given a binding power and a function that
evaluates the node.
"""
class Operator(TokenBase):
lbp = bp
def nud(self, parser):
self.first = parser.expression(bp)
self.second = None
return self
def eval(self, context):
try:
return func(context, self.first)
except Exception:
return False
return Operator
# Operator precedence follows Python.
# NB - we can get slightly more accurate syntax error messages by not using the
# same object for '==' and '='.
# We defer variable evaluation to the lambda to ensure that terms are
# lazily evaluated using Python's boolean parsing logic.
OPERATORS = {
'or': infix(6, lambda context, x, y: x.eval(context) or y.eval(context)),
'and': infix(7, lambda context, x, y: x.eval(context) and y.eval(context)),
'not': prefix(8, lambda context, x: not x.eval(context)),
'in': infix(9, lambda context, x, y: x.eval(context) in y.eval(context)),
'not in': infix(9, lambda context, x, y: x.eval(context) not in y.eval(context)),
'=': infix(10, lambda context, x, y: x.eval(context) == y.eval(context)),
'==': infix(10, lambda context, x, y: x.eval(context) == y.eval(context)),
'!=': infix(10, lambda context, x, y: x.eval(context) != y.eval(context)),
'>': infix(10, lambda context, x, y: x.eval(context) > y.eval(context)),
'>=': infix(10, lambda context, x, y: x.eval(context) >= y.eval(context)),
'<': infix(10, lambda context, x, y: x.eval(context) < y.eval(context)),
'<=': infix(10, lambda context, x, y: x.eval(context) <= y.eval(context)),
}
# Assign 'id' to each:
for key, op in OPERATORS.items():
op.id = key
class Literal(TokenBase):
"""
A basic self-resolvable object similar to a Django template variable.
"""
# IfParser uses Literal in create_var, but TemplateIfParser overrides
# create_var so that a proper implementation that actually resolves
# variables, filters etc is used.
id = "literal"
lbp = 0
def __init__(self, value):
self.value = value
def display(self):
return repr(self.value)
def nud(self, parser):
return self
def eval(self, context):
return self.value
def __repr__(self):
return "(%s %r)" % (self.id, self.value)
class EndToken(TokenBase):
lbp = 0
def nud(self, parser):
raise parser.error_class("Unexpected end of expression in if tag.")
EndToken = EndToken()
class IfParser(object):
error_class = ValueError
def __init__(self, tokens):
# pre-pass necessary to turn 'not','in' into single token
l = len(tokens)
mapped_tokens = []
i = 0
while i < l:
token = tokens[i]
if token == "not" and i + 1 < l and tokens[i+1] == "in":
token = "not in"
i += 1 # skip 'in'
mapped_tokens.append(self.translate_token(token))
i += 1
self.tokens = mapped_tokens
self.pos = 0
self.current_token = self.next()
def translate_token(self, token):
try:
op = OPERATORS[token]
except (KeyError, TypeError):
return self.create_var(token)
else:
return op()
def next(self):
if self.pos >= len(self.tokens):
return EndToken
else:
retval = self.tokens[self.pos]
self.pos += 1
return retval
def parse(self):
retval = self.expression()
# Check that we have exhausted all the tokens
if self.current_token is not EndToken:
raise self.error_class("Unused '%s' at end of if expression." %
self.current_token.display())
return retval
def expression(self, rbp=0):
t = self.current_token
self.current_token = self.next()
left = t.nud(self)
while rbp < self.current_token.lbp:
t = self.current_token
self.current_token = self.next()
left = t.led(left, self)
return left
def create_var(self, value):
return Literal(value)
| gpl-3.0 |
justinvforvendetta/electrum-pkb | lib/network_proxy.py | 7 | 7690 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2014 Thomas Voegtlin
#
# 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, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import socket
import time
import sys
import os
import threading
import traceback
import json
import Queue
import util
from network import Network
from util import print_error, print_stderr, parse_json
from simple_config import SimpleConfig
from daemon import NetworkServer
from network import serialize_proxy, serialize_server
class NetworkProxy(util.DaemonThread):
def __init__(self, socket, config=None):
if config is None:
config = {} # Do not use mutables as default arguments!
util.DaemonThread.__init__(self)
self.config = SimpleConfig(config) if type(config) == type({}) else config
self.message_id = 0
self.unanswered_requests = {}
self.subscriptions = {}
self.debug = False
self.lock = threading.Lock()
self.pending_transactions_for_notifications = []
self.callbacks = {}
if socket:
self.pipe = util.SocketPipe(socket)
self.network = None
else:
self.pipe = util.QueuePipe()
self.network = Network(self.pipe, config)
self.network.start()
for key in ['status','banner','updated','servers','interfaces']:
value = self.network.get_status_value(key)
self.pipe.get_queue.put({'method':'network.status', 'params':[key, value]})
# status variables
self.status = 'connecting'
self.servers = {}
self.banner = ''
self.blockchain_height = 0
self.server_height = 0
self.interfaces = []
def run(self):
while self.is_running():
try:
response = self.pipe.get()
except util.timeout:
continue
if response is None:
break
self.process(response)
self.trigger_callback('stop')
if self.network:
self.network.stop()
self.print_error("stopped")
def process(self, response):
if self.debug:
print_error("<--", response)
if response.get('method') == 'network.status':
key, value = response.get('params')
if key == 'status':
self.status = value
elif key == 'banner':
self.banner = value
elif key == 'updated':
self.blockchain_height, self.server_height = value
elif key == 'servers':
self.servers = value
elif key == 'interfaces':
self.interfaces = value
self.trigger_callback(key)
return
msg_id = response.get('id')
result = response.get('result')
error = response.get('error')
if msg_id is not None:
with self.lock:
method, params, callback = self.unanswered_requests.pop(msg_id)
else:
method = response.get('method')
params = response.get('params')
with self.lock:
for k,v in self.subscriptions.items():
if (method, params) in v:
callback = k
break
else:
print_error( "received unexpected notification", method, params)
return
r = {'method':method, 'params':params, 'result':result, 'id':msg_id, 'error':error}
callback(r)
def send(self, messages, callback):
"""return the ids of the requests that we sent"""
# detect subscriptions
sub = []
for message in messages:
m, v = message
if m[-10:] == '.subscribe':
sub.append(message)
if sub:
with self.lock:
if self.subscriptions.get(callback) is None:
self.subscriptions[callback] = []
for message in sub:
if message not in self.subscriptions[callback]:
self.subscriptions[callback].append(message)
with self.lock:
requests = []
ids = []
for m in messages:
method, params = m
request = { 'id':self.message_id, 'method':method, 'params':params }
self.unanswered_requests[self.message_id] = method, params, callback
ids.append(self.message_id)
requests.append(request)
if self.debug:
print_error("-->", request)
self.message_id += 1
self.pipe.send_all(requests)
return ids
def synchronous_get(self, requests, timeout=100000000):
queue = Queue.Queue()
ids = self.send(requests, queue.put)
id2 = ids[:]
res = {}
while ids:
r = queue.get(True, timeout)
_id = r.get('id')
ids.remove(_id)
if r.get('error'):
return BaseException(r.get('error'))
result = r.get('result')
res[_id] = r.get('result')
out = []
for _id in id2:
out.append(res[_id])
return out
def get_servers(self):
return self.servers
def get_interfaces(self):
return self.interfaces
def get_header(self, height):
return self.synchronous_get([('network.get_header', [height])])[0]
def get_local_height(self):
return self.blockchain_height
def get_server_height(self):
return self.server_height
def is_connected(self):
return self.status == 'connected'
def is_connecting(self):
return self.status == 'connecting'
def is_up_to_date(self):
return self.unanswered_requests == {}
def get_parameters(self):
return self.synchronous_get([('network.get_parameters', [])])[0]
def set_parameters(self, host, port, protocol, proxy, auto_connect):
proxy_str = serialize_proxy(proxy)
server_str = serialize_server(host, port, protocol)
self.config.set_key('auto_cycle', auto_connect, True)
self.config.set_key("proxy", proxy_str, True)
self.config.set_key("server", server_str, True)
# abort if changes were not allowed by config
if self.config.get('server') != server_str or self.config.get('proxy') != proxy_str:
return
return self.synchronous_get([('network.set_parameters', (host, port, protocol, proxy, auto_connect))])[0]
def stop_daemon(self):
return self.send([('daemon.stop',[])], None)
def register_callback(self, event, callback):
with self.lock:
if not self.callbacks.get(event):
self.callbacks[event] = []
self.callbacks[event].append(callback)
def trigger_callback(self, event):
with self.lock:
callbacks = self.callbacks.get(event,[])[:]
if callbacks:
[callback() for callback in callbacks]
| gpl-3.0 |
rcuza/rsyslog | tests/elasticsearch-error-format-check.py | 21 | 4424 | import json
import sys
def checkDefaultErrorFile():
with open("rsyslog.errorfile") as json_file:
json_data = json.load(json_file)
indexCount =0
replyCount=0
for item in json_data:
if item == "request":
for reqItem in json_data[item]:
if reqItem == "url":
print "url found"
print reqItem
elif reqItem == "postdata":
print "postdata found"
indexCount = str(json_data[item]).count('\"_index\":')
print reqItem
else:
print reqItem
print "Unknown item found"
sys.exit(1)
elif item == "reply":
for replyItem in json_data[item]:
if replyItem == "items":
print json_data[item][replyItem]
replyCount = str(json_data[item][replyItem]).count('_index')
elif replyItem == "errors":
print "error node found"
elif replyItem == "took":
print "took node found"
else:
print replyItem
print "Unknown item found"
sys.exit(3)
else:
print item
print "Unknown item found"
print "error"
sys.exit(4)
if replyCount == indexCount :
return 0
else:
sys.exit(7)
return 0
def checkErrorOnlyFile():
with open("rsyslog.errorfile") as json_file:
json_data = json.load(json_file)
indexCount =0
replyCount=0
for item in json_data:
if item == "request":
print json_data[item]
indexCount = str(json_data[item]).count('\"_index\":')
elif item == "url":
print "url found"
elif item == "reply":
print json_data[item]
replyCount = str(json_data[item]).count('\"_index\":')
else:
print item
print "Unknown item found"
print "error"
sys.exit(4)
if replyCount == indexCount :
return 0
else:
sys.exit(7)
return 0
def checkErrorInterleaved():
with open("rsyslog.errorfile") as json_file:
json_data = json.load(json_file)
indexCount =0
replyCount=0
for item in json_data:
print item
if item == "response":
for responseItem in json_data[item]:
print responseItem
for res in responseItem:
print res
if res == "request":
print responseItem[res]
indexCount = str(responseItem[res]).count('\"_index\":')
print "request count ", indexCount
elif res == "reply":
print responseItem[res]
replyCount = str(responseItem[res]).count('\"_index\":')
print "reply count ", replyCount
else:
print res
print "Unknown item found"
sys.exit(9)
if replyCount != indexCount :
sys.exit(8)
elif item == "url":
print "url found"
else:
print item
print "Unknown item found"
sys.exit(4)
return 0
def checkInterleaved():
return checkErrorInterleaved()
if __name__ == "__main__":
option = sys.argv[1]
if option == "default":
checkDefaultErrorFile()
elif option == "erroronly":
checkErrorOnlyFile()
elif option == "errorinterleaved":
checkErrorInterleaved()
elif option == "interleaved":
checkErrorInterleaved()
else:
print "Usage: <script> <default|erroronly|errorinterleaved>"
sys.exit(6)
| gpl-3.0 |
scotthartbti/android_external_chromium_org | tools/linux/dump-static-initializers.py | 68 | 8251 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Dump functions called by static intializers in a Linux Release binary.
Usage example:
tools/linux/dump-static-intializers.py out/Release/chrome
A brief overview of static initialization:
1) the compiler writes out, per object file, a function that contains
the static intializers for that file.
2) the compiler also writes out a pointer to that function in a special
section.
3) at link time, the linker concatenates the function pointer sections
into a single list of all initializers.
4) at run time, on startup the binary runs all function pointers.
The functions in (1) all have mangled names of the form
_GLOBAL__I_foobar.cc
using objdump, we can disassemble those functions and dump all symbols that
they reference.
"""
import optparse
import re
import subprocess
import sys
# A map of symbol => informative text about it.
NOTES = {
'__cxa_atexit@plt': 'registers a dtor to run at exit',
'std::__ioinit': '#includes <iostream>, use <ostream> instead',
}
# Determine whether this is a git checkout (as opposed to e.g. svn).
IS_GIT_WORKSPACE = (subprocess.Popen(
['git', 'rev-parse'], stderr=subprocess.PIPE).wait() == 0)
class Demangler(object):
"""A wrapper around c++filt to provide a function to demangle symbols."""
def __init__(self):
self.cppfilt = subprocess.Popen(['c++filt'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
def Demangle(self, sym):
"""Given mangled symbol |sym|, return its demangled form."""
self.cppfilt.stdin.write(sym + '\n')
return self.cppfilt.stdout.readline().strip()
# Matches for example: "cert_logger.pb.cc", capturing "cert_logger".
protobuf_filename_re = re.compile(r'(.*)\.pb\.cc$')
def QualifyFilenameAsProto(filename):
"""Attempt to qualify a bare |filename| with a src-relative path, assuming it
is a protoc-generated file. If a single match is found, it is returned.
Otherwise the original filename is returned."""
if not IS_GIT_WORKSPACE:
return filename
match = protobuf_filename_re.match(filename)
if not match:
return filename
basename = match.groups(0)
gitlsfiles = subprocess.Popen(
['git', 'ls-files', '--', '*/%s.proto' % basename],
stdout=subprocess.PIPE)
candidate = filename
for line in gitlsfiles.stdout:
if candidate != filename:
return filename # Multiple hits, can't help.
candidate = line.strip()
return candidate
# Regex matching the substring of a symbol's demangled text representation most
# likely to appear in a source file.
# Example: "v8::internal::Builtins::InitBuiltinFunctionTable()" becomes
# "InitBuiltinFunctionTable", since the first (optional & non-capturing) group
# picks up any ::-qualification and the last fragment picks up a suffix that
# starts with an opener.
symbol_code_name_re = re.compile(r'^(?:[^(<[]*::)?([^:(<[]*).*?$')
def QualifyFilename(filename, symbol):
"""Given a bare filename and a symbol that occurs in it, attempt to qualify
it with a src-relative path. If more than one file matches, return the
original filename."""
if not IS_GIT_WORKSPACE:
return filename
match = symbol_code_name_re.match(symbol)
if not match:
return filename
symbol = match.group(1)
gitgrep = subprocess.Popen(
['git', 'grep', '-l', symbol, '--', '*/%s' % filename],
stdout=subprocess.PIPE)
candidate = filename
for line in gitgrep.stdout:
if candidate != filename: # More than one candidate; return bare filename.
return filename
candidate = line.strip()
return candidate
# Regex matching nm output for the symbols we're interested in.
# See test_ParseNmLine for examples.
nm_re = re.compile(r'(\S+) (\S+) t (?:_ZN12)?_GLOBAL__(?:sub_)?I_(.*)')
def ParseNmLine(line):
"""Given a line of nm output, parse static initializers as a
(file, start, size) tuple."""
match = nm_re.match(line)
if match:
addr, size, filename = match.groups()
return (filename, int(addr, 16), int(size, 16))
def test_ParseNmLine():
"""Verify the nm_re regex matches some sample lines."""
parse = ParseNmLine(
'0000000001919920 0000000000000008 t '
'_ZN12_GLOBAL__I_safe_browsing_service.cc')
assert parse == ('safe_browsing_service.cc', 26319136, 8), parse
parse = ParseNmLine(
'00000000026b9eb0 0000000000000024 t '
'_GLOBAL__sub_I_extension_specifics.pb.cc')
assert parse == ('extension_specifics.pb.cc', 40607408, 36), parse
# Just always run the test; it is fast enough.
test_ParseNmLine()
def ParseNm(binary):
"""Given a binary, yield static initializers as (file, start, size) tuples."""
nm = subprocess.Popen(['nm', '-S', binary], stdout=subprocess.PIPE)
for line in nm.stdout:
parse = ParseNmLine(line)
if parse:
yield parse
# Regex matching objdump output for the symbols we're interested in.
# Example line:
# 12354ab: (disassembly, including <FunctionReference>)
disassembly_re = re.compile(r'^\s+[0-9a-f]+:.*<(\S+)>')
def ExtractSymbolReferences(binary, start, end):
"""Given a span of addresses, returns symbol references from disassembly."""
cmd = ['objdump', binary, '--disassemble',
'--start-address=0x%x' % start, '--stop-address=0x%x' % end]
objdump = subprocess.Popen(cmd, stdout=subprocess.PIPE)
refs = set()
for line in objdump.stdout:
if '__static_initialization_and_destruction' in line:
raise RuntimeError, ('code mentions '
'__static_initialization_and_destruction; '
'did you accidentally run this on a Debug binary?')
match = disassembly_re.search(line)
if match:
(ref,) = match.groups()
if ref.startswith('.LC') or ref.startswith('_DYNAMIC'):
# Ignore these, they are uninformative.
continue
if ref.startswith('_GLOBAL__I_'):
# Probably a relative jump within this function.
continue
refs.add(ref)
return sorted(refs)
def main():
parser = optparse.OptionParser(usage='%prog [option] filename')
parser.add_option('-d', '--diffable', dest='diffable',
action='store_true', default=False,
help='Prints the filename on each line, for more easily '
'diff-able output. (Used by sizes.py)')
opts, args = parser.parse_args()
if len(args) != 1:
parser.error('missing filename argument')
return 1
binary = args[0]
demangler = Demangler()
file_count = 0
initializer_count = 0
files = ParseNm(binary)
if opts.diffable:
files = sorted(files)
for filename, addr, size in files:
file_count += 1
ref_output = []
qualified_filename = QualifyFilenameAsProto(filename)
if size == 2:
# gcc generates a two-byte 'repz retq' initializer when there is a
# ctor even when the ctor is empty. This is fixed in gcc 4.6, but
# Android uses gcc 4.4.
ref_output.append('[empty ctor, but it still has cost on gcc <4.6]')
else:
for ref in ExtractSymbolReferences(binary, addr, addr+size):
initializer_count += 1
ref = demangler.Demangle(ref)
if qualified_filename == filename:
qualified_filename = QualifyFilename(filename, ref)
note = ''
if ref in NOTES:
note = NOTES[ref]
elif ref.endswith('_2eproto()'):
note = 'protocol compiler bug: crbug.com/105626'
if note:
ref_output.append('%s [%s]' % (ref, note))
else:
ref_output.append(ref)
if opts.diffable:
print '\n'.join('# ' + qualified_filename + ' ' + r for r in ref_output)
else:
print '%s (initializer offset 0x%x size 0x%x)' % (qualified_filename,
addr, size)
print ''.join(' %s\n' % r for r in ref_output)
if opts.diffable:
print '#',
print 'Found %d static initializers in %d files.' % (initializer_count,
file_count)
return 0
if '__main__' == __name__:
sys.exit(main())
| bsd-3-clause |
ewdurbin/sentry | src/sentry/migrations/0015_auto__add_field_message_project__add_field_messagecountbyminute_projec.py | 36 | 14224 | # encoding: 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):
# Removing unique constraint on 'GroupedMessage', fields ['checksum', 'logger', 'view']
db.delete_unique('sentry_groupedmessage', ['checksum', 'logger', 'view'])
# Removing unique constraint on 'MessageFilterValue', fields ['group', 'value', 'key']
db.delete_unique('sentry_messagefiltervalue', ['group_id', 'value', 'key'])
# Removing unique constraint on 'FilterValue', fields ['key', 'value']
db.delete_unique('sentry_filtervalue', ['key', 'value'])
# Removing unique constraint on 'MessageCountByMinute', fields ['date', 'group']
db.delete_unique('sentry_messagecountbyminute', ['date', 'group_id'])
# Adding field 'Message.project'
db.add_column('sentry_message', 'project', self.gf('sentry.db.models.fields.FlexibleForeignKey')(to=orm['sentry.Project'], null=True), keep_default=False)
# Adding field 'MessageCountByMinute.project'
db.add_column('sentry_messagecountbyminute', 'project', self.gf('sentry.db.models.fields.FlexibleForeignKey')(to=orm['sentry.Project'], null=True), keep_default=False)
# Adding unique constraint on 'MessageCountByMinute', fields ['project', 'date', 'group']
db.create_unique('sentry_messagecountbyminute', ['project_id', 'date', 'group_id'])
# Adding field 'FilterValue.project'
db.add_column('sentry_filtervalue', 'project', self.gf('sentry.db.models.fields.FlexibleForeignKey')(to=orm['sentry.Project'], null=True), keep_default=False)
# Adding unique constraint on 'FilterValue', fields ['project', 'value', 'key']
db.create_unique('sentry_filtervalue', ['project_id', 'value', 'key'])
# Adding field 'MessageFilterValue.project'
db.add_column('sentry_messagefiltervalue', 'project', self.gf('sentry.db.models.fields.FlexibleForeignKey')(to=orm['sentry.Project'], null=True), keep_default=False)
# Adding unique constraint on 'MessageFilterValue', fields ['project', 'group', 'value', 'key']
db.create_unique('sentry_messagefiltervalue', ['project_id', 'group_id', 'value', 'key'])
# Adding field 'GroupedMessage.project'
db.add_column('sentry_groupedmessage', 'project', self.gf('sentry.db.models.fields.FlexibleForeignKey')(to=orm['sentry.Project'], null=True), keep_default=False)
# Adding unique constraint on 'GroupedMessage', fields ['project', 'checksum', 'logger', 'view']
db.create_unique('sentry_groupedmessage', ['project_id', 'checksum', 'logger', 'view'])
def backwards(self, orm):
# Removing unique constraint on 'GroupedMessage', fields ['project', 'checksum', 'logger', 'view']
db.delete_unique('sentry_groupedmessage', ['project_id', 'checksum', 'logger', 'view'])
# Removing unique constraint on 'MessageFilterValue', fields ['project', 'group', 'value', 'key']
db.delete_unique('sentry_messagefiltervalue', ['project_id', 'group_id', 'value', 'key'])
# Removing unique constraint on 'FilterValue', fields ['project', 'value', 'key']
db.delete_unique('sentry_filtervalue', ['project_id', 'value', 'key'])
# Removing unique constraint on 'MessageCountByMinute', fields ['project', 'date', 'group']
db.delete_unique('sentry_messagecountbyminute', ['project_id', 'date', 'group_id'])
# Deleting field 'Message.project'
db.delete_column('sentry_message', 'project_id')
# Deleting field 'MessageCountByMinute.project'
db.delete_column('sentry_messagecountbyminute', 'project_id')
# Adding unique constraint on 'MessageCountByMinute', fields ['date', 'group']
db.create_unique('sentry_messagecountbyminute', ['date', 'group_id'])
# Deleting field 'FilterValue.project'
db.delete_column('sentry_filtervalue', 'project_id')
# Adding unique constraint on 'FilterValue', fields ['key', 'value']
db.create_unique('sentry_filtervalue', ['key', 'value'])
# Deleting field 'MessageFilterValue.project'
db.delete_column('sentry_messagefiltervalue', 'project_id')
# Adding unique constraint on 'MessageFilterValue', fields ['group', 'value', 'key']
db.create_unique('sentry_messagefiltervalue', ['group_id', 'value', 'key'])
# Deleting field 'GroupedMessage.project'
db.delete_column('sentry_groupedmessage', 'project_id')
# Adding unique constraint on 'GroupedMessage', fields ['checksum', 'logger', 'view']
db.create_unique('sentry_groupedmessage', ['checksum', 'logger', 'view'])
models = {
'sentry.user': {
'Meta': {'object_name': 'User', 'db_table': "'auth_user'"},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'sentry.filtervalue': {
'Meta': {'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'FilterValue'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.groupedmessage': {
'Meta': {'unique_together': "(('project', 'logger', 'view', 'checksum'),)", 'object_name': 'GroupedMessage'},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'class_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '128', 'null': 'True', 'blank': 'True'}),
'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}),
'traceback': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'view': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
'sentry.message': {
'Meta': {'object_name': 'Message'},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'class_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '128', 'null': 'True', 'blank': 'True'}),
'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'message_set'", 'null': 'True', 'to': "orm['sentry.GroupedMessage']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'message_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'server_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'db_index': 'True'}),
'site': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'db_index': 'True'}),
'traceback': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'view': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
'sentry.messagecountbyminute': {
'Meta': {'unique_together': "(('project', 'group', 'date'),)", 'object_name': 'MessageCountByMinute'},
'date': ('django.db.models.fields.DateTimeField', [], {}),
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.GroupedMessage']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
},
'sentry.messagefiltervalue': {
'Meta': {'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'MessageFilterValue'},
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.GroupedMessage']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.messageindex': {
'Meta': {'unique_together': "(('column', 'value', 'object_id'),)", 'object_name': 'MessageIndex'},
'column': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'sentry.project': {
'Meta': {'object_name': 'Project'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'owner': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'sentry.projectmember': {
'Meta': {'unique_together': "(('project', 'user'),)", 'object_name': 'ProjectMember'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'permissions': ('django.db.models.fields.BigIntegerField', [], {}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
}
}
complete_apps = ['sentry']
| bsd-3-clause |
timpalpant/calibre | src/odf/text.py | 91 | 17212 | # -*- coding: utf-8 -*-
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Contributor(s):
#
from namespaces import TEXTNS
from element import Element
from style import StyleElement
# Autogenerated
def A(**args):
return Element(qname = (TEXTNS,'a'), **args)
def AlphabeticalIndex(**args):
return Element(qname = (TEXTNS,'alphabetical-index'), **args)
def AlphabeticalIndexAutoMarkFile(**args):
return Element(qname = (TEXTNS,'alphabetical-index-auto-mark-file'), **args)
def AlphabeticalIndexEntryTemplate(**args):
return Element(qname = (TEXTNS,'alphabetical-index-entry-template'), **args)
def AlphabeticalIndexMark(**args):
return Element(qname = (TEXTNS,'alphabetical-index-mark'), **args)
def AlphabeticalIndexMarkEnd(**args):
return Element(qname = (TEXTNS,'alphabetical-index-mark-end'), **args)
def AlphabeticalIndexMarkStart(**args):
return Element(qname = (TEXTNS,'alphabetical-index-mark-start'), **args)
def AlphabeticalIndexSource(**args):
return Element(qname = (TEXTNS,'alphabetical-index-source'), **args)
def AuthorInitials(**args):
return Element(qname = (TEXTNS,'author-initials'), **args)
def AuthorName(**args):
return Element(qname = (TEXTNS,'author-name'), **args)
def Bibliography(**args):
return Element(qname = (TEXTNS,'bibliography'), **args)
def BibliographyConfiguration(**args):
return Element(qname = (TEXTNS,'bibliography-configuration'), **args)
def BibliographyEntryTemplate(**args):
return Element(qname = (TEXTNS,'bibliography-entry-template'), **args)
def BibliographyMark(**args):
return Element(qname = (TEXTNS,'bibliography-mark'), **args)
def BibliographySource(**args):
return Element(qname = (TEXTNS,'bibliography-source'), **args)
def Bookmark(**args):
return Element(qname = (TEXTNS,'bookmark'), **args)
def BookmarkEnd(**args):
return Element(qname = (TEXTNS,'bookmark-end'), **args)
def BookmarkRef(**args):
return Element(qname = (TEXTNS,'bookmark-ref'), **args)
def BookmarkStart(**args):
return Element(qname = (TEXTNS,'bookmark-start'), **args)
def Change(**args):
return Element(qname = (TEXTNS,'change'), **args)
def ChangeEnd(**args):
return Element(qname = (TEXTNS,'change-end'), **args)
def ChangeStart(**args):
return Element(qname = (TEXTNS,'change-start'), **args)
def ChangedRegion(**args):
return Element(qname = (TEXTNS,'changed-region'), **args)
def Chapter(**args):
return Element(qname = (TEXTNS,'chapter'), **args)
def CharacterCount(**args):
return Element(qname = (TEXTNS,'character-count'), **args)
def ConditionalText(**args):
return Element(qname = (TEXTNS,'conditional-text'), **args)
def CreationDate(**args):
return Element(qname = (TEXTNS,'creation-date'), **args)
def CreationTime(**args):
return Element(qname = (TEXTNS,'creation-time'), **args)
def Creator(**args):
return Element(qname = (TEXTNS,'creator'), **args)
def DatabaseDisplay(**args):
return Element(qname = (TEXTNS,'database-display'), **args)
def DatabaseName(**args):
return Element(qname = (TEXTNS,'database-name'), **args)
def DatabaseNext(**args):
return Element(qname = (TEXTNS,'database-next'), **args)
def DatabaseRowNumber(**args):
return Element(qname = (TEXTNS,'database-row-number'), **args)
def DatabaseRowSelect(**args):
return Element(qname = (TEXTNS,'database-row-select'), **args)
def Date(**args):
return Element(qname = (TEXTNS,'date'), **args)
def DdeConnection(**args):
return Element(qname = (TEXTNS,'dde-connection'), **args)
def DdeConnectionDecl(**args):
return Element(qname = (TEXTNS,'dde-connection-decl'), **args)
def DdeConnectionDecls(**args):
return Element(qname = (TEXTNS,'dde-connection-decls'), **args)
def Deletion(**args):
return Element(qname = (TEXTNS,'deletion'), **args)
def Description(**args):
return Element(qname = (TEXTNS,'description'), **args)
def EditingCycles(**args):
return Element(qname = (TEXTNS,'editing-cycles'), **args)
def EditingDuration(**args):
return Element(qname = (TEXTNS,'editing-duration'), **args)
def ExecuteMacro(**args):
return Element(qname = (TEXTNS,'execute-macro'), **args)
def Expression(**args):
return Element(qname = (TEXTNS,'expression'), **args)
def FileName(**args):
return Element(qname = (TEXTNS,'file-name'), **args)
def FormatChange(**args):
return Element(qname = (TEXTNS,'format-change'), **args)
def H(**args):
return Element(qname = (TEXTNS, 'h'), **args)
def HiddenParagraph(**args):
return Element(qname = (TEXTNS,'hidden-paragraph'), **args)
def HiddenText(**args):
return Element(qname = (TEXTNS,'hidden-text'), **args)
def IllustrationIndex(**args):
return Element(qname = (TEXTNS,'illustration-index'), **args)
def IllustrationIndexEntryTemplate(**args):
return Element(qname = (TEXTNS,'illustration-index-entry-template'), **args)
def IllustrationIndexSource(**args):
return Element(qname = (TEXTNS,'illustration-index-source'), **args)
def ImageCount(**args):
return Element(qname = (TEXTNS,'image-count'), **args)
def IndexBody(**args):
return Element(qname = (TEXTNS,'index-body'), **args)
def IndexEntryBibliography(**args):
return Element(qname = (TEXTNS,'index-entry-bibliography'), **args)
def IndexEntryChapter(**args):
return Element(qname = (TEXTNS,'index-entry-chapter'), **args)
def IndexEntryLinkEnd(**args):
return Element(qname = (TEXTNS,'index-entry-link-end'), **args)
def IndexEntryLinkStart(**args):
return Element(qname = (TEXTNS,'index-entry-link-start'), **args)
def IndexEntryPageNumber(**args):
return Element(qname = (TEXTNS,'index-entry-page-number'), **args)
def IndexEntrySpan(**args):
return Element(qname = (TEXTNS,'index-entry-span'), **args)
def IndexEntryTabStop(**args):
return Element(qname = (TEXTNS,'index-entry-tab-stop'), **args)
def IndexEntryText(**args):
return Element(qname = (TEXTNS,'index-entry-text'), **args)
def IndexSourceStyle(**args):
return Element(qname = (TEXTNS,'index-source-style'), **args)
def IndexSourceStyles(**args):
return Element(qname = (TEXTNS,'index-source-styles'), **args)
def IndexTitle(**args):
return Element(qname = (TEXTNS,'index-title'), **args)
def IndexTitleTemplate(**args):
return Element(qname = (TEXTNS,'index-title-template'), **args)
def InitialCreator(**args):
return Element(qname = (TEXTNS,'initial-creator'), **args)
def Insertion(**args):
return Element(qname = (TEXTNS,'insertion'), **args)
def Keywords(**args):
return Element(qname = (TEXTNS,'keywords'), **args)
def LineBreak(**args):
return Element(qname = (TEXTNS,'line-break'), **args)
def LinenumberingConfiguration(**args):
return Element(qname = (TEXTNS,'linenumbering-configuration'), **args)
def LinenumberingSeparator(**args):
return Element(qname = (TEXTNS,'linenumbering-separator'), **args)
def List(**args):
return Element(qname = (TEXTNS,'list'), **args)
def ListHeader(**args):
return Element(qname = (TEXTNS,'list-header'), **args)
def ListItem(**args):
return Element(qname = (TEXTNS,'list-item'), **args)
def ListLevelStyleBullet(**args):
return Element(qname = (TEXTNS,'list-level-style-bullet'), **args)
def ListLevelStyleImage(**args):
return Element(qname = (TEXTNS,'list-level-style-image'), **args)
def ListLevelStyleNumber(**args):
return Element(qname = (TEXTNS,'list-level-style-number'), **args)
def ListStyle(**args):
return StyleElement(qname = (TEXTNS,'list-style'), **args)
def Measure(**args):
return Element(qname = (TEXTNS,'measure'), **args)
def ModificationDate(**args):
return Element(qname = (TEXTNS,'modification-date'), **args)
def ModificationTime(**args):
return Element(qname = (TEXTNS,'modification-time'), **args)
def Note(**args):
return Element(qname = (TEXTNS,'note'), **args)
def NoteBody(**args):
return Element(qname = (TEXTNS,'note-body'), **args)
def NoteCitation(**args):
return Element(qname = (TEXTNS,'note-citation'), **args)
def NoteContinuationNoticeBackward(**args):
return Element(qname = (TEXTNS,'note-continuation-notice-backward'), **args)
def NoteContinuationNoticeForward(**args):
return Element(qname = (TEXTNS,'note-continuation-notice-forward'), **args)
def NoteRef(**args):
return Element(qname = (TEXTNS,'note-ref'), **args)
def NotesConfiguration(**args):
return Element(qname = (TEXTNS,'notes-configuration'), **args)
def Number(**args):
return Element(qname = (TEXTNS,'number'), **args)
def NumberedParagraph(**args):
return Element(qname = (TEXTNS,'numbered-paragraph'), **args)
def ObjectCount(**args):
return Element(qname = (TEXTNS,'object-count'), **args)
def ObjectIndex(**args):
return Element(qname = (TEXTNS,'object-index'), **args)
def ObjectIndexEntryTemplate(**args):
return Element(qname = (TEXTNS,'object-index-entry-template'), **args)
def ObjectIndexSource(**args):
return Element(qname = (TEXTNS,'object-index-source'), **args)
def OutlineLevelStyle(**args):
return Element(qname = (TEXTNS,'outline-level-style'), **args)
def OutlineStyle(**args):
return Element(qname = (TEXTNS,'outline-style'), **args)
def P(**args):
return Element(qname = (TEXTNS, 'p'), **args)
def Page(**args):
return Element(qname = (TEXTNS,'page'), **args)
def PageContinuation(**args):
return Element(qname = (TEXTNS,'page-continuation'), **args)
def PageCount(**args):
return Element(qname = (TEXTNS,'page-count'), **args)
def PageNumber(**args):
return Element(qname = (TEXTNS,'page-number'), **args)
def PageSequence(**args):
return Element(qname = (TEXTNS,'page-sequence'), **args)
def PageVariableGet(**args):
return Element(qname = (TEXTNS,'page-variable-get'), **args)
def PageVariableSet(**args):
return Element(qname = (TEXTNS,'page-variable-set'), **args)
def ParagraphCount(**args):
return Element(qname = (TEXTNS,'paragraph-count'), **args)
def Placeholder(**args):
return Element(qname = (TEXTNS,'placeholder'), **args)
def PrintDate(**args):
return Element(qname = (TEXTNS,'print-date'), **args)
def PrintTime(**args):
return Element(qname = (TEXTNS,'print-time'), **args)
def PrintedBy(**args):
return Element(qname = (TEXTNS,'printed-by'), **args)
def ReferenceMark(**args):
return Element(qname = (TEXTNS,'reference-mark'), **args)
def ReferenceMarkEnd(**args):
return Element(qname = (TEXTNS,'reference-mark-end'), **args)
def ReferenceMarkStart(**args):
return Element(qname = (TEXTNS,'reference-mark-start'), **args)
def ReferenceRef(**args):
return Element(qname = (TEXTNS,'reference-ref'), **args)
def Ruby(**args):
return Element(qname = (TEXTNS,'ruby'), **args)
def RubyBase(**args):
return Element(qname = (TEXTNS,'ruby-base'), **args)
def RubyText(**args):
return Element(qname = (TEXTNS,'ruby-text'), **args)
def S(**args):
return Element(qname = (TEXTNS,'s'), **args)
def Script(**args):
return Element(qname = (TEXTNS,'script'), **args)
def Section(**args):
return Element(qname = (TEXTNS,'section'), **args)
def SectionSource(**args):
return Element(qname = (TEXTNS,'section-source'), **args)
def SenderCity(**args):
return Element(qname = (TEXTNS,'sender-city'), **args)
def SenderCompany(**args):
return Element(qname = (TEXTNS,'sender-company'), **args)
def SenderCountry(**args):
return Element(qname = (TEXTNS,'sender-country'), **args)
def SenderEmail(**args):
return Element(qname = (TEXTNS,'sender-email'), **args)
def SenderFax(**args):
return Element(qname = (TEXTNS,'sender-fax'), **args)
def SenderFirstname(**args):
return Element(qname = (TEXTNS,'sender-firstname'), **args)
def SenderInitials(**args):
return Element(qname = (TEXTNS,'sender-initials'), **args)
def SenderLastname(**args):
return Element(qname = (TEXTNS,'sender-lastname'), **args)
def SenderPhonePrivate(**args):
return Element(qname = (TEXTNS,'sender-phone-private'), **args)
def SenderPhoneWork(**args):
return Element(qname = (TEXTNS,'sender-phone-work'), **args)
def SenderPosition(**args):
return Element(qname = (TEXTNS,'sender-position'), **args)
def SenderPostalCode(**args):
return Element(qname = (TEXTNS,'sender-postal-code'), **args)
def SenderStateOrProvince(**args):
return Element(qname = (TEXTNS,'sender-state-or-province'), **args)
def SenderStreet(**args):
return Element(qname = (TEXTNS,'sender-street'), **args)
def SenderTitle(**args):
return Element(qname = (TEXTNS,'sender-title'), **args)
def Sequence(**args):
return Element(qname = (TEXTNS,'sequence'), **args)
def SequenceDecl(**args):
return Element(qname = (TEXTNS,'sequence-decl'), **args)
def SequenceDecls(**args):
return Element(qname = (TEXTNS,'sequence-decls'), **args)
def SequenceRef(**args):
return Element(qname = (TEXTNS,'sequence-ref'), **args)
def SheetName(**args):
return Element(qname = (TEXTNS,'sheet-name'), **args)
def SoftPageBreak(**args):
return Element(qname = (TEXTNS,'soft-page-break'), **args)
def SortKey(**args):
return Element(qname = (TEXTNS,'sort-key'), **args)
def Span(**args):
return Element(qname = (TEXTNS,'span'), **args)
def Subject(**args):
return Element(qname = (TEXTNS,'subject'), **args)
def Tab(**args):
return Element(qname = (TEXTNS,'tab'), **args)
def TableCount(**args):
return Element(qname = (TEXTNS,'table-count'), **args)
def TableFormula(**args):
return Element(qname = (TEXTNS,'table-formula'), **args)
def TableIndex(**args):
return Element(qname = (TEXTNS,'table-index'), **args)
def TableIndexEntryTemplate(**args):
return Element(qname = (TEXTNS,'table-index-entry-template'), **args)
def TableIndexSource(**args):
return Element(qname = (TEXTNS,'table-index-source'), **args)
def TableOfContent(**args):
return Element(qname = (TEXTNS,'table-of-content'), **args)
def TableOfContentEntryTemplate(**args):
return Element(qname = (TEXTNS,'table-of-content-entry-template'), **args)
def TableOfContentSource(**args):
return Element(qname = (TEXTNS,'table-of-content-source'), **args)
def TemplateName(**args):
return Element(qname = (TEXTNS,'template-name'), **args)
def TextInput(**args):
return Element(qname = (TEXTNS,'text-input'), **args)
def Time(**args):
return Element(qname = (TEXTNS,'time'), **args)
def Title(**args):
return Element(qname = (TEXTNS,'title'), **args)
def TocMark(**args):
return Element(qname = (TEXTNS,'toc-mark'), **args)
def TocMarkEnd(**args):
return Element(qname = (TEXTNS,'toc-mark-end'), **args)
def TocMarkStart(**args):
return Element(qname = (TEXTNS,'toc-mark-start'), **args)
def TrackedChanges(**args):
return Element(qname = (TEXTNS,'tracked-changes'), **args)
def UserDefined(**args):
return Element(qname = (TEXTNS,'user-defined'), **args)
def UserFieldDecl(**args):
return Element(qname = (TEXTNS,'user-field-decl'), **args)
def UserFieldDecls(**args):
return Element(qname = (TEXTNS,'user-field-decls'), **args)
def UserFieldGet(**args):
return Element(qname = (TEXTNS,'user-field-get'), **args)
def UserFieldInput(**args):
return Element(qname = (TEXTNS,'user-field-input'), **args)
def UserIndex(**args):
return Element(qname = (TEXTNS,'user-index'), **args)
def UserIndexEntryTemplate(**args):
return Element(qname = (TEXTNS,'user-index-entry-template'), **args)
def UserIndexMark(**args):
return Element(qname = (TEXTNS,'user-index-mark'), **args)
def UserIndexMarkEnd(**args):
return Element(qname = (TEXTNS,'user-index-mark-end'), **args)
def UserIndexMarkStart(**args):
return Element(qname = (TEXTNS,'user-index-mark-start'), **args)
def UserIndexSource(**args):
return Element(qname = (TEXTNS,'user-index-source'), **args)
def VariableDecl(**args):
return Element(qname = (TEXTNS,'variable-decl'), **args)
def VariableDecls(**args):
return Element(qname = (TEXTNS,'variable-decls'), **args)
def VariableGet(**args):
return Element(qname = (TEXTNS,'variable-get'), **args)
def VariableInput(**args):
return Element(qname = (TEXTNS,'variable-input'), **args)
def VariableSet(**args):
return Element(qname = (TEXTNS,'variable-set'), **args)
def WordCount(**args):
return Element(qname = (TEXTNS,'word-count'), **args)
| gpl-3.0 |
ol-loginov/intellij-community | python/lib/Lib/pydoc.py | 69 | 90393 | #!/usr/bin/env python
# -*- coding: Latin-1 -*-
"""Generate Python documentation in HTML or text for interactive use.
In the Python interpreter, do "from pydoc import help" to provide online
help. Calling help(thing) on a Python object documents the object.
Or, at the shell command line outside of Python:
Run "pydoc <name>" to show documentation on something. <name> may be
the name of a function, module, package, or a dotted reference to a
class or function within a module or module in a package. If the
argument contains a path segment delimiter (e.g. slash on Unix,
backslash on Windows) it is treated as the path to a Python source file.
Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
of all available modules.
Run "pydoc -p <port>" to start an HTTP server on a given port on the
local machine to generate documentation web pages.
For platforms without a command line, "pydoc -g" starts the HTTP server
and also pops up a little window for controlling it.
Run "pydoc -w <name>" to write out the HTML documentation for a module
to a file named "<name>.html".
Module docs for core modules are assumed to be in
http://www.python.org/doc/current/lib/
This can be overridden by setting the PYTHONDOCS environment variable
to a different URL or to a local directory containing the Library
Reference Manual pages.
"""
__author__ = "Ka-Ping Yee <ping@lfw.org>"
__date__ = "26 February 2001"
__version__ = "$Revision: 54366 $"
__credits__ = """Guido van Rossum, for an excellent programming language.
Tommy Burnette, the original creator of manpy.
Paul Prescod, for all his work on onlinehelp.
Richard Chamberlain, for the first implementation of textdoc.
"""
# Known bugs that can't be fixed here:
# - imp.load_module() cannot be prevented from clobbering existing
# loaded modules, so calling synopsis() on a binary module file
# changes the contents of any existing module with the same name.
# - If the __file__ attribute on a module is a relative path and
# the current directory is changed with os.chdir(), an incorrect
# path will be displayed.
import sys, imp, os, re, types, inspect, __builtin__, pkgutil
from repr import Repr
from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
try:
from collections import deque
except ImportError:
# Python 2.3 compatibility
class deque(list):
def popleft(self):
return self.pop(0)
# --------------------------------------------------------- common routines
def pathdirs():
"""Convert sys.path into a list of absolute, existing, unique paths."""
dirs = []
normdirs = []
for dir in sys.path:
dir = os.path.abspath(dir or '.')
normdir = os.path.normcase(dir)
if normdir not in normdirs and os.path.isdir(dir):
dirs.append(dir)
normdirs.append(normdir)
return dirs
def getdoc(object):
"""Get the doc string or comments for an object."""
result = inspect.getdoc(object) or inspect.getcomments(object)
return result and re.sub('^ *\n', '', rstrip(result)) or ''
def splitdoc(doc):
"""Split a doc string into a synopsis line (if any) and the rest."""
lines = split(strip(doc), '\n')
if len(lines) == 1:
return lines[0], ''
elif len(lines) >= 2 and not rstrip(lines[1]):
return lines[0], join(lines[2:], '\n')
return '', join(lines, '\n')
def classname(object, modname):
"""Get a class name and qualify it with a module name if necessary."""
name = object.__name__
if object.__module__ != modname:
name = object.__module__ + '.' + name
return name
def isdata(object):
"""Check if an object is of a type that probably means it's data."""
return not (inspect.ismodule(object) or inspect.isclass(object) or
inspect.isroutine(object) or inspect.isframe(object) or
inspect.istraceback(object) or inspect.iscode(object))
def replace(text, *pairs):
"""Do a series of global replacements on a string."""
while pairs:
text = join(split(text, pairs[0]), pairs[1])
pairs = pairs[2:]
return text
def cram(text, maxlen):
"""Omit part of a string if needed to make it fit in a maximum length."""
if len(text) > maxlen:
pre = max(0, (maxlen-3)//2)
post = max(0, maxlen-3-pre)
return text[:pre] + '...' + text[len(text)-post:]
return text
_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
def stripid(text):
"""Remove the hexadecimal id from a Python object representation."""
# The behaviour of %p is implementation-dependent in terms of case.
if _re_stripid.search(repr(Exception)):
return _re_stripid.sub(r'\1', text)
return text
def _is_some_method(obj):
return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)
def allmethods(cl):
methods = {}
for key, value in inspect.getmembers(cl, _is_some_method):
methods[key] = 1
for base in cl.__bases__:
methods.update(allmethods(base)) # all your base are belong to us
for key in methods.keys():
methods[key] = getattr(cl, key)
return methods
def _split_list(s, predicate):
"""Split sequence s via predicate, and return pair ([true], [false]).
The return value is a 2-tuple of lists,
([x for x in s if predicate(x)],
[x for x in s if not predicate(x)])
"""
yes = []
no = []
for x in s:
if predicate(x):
yes.append(x)
else:
no.append(x)
return yes, no
def visiblename(name, all=None):
"""Decide whether to show documentation on a variable."""
# Certain special names are redundant.
if name in ('__builtins__', '__doc__', '__file__', '__path__',
'__module__', '__name__', '__slots__'): return 0
# Private names are hidden, but special names are displayed.
if name.startswith('__') and name.endswith('__'): return 1
if all is not None:
# only document that which the programmer exported in __all__
return name in all
else:
return not name.startswith('_')
def classify_class_attrs(object):
"""Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
def fixup((name, kind, cls, value)):
if inspect.isdatadescriptor(value):
kind = 'data descriptor'
return name, kind, cls, value
return map(fixup, inspect.classify_class_attrs(object))
# ----------------------------------------------------- module manipulation
def ispackage(path):
"""Guess whether a path refers to a package directory."""
if os.path.isdir(path):
for ext in ('.py', '.pyc', '.pyo', '$py.class'):
if os.path.isfile(os.path.join(path, '__init__' + ext)):
return True
return False
def source_synopsis(file):
line = file.readline()
while line[:1] == '#' or not strip(line):
line = file.readline()
if not line: break
line = strip(line)
if line[:4] == 'r"""': line = line[1:]
if line[:3] == '"""':
line = line[3:]
if line[-1:] == '\\': line = line[:-1]
while not strip(line):
line = file.readline()
if not line: break
result = strip(split(line, '"""')[0])
else: result = None
return result
def synopsis(filename, cache={}):
"""Get the one-line summary out of a module file."""
mtime = os.stat(filename).st_mtime
lastupdate, result = cache.get(filename, (0, None))
if lastupdate < mtime:
info = inspect.getmoduleinfo(filename)
try:
file = open(filename)
except IOError:
# module can't be opened, so skip it
return None
if info and 'b' in info[2]: # binary modules have to be imported
try: module = imp.load_module('__temp__', file, filename, info[1:])
except: return None
result = (module.__doc__ or '').splitlines()[0]
del sys.modules['__temp__']
else: # text modules can be directly examined
result = source_synopsis(file)
file.close()
cache[filename] = (mtime, result)
return result
class ErrorDuringImport(Exception):
"""Errors that occurred while trying to import something to document it."""
def __init__(self, filename, (exc, value, tb)):
self.filename = filename
self.exc = exc
self.value = value
self.tb = tb
def __str__(self):
exc = self.exc
if type(exc) is types.ClassType:
exc = exc.__name__
return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
def importfile(path):
"""Import a Python source file or compiled file given its path."""
magic = imp.get_magic()
file = open(path, 'r')
if file.read(len(magic)) == magic:
kind = imp.PY_COMPILED
else:
kind = imp.PY_SOURCE
file.close()
filename = os.path.basename(path)
name, ext = os.path.splitext(filename)
file = open(path, 'r')
try:
module = imp.load_module(name, file, path, (ext, 'r', kind))
except:
raise ErrorDuringImport(path, sys.exc_info())
file.close()
return module
def safeimport(path, forceload=0, cache={}):
"""Import a module; handle errors; return None if the module isn't found.
If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised. Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning. If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""
try:
# If forceload is 1 and the module has been previously loaded from
# disk, we always have to reload the module. Checking the file's
# mtime isn't good enough (e.g. the module could contain a class
# that inherits from another module that has changed).
if forceload and path in sys.modules:
if path not in sys.builtin_module_names:
# Avoid simply calling reload() because it leaves names in
# the currently loaded module lying around if they're not
# defined in the new source file. Instead, remove the
# module from sys.modules and re-import. Also remove any
# submodules because they won't appear in the newly loaded
# module's namespace if they're already in sys.modules.
subs = [m for m in sys.modules if m.startswith(path + '.')]
for key in [path] + subs:
# Prevent garbage collection.
cache[key] = sys.modules[key]
del sys.modules[key]
module = __import__(path)
except:
# Did the error occur before or after the module was found?
(exc, value, tb) = info = sys.exc_info()
if path in sys.modules:
# An error occurred while executing the imported module.
raise ErrorDuringImport(sys.modules[path].__file__, info)
elif exc is SyntaxError:
# A SyntaxError occurred before we could execute the module.
raise ErrorDuringImport(value.filename, info)
elif exc is ImportError and \
split(lower(str(value)))[:2] == ['no', 'module']:
# The module was not found.
return None
else:
# Some other error occurred during the importing process.
raise ErrorDuringImport(path, sys.exc_info())
for part in split(path, '.')[1:]:
try: module = getattr(module, part)
except AttributeError: return None
return module
# ---------------------------------------------------- formatter base class
class Doc:
def document(self, object, name=None, *args):
"""Generate documentation for an object."""
args = (object, name) + args
# 'try' clause is to attempt to handle the possibility that inspect
# identifies something in a way that pydoc itself has issues handling;
# think 'super' and how it is a descriptor (which raises the exception
# by lacking a __name__ attribute) and an instance.
if inspect.isgetsetdescriptor(object): return self.docdata(*args)
if inspect.ismemberdescriptor(object): return self.docdata(*args)
try:
if inspect.ismodule(object): return self.docmodule(*args)
if inspect.isclass(object): return self.docclass(*args)
if inspect.isroutine(object): return self.docroutine(*args)
except AttributeError:
pass
if isinstance(object, property): return self.docproperty(*args)
return self.docother(*args)
def fail(self, object, name=None, *args):
"""Raise an exception for unimplemented types."""
message = "don't know how to document object%s of type %s" % (
name and ' ' + repr(name), type(object).__name__)
raise TypeError, message
docmodule = docclass = docroutine = docother = docproperty = docdata = fail
def getdocloc(self, object):
"""Return the location of module docs or None"""
try:
file = inspect.getabsfile(object)
except TypeError:
file = '(built-in)'
docloc = os.environ.get("PYTHONDOCS",
"http://www.python.org/doc/current/lib")
basedir = os.path.join(sys.exec_prefix, "lib",
"python"+sys.version[0:3])
if (isinstance(object, type(os)) and
(object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
'marshal', 'posix', 'signal', 'sys',
'thread', 'zipimport') or
(file.startswith(basedir) and
not file.startswith(os.path.join(basedir, 'site-packages'))))):
htmlfile = "module-%s.html" % object.__name__
if docloc.startswith("http://"):
docloc = "%s/%s" % (docloc.rstrip("/"), htmlfile)
else:
docloc = os.path.join(docloc, htmlfile)
else:
docloc = None
return docloc
# -------------------------------------------- HTML documentation generator
class HTMLRepr(Repr):
"""Class for safely making an HTML representation of a Python object."""
def __init__(self):
Repr.__init__(self)
self.maxlist = self.maxtuple = 20
self.maxdict = 10
self.maxstring = self.maxother = 100
def escape(self, text):
return replace(text, '&', '&', '<', '<', '>', '>')
def repr(self, object):
return Repr.repr(self, object)
def repr1(self, x, level):
if hasattr(type(x), '__name__'):
methodname = 'repr_' + join(split(type(x).__name__), '_')
if hasattr(self, methodname):
return getattr(self, methodname)(x, level)
return self.escape(cram(stripid(repr(x)), self.maxother))
def repr_string(self, x, level):
test = cram(x, self.maxstring)
testrepr = repr(test)
if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
# Backslashes are only literal in the string and are never
# needed to make any special characters, so show a raw string.
return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
r'<font color="#c040c0">\1</font>',
self.escape(testrepr))
repr_str = repr_string
def repr_instance(self, x, level):
try:
return self.escape(cram(stripid(repr(x)), self.maxstring))
except:
return self.escape('<%s instance>' % x.__class__.__name__)
repr_unicode = repr_string
class HTMLDoc(Doc):
"""Formatter class for HTML documentation."""
# ------------------------------------------- HTML formatting utilities
_repr_instance = HTMLRepr()
repr = _repr_instance.repr
escape = _repr_instance.escape
def page(self, title, contents):
"""Format an HTML page."""
return '''
<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: %s</title>
</head><body bgcolor="#f0f0f8">
%s
</body></html>''' % (title, contents)
def heading(self, title, fgcol, bgcol, extras=''):
"""Format a page heading."""
return '''
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="%s">
<td valign=bottom> <br>
<font color="%s" face="helvetica, arial"> <br>%s</font></td
><td align=right valign=bottom
><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
''' % (bgcol, fgcol, title, fgcol, extras or ' ')
def section(self, title, fgcol, bgcol, contents, width=6,
prelude='', marginalia=None, gap=' '):
"""Format a section with a heading."""
if marginalia is None:
marginalia = '<tt>' + ' ' * width + '</tt>'
result = '''<p>
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="%s">
<td colspan=3 valign=bottom> <br>
<font color="%s" face="helvetica, arial">%s</font></td></tr>
''' % (bgcol, fgcol, title)
if prelude:
result = result + '''
<tr bgcolor="%s"><td rowspan=2>%s</td>
<td colspan=2>%s</td></tr>
<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
else:
result = result + '''
<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
return result + '\n<td width="100%%">%s</td></tr></table>' % contents
def bigsection(self, title, *args):
"""Format a section with a big heading."""
title = '<big><strong>%s</strong></big>' % title
return self.section(title, *args)
def preformat(self, text):
"""Format literal preformatted text."""
text = self.escape(expandtabs(text))
return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
' ', ' ', '\n', '<br>\n')
def multicolumn(self, list, format, cols=4):
"""Format a list of items into a multi-column list."""
result = ''
rows = (len(list)+cols-1)/cols
for col in range(cols):
result = result + '<td width="%d%%" valign=top>' % (100/cols)
for i in range(rows*col, rows*col+rows):
if i < len(list):
result = result + format(list[i]) + '<br>\n'
result = result + '</td>'
return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
def grey(self, text): return '<font color="#909090">%s</font>' % text
def namelink(self, name, *dicts):
"""Make a link for an identifier, given name-to-URL mappings."""
for dict in dicts:
if name in dict:
return '<a href="%s">%s</a>' % (dict[name], name)
return name
def classlink(self, object, modname):
"""Make a link for a class."""
name, module = object.__name__, sys.modules.get(object.__module__)
if hasattr(module, name) and getattr(module, name) is object:
return '<a href="%s.html#%s">%s</a>' % (
module.__name__, name, classname(object, modname))
return classname(object, modname)
def modulelink(self, object):
"""Make a link for a module."""
return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
def modpkglink(self, (name, path, ispackage, shadowed)):
"""Make a link for a module or package to display in an index."""
if shadowed:
return self.grey(name)
if path:
url = '%s.%s.html' % (path, name)
else:
url = '%s.html' % name
if ispackage:
text = '<strong>%s</strong> (package)' % name
else:
text = name
return '<a href="%s">%s</a>' % (url, text)
def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
"""Mark up some plain text, given a context of symbols to look for.
Each context dictionary maps object names to anchor names."""
escape = escape or self.escape
results = []
here = 0
pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
r'RFC[- ]?(\d+)|'
r'PEP[- ]?(\d+)|'
r'(self\.)?(\w+))')
while True:
match = pattern.search(text, here)
if not match: break
start, end = match.span()
results.append(escape(text[here:start]))
all, scheme, rfc, pep, selfdot, name = match.groups()
if scheme:
url = escape(all).replace('"', '"')
results.append('<a href="%s">%s</a>' % (url, url))
elif rfc:
url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif pep:
url = 'http://www.python.org/peps/pep-%04d.html' % int(pep)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif text[end:end+1] == '(':
results.append(self.namelink(name, methods, funcs, classes))
elif selfdot:
results.append('self.<strong>%s</strong>' % name)
else:
results.append(self.namelink(name, classes))
here = end
results.append(escape(text[here:]))
return join(results, '')
# ---------------------------------------------- type-specific routines
def formattree(self, tree, modname, parent=None):
"""Produce HTML for a class tree as given by inspect.getclasstree()."""
result = ''
for entry in tree:
if type(entry) is type(()):
c, bases = entry
result = result + '<dt><font face="helvetica, arial">'
result = result + self.classlink(c, modname)
if bases and bases != (parent,):
parents = []
for base in bases:
parents.append(self.classlink(base, modname))
result = result + '(' + join(parents, ', ') + ')'
result = result + '\n</font></dt>'
elif type(entry) is type([]):
result = result + '<dd>\n%s</dd>\n' % self.formattree(
entry, modname, c)
return '<dl>\n%s</dl>\n' % result
def docmodule(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a module object."""
name = object.__name__ # ignore the passed-in name
try:
all = object.__all__
except AttributeError:
all = None
parts = split(name, '.')
links = []
for i in range(len(parts)-1):
links.append(
'<a href="%s.html"><font color="#ffffff">%s</font></a>' %
(join(parts[:i+1], '.'), parts[i]))
linkedname = join(links + parts[-1:], '.')
head = '<big><big><strong>%s</strong></big></big>' % linkedname
try:
path = inspect.getabsfile(object)
url = path
if sys.platform == 'win32':
import nturl2path
url = nturl2path.pathname2url(path)
filelink = '<a href="file:%s">%s</a>' % (url, path)
except TypeError:
filelink = '(built-in)'
info = []
if hasattr(object, '__version__'):
version = str(object.__version__)
if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
version = strip(version[11:-1])
info.append('version %s' % self.escape(version))
if hasattr(object, '__date__'):
info.append(self.escape(str(object.__date__)))
if info:
head = head + ' (%s)' % join(info, ', ')
docloc = self.getdocloc(object)
if docloc is not None:
docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
else:
docloc = ''
result = self.heading(
head, '#ffffff', '#7799ee',
'<a href=".">index</a><br>' + filelink + docloc)
modules = inspect.getmembers(object, inspect.ismodule)
classes, cdict = [], {}
for key, value in inspect.getmembers(object, inspect.isclass):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None or
(inspect.getmodule(value) or object) is object):
if visiblename(key, all):
classes.append((key, value))
cdict[key] = cdict[value] = '#' + key
for key, value in classes:
for base in value.__bases__:
key, modname = base.__name__, base.__module__
module = sys.modules.get(modname)
if modname != name and module and hasattr(module, key):
if getattr(module, key) is base:
if not key in cdict:
cdict[key] = cdict[base] = modname + '.html#' + key
funcs, fdict = [], {}
for key, value in inspect.getmembers(object, inspect.isroutine):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None or
inspect.isbuiltin(value) or inspect.getmodule(value) is object):
if visiblename(key, all):
funcs.append((key, value))
fdict[key] = '#-' + key
if inspect.isfunction(value): fdict[value] = fdict[key]
data = []
for key, value in inspect.getmembers(object, isdata):
if visiblename(key, all):
data.append((key, value))
doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
doc = doc and '<tt>%s</tt>' % doc
result = result + '<p>%s</p>\n' % doc
if hasattr(object, '__path__'):
modpkgs = []
for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
modpkgs.append((modname, name, ispkg, 0))
modpkgs.sort()
contents = self.multicolumn(modpkgs, self.modpkglink)
result = result + self.bigsection(
'Package Contents', '#ffffff', '#aa55cc', contents)
elif modules:
contents = self.multicolumn(
modules, lambda (key, value), s=self: s.modulelink(value))
result = result + self.bigsection(
'Modules', '#fffff', '#aa55cc', contents)
if classes:
classlist = map(lambda (key, value): value, classes)
contents = [
self.formattree(inspect.getclasstree(classlist, 1), name)]
for key, value in classes:
contents.append(self.document(value, key, name, fdict, cdict))
result = result + self.bigsection(
'Classes', '#ffffff', '#ee77aa', join(contents))
if funcs:
contents = []
for key, value in funcs:
contents.append(self.document(value, key, name, fdict, cdict))
result = result + self.bigsection(
'Functions', '#ffffff', '#eeaa77', join(contents))
if data:
contents = []
for key, value in data:
contents.append(self.document(value, key))
result = result + self.bigsection(
'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
if hasattr(object, '__author__'):
contents = self.markup(str(object.__author__), self.preformat)
result = result + self.bigsection(
'Author', '#ffffff', '#7799ee', contents)
if hasattr(object, '__credits__'):
contents = self.markup(str(object.__credits__), self.preformat)
result = result + self.bigsection(
'Credits', '#ffffff', '#7799ee', contents)
return result
def docclass(self, object, name=None, mod=None, funcs={}, classes={},
*ignored):
"""Produce HTML documentation for a class object."""
realname = object.__name__
name = name or realname
bases = object.__bases__
contents = []
push = contents.append
# Cute little class to pump out a horizontal rule between sections.
class HorizontalRule:
def __init__(self):
self.needone = 0
def maybe(self):
if self.needone:
push('<hr>\n')
self.needone = 1
hr = HorizontalRule()
# List the mro, if non-trivial.
mro = deque(inspect.getmro(object))
if len(mro) > 2:
hr.maybe()
push('<dl><dt>Method resolution order:</dt>\n')
for base in mro:
push('<dd>%s</dd>\n' % self.classlink(base,
object.__module__))
push('</dl>\n')
def spill(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
push(self.document(getattr(object, name), name, mod,
funcs, classes, mdict, object))
push('\n')
return attrs
def spilldescriptors(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
push(self._docdescriptor(name, value, mod))
return attrs
def spilldata(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
base = self.docother(getattr(object, name), name, mod)
if callable(value) or inspect.isdatadescriptor(value):
doc = getattr(value, "__doc__", None)
else:
doc = None
if doc is None:
push('<dl><dt>%s</dl>\n' % base)
else:
doc = self.markup(getdoc(value), self.preformat,
funcs, classes, mdict)
doc = '<dd><tt>%s</tt>' % doc
push('<dl><dt>%s%s</dl>\n' % (base, doc))
push('\n')
return attrs
attrs = filter(lambda (name, kind, cls, value): visiblename(name),
classify_class_attrs(object))
mdict = {}
for key, kind, homecls, value in attrs:
mdict[key] = anchor = '#' + name + '-' + key
value = getattr(object, key)
try:
# The value may not be hashable (e.g., a data attr with
# a dict or list value).
mdict[value] = anchor
except TypeError:
pass
while attrs:
if mro:
thisclass = mro.popleft()
else:
thisclass = attrs[0][2]
attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
if thisclass is __builtin__.object:
attrs = inherited
continue
elif thisclass is object:
tag = 'defined here'
else:
tag = 'inherited from %s' % self.classlink(thisclass,
object.__module__)
tag += ':<br>\n'
# Sort attrs by name.
try:
attrs.sort(key=lambda t: t[0])
except TypeError:
attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat
# Pump out the attrs, segregated by kind.
attrs = spill('Methods %s' % tag, attrs,
lambda t: t[1] == 'method')
attrs = spill('Class methods %s' % tag, attrs,
lambda t: t[1] == 'class method')
attrs = spill('Static methods %s' % tag, attrs,
lambda t: t[1] == 'static method')
attrs = spilldescriptors('Data descriptors %s' % tag, attrs,
lambda t: t[1] == 'data descriptor')
attrs = spilldata('Data and other attributes %s' % tag, attrs,
lambda t: t[1] == 'data')
assert attrs == []
attrs = inherited
contents = ''.join(contents)
if name == realname:
title = '<a name="%s">class <strong>%s</strong></a>' % (
name, realname)
else:
title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
name, name, realname)
if bases:
parents = []
for base in bases:
parents.append(self.classlink(base, object.__module__))
title = title + '(%s)' % join(parents, ', ')
doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
doc = doc and '<tt>%s<br> </tt>' % doc
return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
def formatvalue(self, object):
"""Format an argument default value as text."""
return self.grey('=' + self.repr(object))
def docroutine(self, object, name=None, mod=None,
funcs={}, classes={}, methods={}, cl=None):
"""Produce HTML documentation for a function or method object."""
realname = object.__name__
name = name or realname
anchor = (cl and cl.__name__ or '') + '-' + name
note = ''
skipdocs = 0
if inspect.ismethod(object):
imclass = object.im_class
if cl:
if imclass is not cl:
note = ' from ' + self.classlink(imclass, mod)
else:
if object.im_self is not None:
note = ' method of %s instance' % self.classlink(
object.im_self.__class__, mod)
else:
note = ' unbound %s method' % self.classlink(imclass,mod)
object = object.im_func
if name == realname:
title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
else:
if (cl and realname in cl.__dict__ and
cl.__dict__[realname] is object):
reallink = '<a href="#%s">%s</a>' % (
cl.__name__ + '-' + realname, realname)
skipdocs = 1
else:
reallink = realname
title = '<a name="%s"><strong>%s</strong></a> = %s' % (
anchor, name, reallink)
if inspect.isfunction(object):
args, varargs, varkw, defaults = inspect.getargspec(object)
argspec = inspect.formatargspec(
args, varargs, varkw, defaults, formatvalue=self.formatvalue)
if realname == '<lambda>':
title = '<strong>%s</strong> <em>lambda</em> ' % name
argspec = argspec[1:-1] # remove parentheses
else:
argspec = '(...)'
decl = title + argspec + (note and self.grey(
'<font face="helvetica, arial">%s</font>' % note))
if skipdocs:
return '<dl><dt>%s</dt></dl>\n' % decl
else:
doc = self.markup(
getdoc(object), self.preformat, funcs, classes, methods)
doc = doc and '<dd><tt>%s</tt></dd>' % doc
return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
def _docdescriptor(self, name, value, mod):
results = []
push = results.append
if name:
push('<dl><dt><strong>%s</strong></dt>\n' % name)
if value.__doc__ is not None:
doc = self.markup(getdoc(value), self.preformat)
push('<dd><tt>%s</tt></dd>\n' % doc)
push('</dl>\n')
return ''.join(results)
def docproperty(self, object, name=None, mod=None, cl=None):
"""Produce html documentation for a property."""
return self._docdescriptor(name, object, mod)
def docother(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a data object."""
lhs = name and '<strong>%s</strong> = ' % name or ''
return lhs + self.repr(object)
def docdata(self, object, name=None, mod=None, cl=None):
"""Produce html documentation for a data descriptor."""
return self._docdescriptor(name, object, mod)
def index(self, dir, shadowed=None):
"""Generate an HTML index for a directory of modules."""
modpkgs = []
if shadowed is None: shadowed = {}
for importer, name, ispkg in pkgutil.iter_modules([dir]):
modpkgs.append((name, '', ispkg, name in shadowed))
shadowed[name] = 1
modpkgs.sort()
contents = self.multicolumn(modpkgs, self.modpkglink)
return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
# -------------------------------------------- text documentation generator
class TextRepr(Repr):
"""Class for safely making a text representation of a Python object."""
def __init__(self):
Repr.__init__(self)
self.maxlist = self.maxtuple = 20
self.maxdict = 10
self.maxstring = self.maxother = 100
def repr1(self, x, level):
if hasattr(type(x), '__name__'):
methodname = 'repr_' + join(split(type(x).__name__), '_')
if hasattr(self, methodname):
return getattr(self, methodname)(x, level)
return cram(stripid(repr(x)), self.maxother)
def repr_string(self, x, level):
test = cram(x, self.maxstring)
testrepr = repr(test)
if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
# Backslashes are only literal in the string and are never
# needed to make any special characters, so show a raw string.
return 'r' + testrepr[0] + test + testrepr[0]
return testrepr
repr_str = repr_string
def repr_instance(self, x, level):
try:
return cram(stripid(repr(x)), self.maxstring)
except:
return '<%s instance>' % x.__class__.__name__
class TextDoc(Doc):
"""Formatter class for text documentation."""
# ------------------------------------------- text formatting utilities
_repr_instance = TextRepr()
repr = _repr_instance.repr
def bold(self, text):
"""Format a string in bold by overstriking."""
return join(map(lambda ch: ch + '\b' + ch, text), '')
def indent(self, text, prefix=' '):
"""Indent text by prepending a given prefix to each line."""
if not text: return ''
lines = split(text, '\n')
lines = map(lambda line, prefix=prefix: prefix + line, lines)
if lines: lines[-1] = rstrip(lines[-1])
return join(lines, '\n')
def section(self, title, contents):
"""Format a section with a given heading."""
return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
# ---------------------------------------------- type-specific routines
def formattree(self, tree, modname, parent=None, prefix=''):
"""Render in text a class tree as returned by inspect.getclasstree()."""
result = ''
for entry in tree:
if type(entry) is type(()):
c, bases = entry
result = result + prefix + classname(c, modname)
if bases and bases != (parent,):
parents = map(lambda c, m=modname: classname(c, m), bases)
result = result + '(%s)' % join(parents, ', ')
result = result + '\n'
elif type(entry) is type([]):
result = result + self.formattree(
entry, modname, c, prefix + ' ')
return result
def docmodule(self, object, name=None, mod=None):
"""Produce text documentation for a given module object."""
name = object.__name__ # ignore the passed-in name
synop, desc = splitdoc(getdoc(object))
result = self.section('NAME', name + (synop and ' - ' + synop))
try:
all = object.__all__
except AttributeError:
all = None
try:
file = inspect.getabsfile(object)
except TypeError:
file = '(built-in)'
result = result + self.section('FILE', file)
docloc = self.getdocloc(object)
if docloc is not None:
result = result + self.section('MODULE DOCS', docloc)
if desc:
result = result + self.section('DESCRIPTION', desc)
classes = []
for key, value in inspect.getmembers(object, inspect.isclass):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None
or (inspect.getmodule(value) or object) is object):
if visiblename(key, all):
classes.append((key, value))
funcs = []
for key, value in inspect.getmembers(object, inspect.isroutine):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None or
inspect.isbuiltin(value) or inspect.getmodule(value) is object):
if visiblename(key, all):
funcs.append((key, value))
data = []
for key, value in inspect.getmembers(object, isdata):
if visiblename(key, all):
data.append((key, value))
if hasattr(object, '__path__'):
modpkgs = []
for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
if ispkg:
modpkgs.append(modname + ' (package)')
else:
modpkgs.append(modname)
modpkgs.sort()
result = result + self.section(
'PACKAGE CONTENTS', join(modpkgs, '\n'))
if classes:
classlist = map(lambda (key, value): value, classes)
contents = [self.formattree(
inspect.getclasstree(classlist, 1), name)]
for key, value in classes:
contents.append(self.document(value, key, name))
result = result + self.section('CLASSES', join(contents, '\n'))
if funcs:
contents = []
for key, value in funcs:
contents.append(self.document(value, key, name))
result = result + self.section('FUNCTIONS', join(contents, '\n'))
if data:
contents = []
for key, value in data:
contents.append(self.docother(value, key, name, maxlen=70))
result = result + self.section('DATA', join(contents, '\n'))
if hasattr(object, '__version__'):
version = str(object.__version__)
if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
version = strip(version[11:-1])
result = result + self.section('VERSION', version)
if hasattr(object, '__date__'):
result = result + self.section('DATE', str(object.__date__))
if hasattr(object, '__author__'):
result = result + self.section('AUTHOR', str(object.__author__))
if hasattr(object, '__credits__'):
result = result + self.section('CREDITS', str(object.__credits__))
return result
def docclass(self, object, name=None, mod=None):
"""Produce text documentation for a given class object."""
realname = object.__name__
name = name or realname
bases = object.__bases__
def makename(c, m=object.__module__):
return classname(c, m)
if name == realname:
title = 'class ' + self.bold(realname)
else:
title = self.bold(name) + ' = class ' + realname
if bases:
parents = map(makename, bases)
title = title + '(%s)' % join(parents, ', ')
doc = getdoc(object)
contents = doc and [doc + '\n'] or []
push = contents.append
# List the mro, if non-trivial.
mro = deque(inspect.getmro(object))
if len(mro) > 2:
push("Method resolution order:")
for base in mro:
push(' ' + makename(base))
push('')
# Cute little class to pump out a horizontal rule between sections.
class HorizontalRule:
def __init__(self):
self.needone = 0
def maybe(self):
if self.needone:
push('-' * 70)
self.needone = 1
hr = HorizontalRule()
def spill(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
push(self.document(getattr(object, name),
name, mod, object))
return attrs
def spilldescriptors(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
push(self._docdescriptor(name, value, mod))
return attrs
def spilldata(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
if callable(value) or inspect.isdatadescriptor(value):
doc = getdoc(value)
else:
doc = None
push(self.docother(getattr(object, name),
name, mod, maxlen=70, doc=doc) + '\n')
return attrs
attrs = filter(lambda (name, kind, cls, value): visiblename(name),
classify_class_attrs(object))
while attrs:
if mro:
thisclass = mro.popleft()
else:
thisclass = attrs[0][2]
attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
if thisclass is __builtin__.object:
attrs = inherited
continue
elif thisclass is object:
tag = "defined here"
else:
tag = "inherited from %s" % classname(thisclass,
object.__module__)
filter(lambda t: not t[0].startswith('_'), attrs)
# Sort attrs by name.
attrs.sort()
# Pump out the attrs, segregated by kind.
attrs = spill("Methods %s:\n" % tag, attrs,
lambda t: t[1] == 'method')
attrs = spill("Class methods %s:\n" % tag, attrs,
lambda t: t[1] == 'class method')
attrs = spill("Static methods %s:\n" % tag, attrs,
lambda t: t[1] == 'static method')
attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
lambda t: t[1] == 'data descriptor')
attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
lambda t: t[1] == 'data')
assert attrs == []
attrs = inherited
contents = '\n'.join(contents)
if not contents:
return title + '\n'
return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n'
def formatvalue(self, object):
"""Format an argument default value as text."""
return '=' + self.repr(object)
def docroutine(self, object, name=None, mod=None, cl=None):
"""Produce text documentation for a function or method object."""
realname = object.__name__
name = name or realname
note = ''
skipdocs = 0
if inspect.ismethod(object):
imclass = object.im_class
if cl:
if imclass is not cl:
note = ' from ' + classname(imclass, mod)
else:
if object.im_self is not None:
note = ' method of %s instance' % classname(
object.im_self.__class__, mod)
else:
note = ' unbound %s method' % classname(imclass,mod)
object = object.im_func
if name == realname:
title = self.bold(realname)
else:
if (cl and realname in cl.__dict__ and
cl.__dict__[realname] is object):
skipdocs = 1
title = self.bold(name) + ' = ' + realname
if inspect.isfunction(object):
args, varargs, varkw, defaults = inspect.getargspec(object)
argspec = inspect.formatargspec(
args, varargs, varkw, defaults, formatvalue=self.formatvalue)
if realname == '<lambda>':
title = self.bold(name) + ' lambda '
argspec = argspec[1:-1] # remove parentheses
else:
argspec = '(...)'
decl = title + argspec + note
if skipdocs:
return decl + '\n'
else:
doc = getdoc(object) or ''
return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n')
def _docdescriptor(self, name, value, mod):
results = []
push = results.append
if name:
push(self.bold(name))
push('\n')
doc = getdoc(value) or ''
if doc:
push(self.indent(doc))
push('\n')
return ''.join(results)
def docproperty(self, object, name=None, mod=None, cl=None):
"""Produce text documentation for a property."""
return self._docdescriptor(name, object, mod)
def docdata(self, object, name=None, mod=None, cl=None):
"""Produce text documentation for a data descriptor."""
return self._docdescriptor(name, object, mod)
def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
"""Produce text documentation for a data object."""
repr = self.repr(object)
if maxlen:
line = (name and name + ' = ' or '') + repr
chop = maxlen - len(line)
if chop < 0: repr = repr[:chop] + '...'
line = (name and self.bold(name) + ' = ' or '') + repr
if doc is not None:
line += '\n' + self.indent(str(doc))
return line
# --------------------------------------------------------- user interfaces
def pager(text):
"""The first time this is called, determine what kind of pager to use."""
global pager
pager = getpager()
pager(text)
def getpager():
"""Decide what method to use for paging through text."""
if sys.platform.startswith('java'):
return plainpager
if type(sys.stdout) is not types.FileType:
return plainpager
if not sys.stdin.isatty() or not sys.stdout.isatty():
return plainpager
if 'PAGER' in os.environ:
if sys.platform == 'win32': # pipes completely broken in Windows
return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
elif os.environ.get('TERM') in ('dumb', 'emacs'):
return lambda text: pipepager(plain(text), os.environ['PAGER'])
else:
return lambda text: pipepager(text, os.environ['PAGER'])
if os.environ.get('TERM') in ('dumb', 'emacs'):
return plainpager
if sys.platform == 'win32' or sys.platform.startswith('os2'):
return lambda text: tempfilepager(plain(text), 'more <')
if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
return lambda text: pipepager(text, 'less')
import tempfile
(fd, filename) = tempfile.mkstemp()
os.close(fd)
try:
if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
return lambda text: pipepager(text, 'more')
else:
return ttypager
finally:
os.unlink(filename)
def plain(text):
"""Remove boldface formatting from text."""
return re.sub('.\b', '', text)
def pipepager(text, cmd):
"""Page through text by feeding it to another program."""
pipe = os.popen(cmd, 'w')
try:
pipe.write(text)
pipe.close()
except IOError:
pass # Ignore broken pipes caused by quitting the pager program.
def tempfilepager(text, cmd):
"""Page through text by invoking a program on a temporary file."""
import tempfile
filename = tempfile.mktemp()
file = open(filename, 'w')
file.write(text)
file.close()
try:
os.system(cmd + ' ' + filename)
finally:
os.unlink(filename)
def ttypager(text):
"""Page through text on a text terminal."""
lines = split(plain(text), '\n')
try:
import tty
fd = sys.stdin.fileno()
old = tty.tcgetattr(fd)
tty.setcbreak(fd)
getchar = lambda: sys.stdin.read(1)
except (ImportError, AttributeError):
tty = None
getchar = lambda: sys.stdin.readline()[:-1][:1]
try:
r = inc = os.environ.get('LINES', 25) - 1
sys.stdout.write(join(lines[:inc], '\n') + '\n')
while lines[r:]:
sys.stdout.write('-- more --')
sys.stdout.flush()
c = getchar()
if c in ('q', 'Q'):
sys.stdout.write('\r \r')
break
elif c in ('\r', '\n'):
sys.stdout.write('\r \r' + lines[r] + '\n')
r = r + 1
continue
if c in ('b', 'B', '\x1b'):
r = r - inc - inc
if r < 0: r = 0
sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
r = r + inc
finally:
if tty:
tty.tcsetattr(fd, tty.TCSAFLUSH, old)
def plainpager(text):
"""Simply print unformatted text. This is the ultimate fallback."""
sys.stdout.write(plain(text))
def describe(thing):
"""Produce a short description of the given thing."""
if inspect.ismodule(thing):
if thing.__name__ in sys.builtin_module_names:
return 'built-in module ' + thing.__name__
if hasattr(thing, '__path__'):
return 'package ' + thing.__name__
else:
return 'module ' + thing.__name__
if inspect.isbuiltin(thing):
return 'built-in function ' + thing.__name__
if inspect.isgetsetdescriptor(thing):
return 'getset descriptor %s.%s.%s' % (
thing.__objclass__.__module__, thing.__objclass__.__name__,
thing.__name__)
if inspect.ismemberdescriptor(thing):
return 'member descriptor %s.%s.%s' % (
thing.__objclass__.__module__, thing.__objclass__.__name__,
thing.__name__)
if inspect.isclass(thing):
return 'class ' + thing.__name__
if inspect.isfunction(thing):
return 'function ' + thing.__name__
if inspect.ismethod(thing):
return 'method ' + thing.__name__
if type(thing) is types.InstanceType:
return 'instance of ' + thing.__class__.__name__
return type(thing).__name__
def locate(path, forceload=0):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in split(path, '.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
if nextmodule: module, n = nextmodule, n + 1
else: break
if module:
object = module
for part in parts[n:]:
try: object = getattr(object, part)
except AttributeError: return None
return object
else:
if hasattr(__builtin__, path):
return getattr(__builtin__, path)
# --------------------------------------- interactive interpreter interface
text = TextDoc()
html = HTMLDoc()
def resolve(thing, forceload=0):
"""Given an object or a path to an object, get the object and its name."""
if isinstance(thing, str):
object = locate(thing, forceload)
if not object:
raise ImportError, 'no Python documentation found for %r' % thing
return object, thing
else:
return thing, getattr(thing, '__name__', None)
def doc(thing, title='Python Library Documentation: %s', forceload=0):
"""Display text documentation, given an object or a path to an object."""
try:
object, name = resolve(thing, forceload)
desc = describe(object)
module = inspect.getmodule(object)
if name and '.' in name:
desc += ' in ' + name[:name.rfind('.')]
elif module and module is not object:
desc += ' in module ' + module.__name__
if not (inspect.ismodule(object) or
inspect.isclass(object) or
inspect.isroutine(object) or
inspect.isgetsetdescriptor(object) or
inspect.ismemberdescriptor(object) or
isinstance(object, property)):
# If the passed object is a piece of data or an instance,
# document its available methods instead of its value.
object = type(object)
desc += ' object'
pager(title % desc + '\n\n' + text.document(object, name))
except (ImportError, ErrorDuringImport), value:
print value
def writedoc(thing, forceload=0):
"""Write HTML documentation to a file in the current directory."""
try:
object, name = resolve(thing, forceload)
page = html.page(describe(object), html.document(object, name))
file = open(name + '.html', 'w')
file.write(page)
file.close()
print 'wrote', name + '.html'
except (ImportError, ErrorDuringImport), value:
print value
def writedocs(dir, pkgpath='', done=None):
"""Write out HTML documentation for all modules in a directory tree."""
if done is None: done = {}
for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):
writedoc(modname)
return
class Helper:
keywords = {
'and': 'BOOLEAN',
'as': 'with',
'assert': ('ref/assert', ''),
'break': ('ref/break', 'while for'),
'class': ('ref/class', 'CLASSES SPECIALMETHODS'),
'continue': ('ref/continue', 'while for'),
'def': ('ref/function', ''),
'del': ('ref/del', 'BASICMETHODS'),
'elif': 'if',
'else': ('ref/if', 'while for'),
'except': 'try',
'exec': ('ref/exec', ''),
'finally': 'try',
'for': ('ref/for', 'break continue while'),
'from': 'import',
'global': ('ref/global', 'NAMESPACES'),
'if': ('ref/if', 'TRUTHVALUE'),
'import': ('ref/import', 'MODULES'),
'in': ('ref/comparisons', 'SEQUENCEMETHODS2'),
'is': 'COMPARISON',
'lambda': ('ref/lambdas', 'FUNCTIONS'),
'not': 'BOOLEAN',
'or': 'BOOLEAN',
'pass': ('ref/pass', ''),
'print': ('ref/print', ''),
'raise': ('ref/raise', 'EXCEPTIONS'),
'return': ('ref/return', 'FUNCTIONS'),
'try': ('ref/try', 'EXCEPTIONS'),
'while': ('ref/while', 'break continue if TRUTHVALUE'),
'with': ('ref/with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
'yield': ('ref/yield', ''),
}
topics = {
'TYPES': ('ref/types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'),
'STRINGS': ('ref/strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'),
'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'),
'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'),
'UNICODE': ('ref/strings', 'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'),
'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'),
'INTEGER': ('ref/integers', 'int range'),
'FLOAT': ('ref/floating', 'float math'),
'COMPLEX': ('ref/imaginary', 'complex cmath'),
'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
'MAPPINGS': 'DICTIONARIES',
'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'),
'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
'CODEOBJECTS': ('lib/bltin-code-objects', 'compile FUNCTIONS TYPES'),
'TYPEOBJECTS': ('lib/bltin-type-objects', 'types TYPES'),
'FRAMEOBJECTS': 'TYPES',
'TRACEBACKS': 'TYPES',
'NONE': ('lib/bltin-null-object', ''),
'ELLIPSIS': ('lib/bltin-ellipsis-object', 'SLICINGS'),
'FILES': ('lib/bltin-file-objects', ''),
'SPECIALATTRIBUTES': ('lib/specialattrs', ''),
'CLASSES': ('ref/types', 'class SPECIALMETHODS PRIVATENAMES'),
'MODULES': ('lib/typesmodules', 'import'),
'PACKAGES': 'import',
'EXPRESSIONS': ('ref/summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'),
'OPERATORS': 'EXPRESSIONS',
'PRECEDENCE': 'EXPRESSIONS',
'OBJECTS': ('ref/objects', 'TYPES'),
'SPECIALMETHODS': ('ref/specialnames', 'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
'BASICMETHODS': ('ref/customization', 'cmp hash repr str SPECIALMETHODS'),
'ATTRIBUTEMETHODS': ('ref/attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
'CALLABLEMETHODS': ('ref/callable-types', 'CALLS SPECIALMETHODS'),
'SEQUENCEMETHODS1': ('ref/sequence-types', 'SEQUENCES SEQUENCEMETHODS2 SPECIALMETHODS'),
'SEQUENCEMETHODS2': ('ref/sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 SPECIALMETHODS'),
'MAPPINGMETHODS': ('ref/sequence-types', 'MAPPINGS SPECIALMETHODS'),
'NUMBERMETHODS': ('ref/numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'),
'EXECUTION': ('ref/execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
'NAMESPACES': ('ref/naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
'DYNAMICFEATURES': ('ref/dynamic-features', ''),
'SCOPING': 'NAMESPACES',
'FRAMES': 'NAMESPACES',
'EXCEPTIONS': ('ref/exceptions', 'try except finally raise'),
'COERCIONS': ('ref/coercion-rules','CONVERSIONS'),
'CONVERSIONS': ('ref/conversions', 'COERCIONS'),
'IDENTIFIERS': ('ref/identifiers', 'keywords SPECIALIDENTIFIERS'),
'SPECIALIDENTIFIERS': ('ref/id-classes', ''),
'PRIVATENAMES': ('ref/atom-identifiers', ''),
'LITERALS': ('ref/atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
'TUPLES': 'SEQUENCES',
'TUPLELITERALS': ('ref/exprlists', 'TUPLES LITERALS'),
'LISTS': ('lib/typesseq-mutable', 'LISTLITERALS'),
'LISTLITERALS': ('ref/lists', 'LISTS LITERALS'),
'DICTIONARIES': ('lib/typesmapping', 'DICTIONARYLITERALS'),
'DICTIONARYLITERALS': ('ref/dict', 'DICTIONARIES LITERALS'),
'BACKQUOTES': ('ref/string-conversions', 'repr str STRINGS LITERALS'),
'ATTRIBUTES': ('ref/attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
'SUBSCRIPTS': ('ref/subscriptions', 'SEQUENCEMETHODS1'),
'SLICINGS': ('ref/slicings', 'SEQUENCEMETHODS2'),
'CALLS': ('ref/calls', 'EXPRESSIONS'),
'POWER': ('ref/power', 'EXPRESSIONS'),
'UNARY': ('ref/unary', 'EXPRESSIONS'),
'BINARY': ('ref/binary', 'EXPRESSIONS'),
'SHIFTING': ('ref/shifting', 'EXPRESSIONS'),
'BITWISE': ('ref/bitwise', 'EXPRESSIONS'),
'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'),
'BOOLEAN': ('ref/Booleans', 'EXPRESSIONS TRUTHVALUE'),
'ASSERTION': 'assert',
'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'),
'AUGMENTEDASSIGNMENT': ('ref/augassign', 'NUMBERMETHODS'),
'DELETION': 'del',
'PRINTING': 'print',
'RETURNING': 'return',
'IMPORTING': 'import',
'CONDITIONAL': 'if',
'LOOPING': ('ref/compound', 'for while break continue'),
'TRUTHVALUE': ('lib/truth', 'if while and or not BASICMETHODS'),
'DEBUGGING': ('lib/module-pdb', 'pdb'),
'CONTEXTMANAGERS': ('ref/context-managers', 'with'),
}
def __init__(self, input, output):
self.input = input
self.output = output
self.docdir = None
if sys.executable is None:
execdir = os.getcwd()
else:
execdir = os.path.dirname(sys.executable)
homedir = os.environ.get('PYTHONHOME')
for dir in [os.environ.get('PYTHONDOCS'),
homedir and os.path.join(homedir, 'doc'),
os.path.join(execdir, 'doc'),
'/usr/doc/python-docs-' + split(sys.version)[0],
'/usr/doc/python-' + split(sys.version)[0],
'/usr/doc/python-docs-' + sys.version[:3],
'/usr/doc/python-' + sys.version[:3],
os.path.join(sys.prefix, 'Resources/English.lproj/Documentation')]:
if dir and os.path.isdir(os.path.join(dir, 'lib')):
self.docdir = dir
def __repr__(self):
if inspect.stack()[1][3] == '?':
self()
return ''
return '<pydoc.Helper instance>'
def __call__(self, request=None):
if request is not None:
self.help(request)
else:
self.intro()
self.interact()
self.output.write('''
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
''')
def interact(self):
self.output.write('\n')
while True:
try:
request = self.getline('help> ')
if not request: break
except (KeyboardInterrupt, EOFError):
break
request = strip(replace(request, '"', '', "'", ''))
if lower(request) in ('q', 'quit'): break
self.help(request)
def getline(self, prompt):
"""Read one line, using raw_input when available."""
if self.input is sys.stdin:
return raw_input(prompt)
else:
self.output.write(prompt)
self.output.flush()
return self.input.readline()
def help(self, request):
if type(request) is type(''):
if request == 'help': self.intro()
elif request == 'keywords': self.listkeywords()
elif request == 'topics': self.listtopics()
elif request == 'modules': self.listmodules()
elif request[:8] == 'modules ':
self.listmodules(split(request)[1])
elif request in self.keywords: self.showtopic(request)
elif request in self.topics: self.showtopic(request)
elif request: doc(request, 'Help on %s:')
elif isinstance(request, Helper): self()
else: doc(request, 'Help on %s:')
self.output.write('\n')
def intro(self):
self.output.write('''
Welcome to Python %s! This is the online help utility.
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
''' % sys.version[:3])
def list(self, items, columns=4, width=80):
items = items[:]
items.sort()
colw = width / columns
rows = (len(items) + columns - 1) / columns
for row in range(rows):
for col in range(columns):
i = col * rows + row
if i < len(items):
self.output.write(items[i])
if col < columns - 1:
self.output.write(' ' + ' ' * (colw-1 - len(items[i])))
self.output.write('\n')
def listkeywords(self):
self.output.write('''
Here is a list of the Python keywords. Enter any keyword to get more help.
''')
self.list(self.keywords.keys())
def listtopics(self):
self.output.write('''
Here is a list of available topics. Enter any topic name to get more help.
''')
self.list(self.topics.keys())
def showtopic(self, topic):
if not self.docdir:
self.output.write('''
Sorry, topic and keyword documentation is not available because the Python
HTML documentation files could not be found. If you have installed them,
please set the environment variable PYTHONDOCS to indicate their location.
On the Microsoft Windows operating system, the files can be built by
running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory.
''')
return
target = self.topics.get(topic, self.keywords.get(topic))
if not target:
self.output.write('no documentation found for %s\n' % repr(topic))
return
if type(target) is type(''):
return self.showtopic(target)
filename, xrefs = target
filename = self.docdir + '/' + filename + '.html'
try:
file = open(filename)
except:
self.output.write('could not read docs from %s\n' % filename)
return
divpat = re.compile('<div[^>]*navigat.*?</div.*?>', re.I | re.S)
addrpat = re.compile('<address.*?>.*?</address.*?>', re.I | re.S)
document = re.sub(addrpat, '', re.sub(divpat, '', file.read()))
file.close()
import htmllib, formatter, StringIO
buffer = StringIO.StringIO()
parser = htmllib.HTMLParser(
formatter.AbstractFormatter(formatter.DumbWriter(buffer)))
parser.start_table = parser.do_p
parser.end_table = lambda parser=parser: parser.do_p({})
parser.start_tr = parser.do_br
parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t')
parser.feed(document)
buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n ')
pager(' ' + strip(buffer) + '\n')
if xrefs:
buffer = StringIO.StringIO()
formatter.DumbWriter(buffer).send_flowing_data(
'Related help topics: ' + join(split(xrefs), ', ') + '\n')
self.output.write('\n%s\n' % buffer.getvalue())
def listmodules(self, key=''):
if key:
self.output.write('''
Here is a list of matching modules. Enter any module name to get more help.
''')
apropos(key)
else:
self.output.write('''
Please wait a moment while I gather a list of all available modules...
''')
modules = {}
def callback(path, modname, desc, modules=modules):
if modname and modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
if find(modname, '.') < 0:
modules[modname] = 1
ModuleScanner().run(callback)
self.list(modules.keys())
self.output.write('''
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".
''')
help = Helper(sys.stdin, sys.stdout)
class Scanner:
"""A generic tree iterator."""
def __init__(self, roots, children, descendp):
self.roots = roots[:]
self.state = []
self.children = children
self.descendp = descendp
def next(self):
if not self.state:
if not self.roots:
return None
root = self.roots.pop(0)
self.state = [(root, self.children(root))]
node, children = self.state[-1]
if not children:
self.state.pop()
return self.next()
child = children.pop(0)
if self.descendp(child):
self.state.append((child, self.children(child)))
return child
class ModuleScanner:
"""An interruptible scanner that searches module synopses."""
def run(self, callback, key=None, completer=None):
if key: key = lower(key)
self.quit = False
seen = {}
for modname in sys.builtin_module_names:
if modname != '__main__':
seen[modname] = 1
if key is None:
callback(None, modname, '')
else:
desc = split(__import__(modname).__doc__ or '', '\n')[0]
if find(lower(modname + ' - ' + desc), key) >= 0:
callback(None, modname, desc)
for importer, modname, ispkg in pkgutil.walk_packages():
if self.quit:
break
if key is None:
callback(None, modname, '')
else:
loader = importer.find_module(modname)
if hasattr(loader,'get_source'):
import StringIO
desc = source_synopsis(
StringIO.StringIO(loader.get_source(modname))
) or ''
if hasattr(loader,'get_filename'):
path = loader.get_filename(modname)
else:
path = None
else:
module = loader.load_module(modname)
desc = (module.__doc__ or '').splitlines()[0]
path = getattr(module,'__file__',None)
if find(lower(modname + ' - ' + desc), key) >= 0:
callback(path, modname, desc)
if completer:
completer()
def apropos(key):
"""Print all the one-line module summaries that contain a substring."""
def callback(path, modname, desc):
if modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
print modname, desc and '- ' + desc
try: import warnings
except ImportError: pass
else: warnings.filterwarnings('ignore') # ignore problems during import
ModuleScanner().run(callback, key)
# --------------------------------------------------- web browser interface
def serve(port, callback=None, completer=None):
import BaseHTTPServer, mimetools, select
# Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
class Message(mimetools.Message):
def __init__(self, fp, seekable=1):
Message = self.__class__
Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
self.encodingheader = self.getheader('content-transfer-encoding')
self.typeheader = self.getheader('content-type')
self.parsetype()
self.parseplist()
class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def send_document(self, title, contents):
try:
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(html.page(title, contents))
except IOError: pass
def do_GET(self):
path = self.path
if path[-5:] == '.html': path = path[:-5]
if path[:1] == '/': path = path[1:]
if path and path != '.':
try:
obj = locate(path, forceload=1)
except ErrorDuringImport, value:
self.send_document(path, html.escape(str(value)))
return
if obj:
self.send_document(describe(obj), html.document(obj, path))
else:
self.send_document(path,
'no Python documentation found for %s' % repr(path))
else:
heading = html.heading(
'<big><big><strong>Python: Index of Modules</strong></big></big>',
'#ffffff', '#7799ee')
def bltinlink(name):
return '<a href="%s.html">%s</a>' % (name, name)
names = filter(lambda x: x != '__main__',
sys.builtin_module_names)
contents = html.multicolumn(names, bltinlink)
indices = ['<p>' + html.bigsection(
'Built-in Modules', '#ffffff', '#ee77aa', contents)]
seen = {}
for dir in sys.path:
indices.append(html.index(dir, seen))
contents = heading + join(indices) + '''<p align=right>
<font color="#909090" face="helvetica, arial"><strong>
pydoc</strong> by Ka-Ping Yee <ping@lfw.org></font>'''
self.send_document('Index of Modules', contents)
def log_message(self, *args): pass
class DocServer(BaseHTTPServer.HTTPServer):
def __init__(self, port, callback):
host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
self.address = ('', port)
self.url = 'http://%s:%d/' % (host, port)
self.callback = callback
self.base.__init__(self, self.address, self.handler)
def serve_until_quit(self):
import sys
if sys.platform.startswith('java'):
from select import cpython_compatible_select as select
else:
from select import select
self.quit = False
while not self.quit:
rd, wr, ex = select([self.socket], [], [], 1)
if rd: self.handle_request()
def server_activate(self):
self.base.server_activate(self)
if self.callback: self.callback(self)
DocServer.base = BaseHTTPServer.HTTPServer
DocServer.handler = DocHandler
DocHandler.MessageClass = Message
try:
try:
DocServer(port, callback).serve_until_quit()
except (KeyboardInterrupt, select.error):
pass
finally:
if completer: completer()
# ----------------------------------------------------- graphical interface
def gui():
"""Graphical interface (starts web server and pops up a control window)."""
class GUI:
def __init__(self, window, port=7464):
self.window = window
self.server = None
self.scanner = None
import Tkinter
self.server_frm = Tkinter.Frame(window)
self.title_lbl = Tkinter.Label(self.server_frm,
text='Starting server...\n ')
self.open_btn = Tkinter.Button(self.server_frm,
text='open browser', command=self.open, state='disabled')
self.quit_btn = Tkinter.Button(self.server_frm,
text='quit serving', command=self.quit, state='disabled')
self.search_frm = Tkinter.Frame(window)
self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
self.search_ent = Tkinter.Entry(self.search_frm)
self.search_ent.bind('<Return>', self.search)
self.stop_btn = Tkinter.Button(self.search_frm,
text='stop', pady=0, command=self.stop, state='disabled')
if sys.platform == 'win32':
# Trying to hide and show this button crashes under Windows.
self.stop_btn.pack(side='right')
self.window.title('pydoc')
self.window.protocol('WM_DELETE_WINDOW', self.quit)
self.title_lbl.pack(side='top', fill='x')
self.open_btn.pack(side='left', fill='x', expand=1)
self.quit_btn.pack(side='right', fill='x', expand=1)
self.server_frm.pack(side='top', fill='x')
self.search_lbl.pack(side='left')
self.search_ent.pack(side='right', fill='x', expand=1)
self.search_frm.pack(side='top', fill='x')
self.search_ent.focus_set()
font = ('helvetica', sys.platform == 'win32' and 8 or 10)
self.result_lst = Tkinter.Listbox(window, font=font, height=6)
self.result_lst.bind('<Button-1>', self.select)
self.result_lst.bind('<Double-Button-1>', self.goto)
self.result_scr = Tkinter.Scrollbar(window,
orient='vertical', command=self.result_lst.yview)
self.result_lst.config(yscrollcommand=self.result_scr.set)
self.result_frm = Tkinter.Frame(window)
self.goto_btn = Tkinter.Button(self.result_frm,
text='go to selected', command=self.goto)
self.hide_btn = Tkinter.Button(self.result_frm,
text='hide results', command=self.hide)
self.goto_btn.pack(side='left', fill='x', expand=1)
self.hide_btn.pack(side='right', fill='x', expand=1)
self.window.update()
self.minwidth = self.window.winfo_width()
self.minheight = self.window.winfo_height()
self.bigminheight = (self.server_frm.winfo_reqheight() +
self.search_frm.winfo_reqheight() +
self.result_lst.winfo_reqheight() +
self.result_frm.winfo_reqheight())
self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
self.expanded = 0
self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
self.window.wm_minsize(self.minwidth, self.minheight)
self.window.tk.willdispatch()
import threading
threading.Thread(
target=serve, args=(port, self.ready, self.quit)).start()
def ready(self, server):
self.server = server
self.title_lbl.config(
text='Python documentation server at\n' + server.url)
self.open_btn.config(state='normal')
self.quit_btn.config(state='normal')
def open(self, event=None, url=None):
url = url or self.server.url
try:
import webbrowser
webbrowser.open(url)
except ImportError: # pre-webbrowser.py compatibility
if sys.platform == 'win32':
os.system('start "%s"' % url)
elif sys.platform == 'mac':
try: import ic
except ImportError: pass
else: ic.launchurl(url)
else:
rc = os.system('netscape -remote "openURL(%s)" &' % url)
if rc: os.system('netscape "%s" &' % url)
def quit(self, event=None):
if self.server:
self.server.quit = 1
self.window.quit()
def search(self, event=None):
key = self.search_ent.get()
self.stop_btn.pack(side='right')
self.stop_btn.config(state='normal')
self.search_lbl.config(text='Searching for "%s"...' % key)
self.search_ent.forget()
self.search_lbl.pack(side='left')
self.result_lst.delete(0, 'end')
self.goto_btn.config(state='disabled')
self.expand()
import threading
if self.scanner:
self.scanner.quit = 1
self.scanner = ModuleScanner()
threading.Thread(target=self.scanner.run,
args=(self.update, key, self.done)).start()
def update(self, path, modname, desc):
if modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
self.result_lst.insert('end',
modname + ' - ' + (desc or '(no description)'))
def stop(self, event=None):
if self.scanner:
self.scanner.quit = 1
self.scanner = None
def done(self):
self.scanner = None
self.search_lbl.config(text='Search for')
self.search_lbl.pack(side='left')
self.search_ent.pack(side='right', fill='x', expand=1)
if sys.platform != 'win32': self.stop_btn.forget()
self.stop_btn.config(state='disabled')
def select(self, event=None):
self.goto_btn.config(state='normal')
def goto(self, event=None):
selection = self.result_lst.curselection()
if selection:
modname = split(self.result_lst.get(selection[0]))[0]
self.open(url=self.server.url + modname + '.html')
def collapse(self):
if not self.expanded: return
self.result_frm.forget()
self.result_scr.forget()
self.result_lst.forget()
self.bigwidth = self.window.winfo_width()
self.bigheight = self.window.winfo_height()
self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
self.window.wm_minsize(self.minwidth, self.minheight)
self.expanded = 0
def expand(self):
if self.expanded: return
self.result_frm.pack(side='bottom', fill='x')
self.result_scr.pack(side='right', fill='y')
self.result_lst.pack(side='top', fill='both', expand=1)
self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
self.window.wm_minsize(self.minwidth, self.bigminheight)
self.expanded = 1
def hide(self, event=None):
self.stop()
self.collapse()
import Tkinter
try:
root = Tkinter.Tk()
# Tk will crash if pythonw.exe has an XP .manifest
# file and the root has is not destroyed explicitly.
# If the problem is ever fixed in Tk, the explicit
# destroy can go.
try:
gui = GUI(root)
root.mainloop()
finally:
root.destroy()
except KeyboardInterrupt:
pass
# -------------------------------------------------- command-line interface
def ispath(x):
return isinstance(x, str) and find(x, os.sep) >= 0
def cli():
"""Command-line interface (looks at sys.argv to decide what to do)."""
import getopt
class BadUsage: pass
# Scripts don't get the current directory in their path by default.
scriptdir = os.path.dirname(sys.argv[0])
if scriptdir in sys.path:
sys.path.remove(scriptdir)
sys.path.insert(0, '.')
try:
opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
writing = 0
for opt, val in opts:
if opt == '-g':
gui()
return
if opt == '-k':
apropos(val)
return
if opt == '-p':
try:
port = int(val)
except ValueError:
raise BadUsage
def ready(server):
print 'pydoc server ready at %s' % server.url
def stopped():
print 'pydoc server stopped'
serve(port, ready, stopped)
return
if opt == '-w':
writing = 1
if not args: raise BadUsage
for arg in args:
if ispath(arg) and not os.path.exists(arg):
print 'file %r does not exist' % arg
break
try:
if ispath(arg) and os.path.isfile(arg):
arg = importfile(arg)
if writing:
if ispath(arg) and os.path.isdir(arg):
writedocs(arg)
else:
writedoc(arg)
else:
help.help(arg)
except ErrorDuringImport, value:
print value
except (getopt.error, BadUsage):
cmd = os.path.basename(sys.argv[0])
print """pydoc - the Python documentation tool
%s <name> ...
Show text documentation on something. <name> may be the name of a
Python keyword, topic, function, module, or package, or a dotted
reference to a class or function within a module or module in a
package. If <name> contains a '%s', it is used as the path to a
Python source file to document. If name is 'keywords', 'topics',
or 'modules', a listing of these things is displayed.
%s -k <keyword>
Search for a keyword in the synopsis lines of all available modules.
%s -p <port>
Start an HTTP server on the given port on the local machine.
%s -g
Pop up a graphical interface for finding and serving documentation.
%s -w <name> ...
Write out the HTML documentation for a module to a file in the current
directory. If <name> contains a '%s', it is treated as a filename; if
it names a directory, documentation is written for all the contents.
""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
if __name__ == '__main__': cli()
| apache-2.0 |
hammerhorn/hammerhorn-jive | addup/addup.py | 1 | 1351 | #!/usr/bin/env python
"""
Sum of a list
Find the sum of a user-input list of numbers. It would be good to time
each subroutine to see which is the fastest.
"""
import decimal
import math
import sys
try:
import numpy
NUMPY_AVAILABLE = True
except ImportError:
NUMPY_AVAILABLE = False
def numpy_method(nlist):
"""
Find sum using the numpy module.
"""
if NUMPY_AVAILABLE is not True:
total = 'Not available.'
else:
total = numpy.array(nlist, float).sum()
print("numpy: {}".format(total)) # pylint: disable=C0325
def math_method(nlist):
"""
Calculate using the math module from the standard library.
"""
total = math.fsum(nlist)
print('math.fsum(): {}'.format(total)) # pylint: disable=C0325
def native_method(nlist):
"""
Calculate using the native sum() function.
"""
total = sum(nlist)
print('sum(): {}'.format(total)) # pylint: disable=C0325
def main():
"""
Get a list a numbers from the user, and sum them up three ways.
"""
input_str = sys.stdin.read().strip()
str_list = input_str.split()
num_list = [decimal.Decimal(i) for i in str_list]
print('') # pylint: disable=C0325
# Find the sum.
numpy_method(num_list)
math_method(num_list)
native_method(num_list)
if __name__ == '__main__':
main()
| gpl-2.0 |
lzw120/django | django/contrib/sessions/tests.py | 10 | 15989 | from datetime import datetime, timedelta
import shutil
import string
import tempfile
import warnings
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DatabaseSession
from django.contrib.sessions.backends.cache import SessionStore as CacheSession
from django.contrib.sessions.backends.cached_db import SessionStore as CacheDBSession
from django.contrib.sessions.backends.file import SessionStore as FileSession
from django.contrib.sessions.backends.signed_cookies import SessionStore as CookieSession
from django.contrib.sessions.models import Session
from django.contrib.sessions.middleware import SessionMiddleware
from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
from django.http import HttpResponse
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
from django.utils import timezone
from django.utils import unittest
class SessionTestsMixin(object):
# This does not inherit from TestCase to avoid any tests being run with this
# class, which wouldn't work, and to allow different TestCase subclasses to
# be used.
backend = None # subclasses must specify
def setUp(self):
self.session = self.backend()
def tearDown(self):
# NB: be careful to delete any sessions created; stale sessions fill up
# the /tmp (with some backends) and eventually overwhelm it after lots
# of runs (think buildbots)
self.session.delete()
def test_new_session(self):
self.assertFalse(self.session.modified)
self.assertFalse(self.session.accessed)
def test_get_empty(self):
self.assertEqual(self.session.get('cat'), None)
def test_store(self):
self.session['cat'] = "dog"
self.assertTrue(self.session.modified)
self.assertEqual(self.session.pop('cat'), 'dog')
def test_pop(self):
self.session['some key'] = 'exists'
# Need to reset these to pretend we haven't accessed it:
self.accessed = False
self.modified = False
self.assertEqual(self.session.pop('some key'), 'exists')
self.assertTrue(self.session.accessed)
self.assertTrue(self.session.modified)
self.assertEqual(self.session.get('some key'), None)
def test_pop_default(self):
self.assertEqual(self.session.pop('some key', 'does not exist'),
'does not exist')
self.assertTrue(self.session.accessed)
self.assertFalse(self.session.modified)
def test_setdefault(self):
self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar')
self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar')
self.assertTrue(self.session.accessed)
self.assertTrue(self.session.modified)
def test_update(self):
self.session.update({'update key': 1})
self.assertTrue(self.session.accessed)
self.assertTrue(self.session.modified)
self.assertEqual(self.session.get('update key', None), 1)
def test_has_key(self):
self.session['some key'] = 1
self.session.modified = False
self.session.accessed = False
self.assertTrue('some key' in self.session)
self.assertTrue(self.session.accessed)
self.assertFalse(self.session.modified)
def test_values(self):
self.assertEqual(self.session.values(), [])
self.assertTrue(self.session.accessed)
self.session['some key'] = 1
self.assertEqual(self.session.values(), [1])
def test_iterkeys(self):
self.session['x'] = 1
self.session.modified = False
self.session.accessed = False
i = self.session.iterkeys()
self.assertTrue(hasattr(i, '__iter__'))
self.assertTrue(self.session.accessed)
self.assertFalse(self.session.modified)
self.assertEqual(list(i), ['x'])
def test_itervalues(self):
self.session['x'] = 1
self.session.modified = False
self.session.accessed = False
i = self.session.itervalues()
self.assertTrue(hasattr(i, '__iter__'))
self.assertTrue(self.session.accessed)
self.assertFalse(self.session.modified)
self.assertEqual(list(i), [1])
def test_iteritems(self):
self.session['x'] = 1
self.session.modified = False
self.session.accessed = False
i = self.session.iteritems()
self.assertTrue(hasattr(i, '__iter__'))
self.assertTrue(self.session.accessed)
self.assertFalse(self.session.modified)
self.assertEqual(list(i), [('x', 1)])
def test_clear(self):
self.session['x'] = 1
self.session.modified = False
self.session.accessed = False
self.assertEqual(self.session.items(), [('x', 1)])
self.session.clear()
self.assertEqual(self.session.items(), [])
self.assertTrue(self.session.accessed)
self.assertTrue(self.session.modified)
def test_save(self):
self.session.save()
self.assertTrue(self.session.exists(self.session.session_key))
def test_delete(self):
self.session.save()
self.session.delete(self.session.session_key)
self.assertFalse(self.session.exists(self.session.session_key))
def test_flush(self):
self.session['foo'] = 'bar'
self.session.save()
prev_key = self.session.session_key
self.session.flush()
self.assertFalse(self.session.exists(prev_key))
self.assertNotEqual(self.session.session_key, prev_key)
self.assertTrue(self.session.modified)
self.assertTrue(self.session.accessed)
def test_cycle(self):
self.session['a'], self.session['b'] = 'c', 'd'
self.session.save()
prev_key = self.session.session_key
prev_data = self.session.items()
self.session.cycle_key()
self.assertNotEqual(self.session.session_key, prev_key)
self.assertEqual(self.session.items(), prev_data)
def test_invalid_key(self):
# Submitting an invalid session key (either by guessing, or if the db has
# removed the key) results in a new key being generated.
try:
session = self.backend('1')
try:
session.save()
except AttributeError:
self.fail("The session object did not save properly. Middleware may be saving cache items without namespaces.")
self.assertNotEqual(session.session_key, '1')
self.assertEqual(session.get('cat'), None)
session.delete()
finally:
# Some backends leave a stale cache entry for the invalid
# session key; make sure that entry is manually deleted
session.delete('1')
def test_session_key_is_read_only(self):
def set_session_key(session):
session.session_key = session._get_new_session_key()
self.assertRaises(AttributeError, set_session_key, self.session)
# Custom session expiry
def test_default_expiry(self):
# A normal session has a max age equal to settings
self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)
# So does a custom session with an idle expiration time of 0 (but it'll
# expire at browser close)
self.session.set_expiry(0)
self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)
def test_custom_expiry_seconds(self):
# Using seconds
self.session.set_expiry(10)
delta = self.session.get_expiry_date() - timezone.now()
self.assertTrue(delta.seconds in (9, 10))
age = self.session.get_expiry_age()
self.assertTrue(age in (9, 10))
def test_custom_expiry_timedelta(self):
# Using timedelta
self.session.set_expiry(timedelta(seconds=10))
delta = self.session.get_expiry_date() - timezone.now()
self.assertTrue(delta.seconds in (9, 10))
age = self.session.get_expiry_age()
self.assertTrue(age in (9, 10))
def test_custom_expiry_datetime(self):
# Using fixed datetime
self.session.set_expiry(timezone.now() + timedelta(seconds=10))
delta = self.session.get_expiry_date() - timezone.now()
self.assertTrue(delta.seconds in (9, 10))
age = self.session.get_expiry_age()
self.assertTrue(age in (9, 10))
def test_custom_expiry_reset(self):
self.session.set_expiry(None)
self.session.set_expiry(10)
self.session.set_expiry(None)
self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)
def test_get_expire_at_browser_close(self):
# Tests get_expire_at_browser_close with different settings and different
# set_expiry calls
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False):
self.session.set_expiry(10)
self.assertFalse(self.session.get_expire_at_browser_close())
self.session.set_expiry(0)
self.assertTrue(self.session.get_expire_at_browser_close())
self.session.set_expiry(None)
self.assertFalse(self.session.get_expire_at_browser_close())
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True):
self.session.set_expiry(10)
self.assertFalse(self.session.get_expire_at_browser_close())
self.session.set_expiry(0)
self.assertTrue(self.session.get_expire_at_browser_close())
self.session.set_expiry(None)
self.assertTrue(self.session.get_expire_at_browser_close())
def test_decode(self):
# Ensure we can decode what we encode
data = {'a test key': 'a test value'}
encoded = self.session.encode(data)
self.assertEqual(self.session.decode(encoded), data)
class DatabaseSessionTests(SessionTestsMixin, TestCase):
backend = DatabaseSession
def test_session_get_decoded(self):
"""
Test we can use Session.get_decoded to retrieve data stored
in normal way
"""
self.session['x'] = 1
self.session.save()
s = Session.objects.get(session_key=self.session.session_key)
self.assertEqual(s.get_decoded(), {'x': 1})
def test_sessionmanager_save(self):
"""
Test SessionManager.save method
"""
# Create a session
self.session['y'] = 1
self.session.save()
s = Session.objects.get(session_key=self.session.session_key)
# Change it
Session.objects.save(s.session_key, {'y': 2}, s.expire_date)
# Clear cache, so that it will be retrieved from DB
del self.session._session_cache
self.assertEqual(self.session['y'], 2)
@override_settings(USE_TZ=True)
class DatabaseSessionWithTimeZoneTests(DatabaseSessionTests):
pass
class CacheDBSessionTests(SessionTestsMixin, TestCase):
backend = CacheDBSession
def test_exists_searches_cache_first(self):
self.session.save()
with self.assertNumQueries(0):
self.assertTrue(self.session.exists(self.session.session_key))
def test_load_overlong_key(self):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
self.session._session_key = (string.ascii_letters + string.digits) * 20
self.assertEqual(self.session.load(), {})
self.assertEqual(len(w), 1)
@override_settings(USE_TZ=True)
class CacheDBSessionWithTimeZoneTests(CacheDBSessionTests):
pass
# Don't need DB flushing for these tests, so can use unittest.TestCase as base class
class FileSessionTests(SessionTestsMixin, unittest.TestCase):
backend = FileSession
def setUp(self):
super(FileSessionTests, self).setUp()
# Do file session tests in an isolated directory, and kill it after we're done.
self.original_session_file_path = settings.SESSION_FILE_PATH
self.temp_session_store = settings.SESSION_FILE_PATH = tempfile.mkdtemp()
def tearDown(self):
settings.SESSION_FILE_PATH = self.original_session_file_path
shutil.rmtree(self.temp_session_store)
super(FileSessionTests, self).tearDown()
@override_settings(
SESSION_FILE_PATH="/if/this/directory/exists/you/have/a/weird/computer")
def test_configuration_check(self):
# Make sure the file backend checks for a good storage dir
self.assertRaises(ImproperlyConfigured, self.backend)
def test_invalid_key_backslash(self):
# Ensure we don't allow directory-traversal
self.assertRaises(SuspiciousOperation,
self.backend("a\\b\\c").load)
def test_invalid_key_forwardslash(self):
# Ensure we don't allow directory-traversal
self.assertRaises(SuspiciousOperation,
self.backend("a/b/c").load)
class CacheSessionTests(SessionTestsMixin, unittest.TestCase):
backend = CacheSession
def test_load_overlong_key(self):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
self.session._session_key = (string.ascii_letters + string.digits) * 20
self.assertEqual(self.session.load(), {})
self.assertEqual(len(w), 1)
class SessionMiddlewareTests(unittest.TestCase):
@override_settings(SESSION_COOKIE_SECURE=True)
def test_secure_session_cookie(self):
request = RequestFactory().get('/')
response = HttpResponse('Session test')
middleware = SessionMiddleware()
# Simulate a request the modifies the session
middleware.process_request(request)
request.session['hello'] = 'world'
# Handle the response through the middleware
response = middleware.process_response(request, response)
self.assertTrue(
response.cookies[settings.SESSION_COOKIE_NAME]['secure'])
@override_settings(SESSION_COOKIE_HTTPONLY=True)
def test_httponly_session_cookie(self):
request = RequestFactory().get('/')
response = HttpResponse('Session test')
middleware = SessionMiddleware()
# Simulate a request the modifies the session
middleware.process_request(request)
request.session['hello'] = 'world'
# Handle the response through the middleware
response = middleware.process_response(request, response)
self.assertTrue(
response.cookies[settings.SESSION_COOKIE_NAME]['httponly'])
self.assertIn('httponly',
str(response.cookies[settings.SESSION_COOKIE_NAME]))
@override_settings(SESSION_COOKIE_HTTPONLY=False)
def test_no_httponly_session_cookie(self):
request = RequestFactory().get('/')
response = HttpResponse('Session test')
middleware = SessionMiddleware()
# Simulate a request the modifies the session
middleware.process_request(request)
request.session['hello'] = 'world'
# Handle the response through the middleware
response = middleware.process_response(request, response)
self.assertFalse(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'])
self.assertNotIn('httponly',
str(response.cookies[settings.SESSION_COOKIE_NAME]))
class CookieSessionTests(SessionTestsMixin, TestCase):
backend = CookieSession
def test_save(self):
"""
This test tested exists() in the other session backends, but that
doesn't make sense for us.
"""
pass
def test_cycle(self):
"""
This test tested cycle_key() which would create a new session
key for the same session data. But we can't invalidate previously
signed cookies (other than letting them expire naturally) so
testing for this behavior is meaningless.
"""
pass
| bsd-3-clause |
sean-/ansible | test/units/mock/loader.py | 50 | 2876 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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 Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.errors import AnsibleParserError
from ansible.parsing import DataLoader
class DictDataLoader(DataLoader):
def __init__(self, file_mapping=dict()):
assert type(file_mapping) == dict
self._file_mapping = file_mapping
self._build_known_directories()
super(DictDataLoader, self).__init__()
def load_from_file(self, path):
if path in self._file_mapping:
return self.load(self._file_mapping[path], path)
return None
def _get_file_contents(self, path):
if path in self._file_mapping:
return (self._file_mapping[path], False)
else:
raise AnsibleParserError("file not found: %s" % path)
def path_exists(self, path):
return path in self._file_mapping or path in self._known_directories
def is_file(self, path):
return path in self._file_mapping
def is_directory(self, path):
return path in self._known_directories
def list_directory(self, path):
return [x for x in self._known_directories]
def _add_known_directory(self, directory):
if directory not in self._known_directories:
self._known_directories.append(directory)
def _build_known_directories(self):
self._known_directories = []
for path in self._file_mapping:
dirname = os.path.dirname(path)
while dirname not in ('/', ''):
self._add_known_directory(dirname)
dirname = os.path.dirname(dirname)
def push(self, path, content):
rebuild_dirs = False
if path not in self._file_mapping:
rebuild_dirs = True
self._file_mapping[path] = content
if rebuild_dirs:
self._build_known_directories()
def pop(self, path):
if path in self._file_mapping:
del self._file_mapping[path]
self._build_known_directories()
def clear(self):
self._file_mapping = dict()
self._known_directories = []
| gpl-3.0 |
hargup/sympy | sympy/printing/tests/test_lambdarepr.py | 38 | 5058 | from sympy import symbols, sin, Matrix, Interval, Piecewise, Sum, lambdify
from sympy.utilities.pytest import raises
from sympy.printing.lambdarepr import lambdarepr
x, y, z = symbols("x,y,z")
i, a, b = symbols("i,a,b")
j, c, d = symbols("j,c,d")
def test_basic():
assert lambdarepr(x*y) == "x*y"
assert lambdarepr(x + y) in ["y + x", "x + y"]
assert lambdarepr(x**y) == "x**y"
def test_matrix():
A = Matrix([[x, y], [y*x, z**2]])
assert lambdarepr(A) == "MutableDenseMatrix([[x, y], [x*y, z**2]])"
# Test printing a Matrix that has an element that is printed differently
# with the LambdaPrinter than in the StrPrinter.
p = Piecewise((x, True), evaluate=False)
A = Matrix([p])
assert lambdarepr(A) == "MutableDenseMatrix([[((x) if (True) else None)]])"
def test_piecewise():
# In each case, test eval() the lambdarepr() to make sure there are a
# correct number of parentheses. It will give a SyntaxError if there aren't.
h = "lambda x: "
p = Piecewise((x, True), evaluate=False)
l = lambdarepr(p)
eval(h + l)
assert l == "((x) if (True) else None)"
p = Piecewise((x, x < 0))
l = lambdarepr(p)
eval(h + l)
assert l == "((x) if (x < 0) else None)"
p = Piecewise(
(1, x < 1),
(2, x < 2),
(0, True)
)
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x < 1) else (((2) if (x < 2) else " \
"(((0) if (True) else None)))))"
p = Piecewise(
(1, x < 1),
(2, x < 2),
)
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x < 1) else (((2) if (x < 2) else None)))"
p = Piecewise(
(x, x < 1),
(x**2, Interval(3, 4, True, False).contains(x)),
(0, True),
)
l = lambdarepr(p)
eval(h + l)
assert l == "((x) if (x < 1) else (((x**2) if (((x <= 4) and " \
"(x > 3))) else (((0) if (True) else None)))))"
p = Piecewise(
(x**2, x < 0),
(x, Interval(0, 1, False, True).contains(x)),
(2 - x, x >= 1),
(0, True)
)
l = lambdarepr(p)
eval(h + l)
assert l == "((x**2) if (x < 0) else (((x) if (((x >= 0) and (x < 1))) " \
"else (((-x + 2) if (x >= 1) else (((0) if (True) else None)))))))"
p = Piecewise(
(x**2, x < 0),
(x, Interval(0, 1, False, True).contains(x)),
(2 - x, x >= 1),
)
l = lambdarepr(p)
eval(h + l)
assert l == "((x**2) if (x < 0) else (((x) if (((x >= 0) and " \
"(x < 1))) else (((-x + 2) if (x >= 1) else None)))))"
p = Piecewise(
(1, x >= 1),
(2, x >= 2),
(3, x >= 3),
(4, x >= 4),
(5, x >= 5),
(6, True)
)
l = lambdarepr(p)
eval(h + l)
assert l == ("((1) if (x >= 1) else (((2) if (x >= 2) else (((3) if "
"(x >= 3) else (((4) if (x >= 4) else (((5) if (x >= 5) else (((6) if "
"(True) else None)))))))))))")
p = Piecewise(
(1, x <= 1),
(2, x <= 2),
(3, x <= 3),
(4, x <= 4),
(5, x <= 5),
(6, True)
)
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x <= 1) else (((2) if (x <= 2) else (((3) if " \
"(x <= 3) else (((4) if (x <= 4) else (((5) if (x <= 5) else (((6) if " \
"(True) else None)))))))))))"
p = Piecewise(
(1, x > 1),
(2, x > 2),
(3, x > 3),
(4, x > 4),
(5, x > 5),
(6, True)
)
l = lambdarepr(p)
eval(h + l)
assert l == ("((1) if (x > 1) else (((2) if (x > 2) else (((3) if "
"(x > 3) else (((4) if (x > 4) else (((5) if (x > 5) else (((6) if "
"(True) else None)))))))))))")
p = Piecewise(
(1, x < 1),
(2, x < 2),
(3, x < 3),
(4, x < 4),
(5, x < 5),
(6, True)
)
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x < 1) else (((2) if (x < 2) else (((3) if " \
"(x < 3) else (((4) if (x < 4) else (((5) if (x < 5) else (((6) if " \
"(True) else None)))))))))))"
def test_sum():
# In each case, test eval() the lambdarepr() to make sure that
# it evaluates to the same results as the symbolic expression
s = Sum(x ** i, (i, a, b))
l = lambdarepr(s)
assert l == "(builtins.sum(x**i for i in range(a, b+1)))"
assert (lambdify((x, a, b), s)(2, 3, 8) ==
s.subs([(x, 2), (a, 3), (b, 8)]).doit())
s = Sum(i * x, (i, a, b))
l = lambdarepr(s)
assert l == "(builtins.sum(i*x for i in range(a, b+1)))"
assert (lambdify((x, a, b), s)(2, 3, 8) ==
s.subs([(x, 2), (a, 3), (b, 8)]).doit())
def test_multiple_sums():
s = Sum(i * x + j, (i, a, b), (j, c, d))
l = lambdarepr(s)
assert l == "(builtins.sum(i*x + j for i in range(a, b+1) for j in range(c, d+1)))"
assert (lambdify((x, a, b, c, d), s)(2, 3, 4, 5, 6) ==
s.subs([(x, 2), (a, 3), (b, 4), (c, 5), (d, 6)]).doit())
def test_settings():
raises(TypeError, lambda: lambdarepr(sin(x), method="garbage"))
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.