repo_name stringlengths 5 100 | path stringlengths 4 375 | copies stringclasses 991
values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15
values |
|---|---|---|---|---|---|
edibledinos/pwnypack | tests/test_codec.py | 1 | 1440 | import pwny
def test_xor_int():
assert pwny.xor(61, b'fooo') == b'[RRR'
def test_xor_str():
assert pwny.xor(b'abcd', b'fooo') == b'\x07\r\x0c\x0b'
assert pwny.xor(b'abcd', b'fooofooo') == b'\x07\r\x0c\x0b\x07\r\x0c\x0b'
def test_rot13():
assert pwny.rot13('whax') == 'junk'
def test_caesar():
assert pwny.caesar(1, 'abcXYZ') == 'bcdYZA'
def test_enhex():
assert pwny.enhex(b'ABCD') == '41424344'
def test_dehex():
assert pwny.dehex('41424344') == b'ABCD'
def test_enb64():
assert pwny.enb64(b'ABCD') == 'QUJDRA=='
def test_deb64():
assert pwny.deb64('QUJDRA==') == b'ABCD'
def test_deurlform():
assert pwny.deurlform('foo=bar&baz=quux&baz=corge') == {'foo': ['bar'], 'baz': ['quux', 'corge']}
def test_enurlform():
assert pwny.enurlform((('foo', 'bar'), ('baz', ['quux', 'corge']))) == 'foo=bar&baz=quux&baz=corge'
def test_enurlquote():
assert pwny.enurlquote('Foo Bar/Baz') == 'Foo%20Bar/Baz'
def test_enurlquote_plus():
assert pwny.enurlquote('Foo Bar/Baz', plus=True) == 'Foo+Bar%2FBaz'
def test_deurlquote():
assert pwny.deurlquote('Foo%20Bar%2FBaz') == 'Foo Bar/Baz'
def test_deurlquote_no_plus():
assert pwny.deurlquote('Foo+Bar%2FBaz') == 'Foo+Bar/Baz'
def test_deurlquote_plus():
assert pwny.deurlquote('Foo+Bar%2FBaz', True) == 'Foo Bar/Baz'
def test_frequency():
assert pwny.frequency('ABCD') == {'A': 1, 'B': 1, 'C': 1, 'D': 1}
| mit |
susansalkeld/discsongs | discsongs/lib/python2.7/site-packages/sqlalchemy/orm/evaluator.py | 33 | 5032 | # orm/evaluator.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import operator
from ..sql import operators
from .. import util
class UnevaluatableError(Exception):
pass
_straight_ops = set(getattr(operators, op)
for op in ('add', 'mul', 'sub',
'div',
'mod', 'truediv',
'lt', 'le', 'ne', 'gt', 'ge', 'eq'))
_notimplemented_ops = set(getattr(operators, op)
for op in ('like_op', 'notlike_op', 'ilike_op',
'notilike_op', 'between_op', 'in_op',
'notin_op', 'endswith_op', 'concat_op'))
class EvaluatorCompiler(object):
def __init__(self, target_cls=None):
self.target_cls = target_cls
def process(self, clause):
meth = getattr(self, "visit_%s" % clause.__visit_name__, None)
if not meth:
raise UnevaluatableError(
"Cannot evaluate %s" % type(clause).__name__)
return meth(clause)
def visit_grouping(self, clause):
return self.process(clause.element)
def visit_null(self, clause):
return lambda obj: None
def visit_false(self, clause):
return lambda obj: False
def visit_true(self, clause):
return lambda obj: True
def visit_column(self, clause):
if 'parentmapper' in clause._annotations:
parentmapper = clause._annotations['parentmapper']
if self.target_cls and not issubclass(
self.target_cls, parentmapper.class_):
util.warn(
"Can't do in-Python evaluation of criteria against "
"alternate class %s; "
"expiration of objects will not be accurate "
"and/or may fail. synchronize_session should be set to "
"False or 'fetch'. "
"This warning will be an exception "
"in 1.0." % parentmapper.class_
)
key = parentmapper._columntoproperty[clause].key
else:
key = clause.key
get_corresponding_attr = operator.attrgetter(key)
return lambda obj: get_corresponding_attr(obj)
def visit_clauselist(self, clause):
evaluators = list(map(self.process, clause.clauses))
if clause.operator is operators.or_:
def evaluate(obj):
has_null = False
for sub_evaluate in evaluators:
value = sub_evaluate(obj)
if value:
return True
has_null = has_null or value is None
if has_null:
return None
return False
elif clause.operator is operators.and_:
def evaluate(obj):
for sub_evaluate in evaluators:
value = sub_evaluate(obj)
if not value:
if value is None:
return None
return False
return True
else:
raise UnevaluatableError(
"Cannot evaluate clauselist with operator %s" %
clause.operator)
return evaluate
def visit_binary(self, clause):
eval_left, eval_right = list(map(self.process,
[clause.left, clause.right]))
operator = clause.operator
if operator is operators.is_:
def evaluate(obj):
return eval_left(obj) == eval_right(obj)
elif operator is operators.isnot:
def evaluate(obj):
return eval_left(obj) != eval_right(obj)
elif operator in _straight_ops:
def evaluate(obj):
left_val = eval_left(obj)
right_val = eval_right(obj)
if left_val is None or right_val is None:
return None
return operator(eval_left(obj), eval_right(obj))
else:
raise UnevaluatableError(
"Cannot evaluate %s with operator %s" %
(type(clause).__name__, clause.operator))
return evaluate
def visit_unary(self, clause):
eval_inner = self.process(clause.element)
if clause.operator is operators.inv:
def evaluate(obj):
value = eval_inner(obj)
if value is None:
return None
return not value
return evaluate
raise UnevaluatableError(
"Cannot evaluate %s with operator %s" %
(type(clause).__name__, clause.operator))
def visit_bindparam(self, clause):
val = clause.value
return lambda obj: val
| mit |
boberfly/gaffer | python/GafferTest/CompoundPlugNode.py | 11 | 3137 | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import IECore
import Gaffer
## This class is used by several of the unit tests.
class CompoundPlugNode( Gaffer.DependencyNode ) :
def __init__( self, name="CompoundPlugNode" ) :
Gaffer.DependencyNode.__init__( self, name )
p = Gaffer.Plug( name = "p" )
c1 = Gaffer.FloatPlug( name = "f" )
c2 = Gaffer.StringPlug( name = "s" )
p.addChild( c1 )
p.addChild( c2 )
self.addChild( p )
po = Gaffer.Plug( name = "o", direction = Gaffer.Plug.Direction.Out )
co1 = Gaffer.FloatPlug( name = "f", direction = Gaffer.Plug.Direction.Out )
co2 = Gaffer.StringPlug( name = "s", direction = Gaffer.Plug.Direction.Out )
po.addChild( co1 )
po.addChild( co2 )
self.addChild( po )
# For ValuePlugTest.testSerialisationOfDynamicPlugsOnNondynamicParent().
self.addChild( Gaffer.Plug( name = "nonDynamicParent" ) )
# For BoxTest.testPromoteStaticPlugsWithChildren
self["valuePlug"] = Gaffer.ValuePlug()
self["valuePlug"]["i"] = Gaffer.IntPlug()
def affects( self, inputPlug ) :
outputs = Gaffer.DependencyNode.affects( self, inputPlug )
if inputPlug.parent().isSame( self["p"] ) :
outputs.append( self["o"][inputPlug.getName()] )
return outputs
IECore.registerRunTimeTyped( CompoundPlugNode, typeName = "GafferTest::CompoundPlugNode" )
| bsd-3-clause |
davidar/pyzui | pyzui/statictileprovider.py | 1 | 1667 | ## PyZUI 0.1 - Python Zooming User Interface
## Copyright (C) 2009 David Roberts <d@vidr.cc>
##
## 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.
"""Class for loading tiles from the local tilestore."""
import os
import Image
from tileprovider import TileProvider
import tilestore as TileStore
class StaticTileProvider(TileProvider):
"""StaticTileProvider objects are used for loading tiles from the
disk-cache into a TileCache.
Constructor: StaticTileProvider(TileCache)
"""
def __init__(self, tilecache):
TileProvider.__init__(self, tilecache)
def _load(self, tile_id):
media_id, tilelevel, row, col = tile_id
maxtilelevel = TileStore.get_metadata(media_id, 'maxtilelevel')
if tilelevel > maxtilelevel:
return None
filename = TileStore.get_tile_path(tile_id)
try:
tile = Image.open(filename)
tile.load()
return tile
except IOError:
return None
| gpl-2.0 |
DxCx/plugin.video.animeram | resources/lib/ui/js2py/host/jseval.py | 27 | 1517 | from ..base import *
import inspect
try:
from js2py.translators.translator import translate_js
except:
pass
@Js
def Eval(code):
local_scope = inspect.stack()[3][0].f_locals['var']
global_scope = this.GlobalObject
# todo fix scope - we have to behave differently if called through variable other than eval
# we will use local scope (default)
globals()['var'] = local_scope
try:
py_code = translate_js(code.to_string().value, '')
except SyntaxError as syn_err:
raise MakeError('SyntaxError', str(syn_err))
lines = py_code.split('\n')
# a simple way to return value from eval. Will not work in complex cases.
has_return = False
for n in xrange(len(lines)):
line = lines[len(lines)-n-1]
if line.strip():
if line.startswith(' '):
break
elif line.strip()=='pass':
continue
elif any(line.startswith(e) for e in ['return ', 'continue ', 'break', 'raise ']):
break
else:
has_return = True
cand = 'EVAL_RESULT = (%s)\n'%line
try:
compile(cand, '', 'exec')
except SyntaxError:
break
lines[len(lines)-n-1] = cand
py_code = '\n'.join(lines)
break
#print py_code
executor(py_code)
if has_return:
return globals()['EVAL_RESULT']
def executor(code):
exec(code, globals())
| gpl-3.0 |
mariosky/evo-drawings | venv/lib/python2.7/site-packages/pip/commands/__init__.py | 476 | 2236 | """
Package containing all pip commands
"""
from pip.commands.bundle import BundleCommand
from pip.commands.completion import CompletionCommand
from pip.commands.freeze import FreezeCommand
from pip.commands.help import HelpCommand
from pip.commands.list import ListCommand
from pip.commands.search import SearchCommand
from pip.commands.show import ShowCommand
from pip.commands.install import InstallCommand
from pip.commands.uninstall import UninstallCommand
from pip.commands.unzip import UnzipCommand
from pip.commands.zip import ZipCommand
from pip.commands.wheel import WheelCommand
commands = {
BundleCommand.name: BundleCommand,
CompletionCommand.name: CompletionCommand,
FreezeCommand.name: FreezeCommand,
HelpCommand.name: HelpCommand,
SearchCommand.name: SearchCommand,
ShowCommand.name: ShowCommand,
InstallCommand.name: InstallCommand,
UninstallCommand.name: UninstallCommand,
UnzipCommand.name: UnzipCommand,
ZipCommand.name: ZipCommand,
ListCommand.name: ListCommand,
WheelCommand.name: WheelCommand,
}
commands_order = [
InstallCommand,
UninstallCommand,
FreezeCommand,
ListCommand,
ShowCommand,
SearchCommand,
WheelCommand,
ZipCommand,
UnzipCommand,
BundleCommand,
HelpCommand,
]
def get_summaries(ignore_hidden=True, ordered=True):
"""Yields sorted (command name, command summary) tuples."""
if ordered:
cmditems = _sort_commands(commands, commands_order)
else:
cmditems = commands.items()
for name, command_class in cmditems:
if ignore_hidden and command_class.hidden:
continue
yield (name, command_class.summary)
def get_similar_commands(name):
"""Command name auto-correct."""
from difflib import get_close_matches
close_commands = get_close_matches(name, commands.keys())
if close_commands:
guess = close_commands[0]
else:
guess = False
return guess
def _sort_commands(cmddict, order):
def keyfn(key):
try:
return order.index(key[1])
except ValueError:
# unordered items should come last
return 0xff
return sorted(cmddict.items(), key=keyfn)
| agpl-3.0 |
scottdangelo/RemoveVolumeMangerLocks | cinder/tests/unit/wsgi/test_eventlet_server.py | 10 | 12798 | # Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Unit tests for `cinder.wsgi`."""
import os.path
import re
import socket
import ssl
import tempfile
import time
import mock
from oslo_config import cfg
from oslo_i18n import fixture as i18n_fixture
from six.moves import urllib
import testtools
import webob
import webob.dec
from cinder import exception
from cinder.i18n import _
from cinder import test
from cinder.wsgi import common as wsgi_common
from cinder.wsgi import eventlet_server as wsgi
CONF = cfg.CONF
TEST_VAR_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
'../var'))
def open_no_proxy(*args, **kwargs):
# NOTE(coreycb):
# Deal with more secure certification chain verficiation
# introduced in python 2.7.9 under PEP-0476
# https://github.com/python/peps/blob/master/pep-0476.txt
if hasattr(ssl, "_create_unverified_context"):
context = ssl._create_unverified_context()
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({}),
urllib.request.HTTPSHandler(context=context)
)
else:
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
return opener.open(*args, **kwargs)
class TestLoaderNothingExists(test.TestCase):
"""Loader tests where os.path.exists always returns False."""
def setUp(self):
super(TestLoaderNothingExists, self).setUp()
self.stubs.Set(os.path, 'exists', lambda _: False)
def test_config_not_found(self):
self.assertRaises(
exception.ConfigNotFound,
wsgi_common.Loader,
)
class TestLoaderNormalFilesystem(test.TestCase):
"""Loader tests with normal filesystem (unmodified os.path module)."""
_paste_config = """
[app:test_app]
use = egg:Paste#static
document_root = /tmp
"""
def setUp(self):
super(TestLoaderNormalFilesystem, self).setUp()
self.config = tempfile.NamedTemporaryFile(mode="w+t")
self.config.write(self._paste_config.lstrip())
self.config.seek(0)
self.config.flush()
self.loader = wsgi_common.Loader(self.config.name)
self.addCleanup(self.config.close)
def test_config_found(self):
self.assertEqual(self.config.name, self.loader.config_path)
def test_app_not_found(self):
self.assertRaises(
exception.PasteAppNotFound,
self.loader.load_app,
"non-existent app",
)
def test_app_found(self):
url_parser = self.loader.load_app("test_app")
self.assertEqual("/tmp", url_parser.directory)
class TestWSGIServer(test.TestCase):
"""WSGI server tests."""
def _ipv6_configured():
try:
with file('/proc/net/if_inet6') as f:
return len(f.read()) > 0
except IOError:
return False
def test_no_app(self):
server = wsgi.Server("test_app", None,
host="127.0.0.1", port=0)
self.assertEqual("test_app", server.name)
def test_start_random_port(self):
server = wsgi.Server("test_random_port", None, host="127.0.0.1")
server.start()
self.assertNotEqual(0, server.port)
server.stop()
server.wait()
@testtools.skipIf(not _ipv6_configured(),
"Test requires an IPV6 configured interface")
def test_start_random_port_with_ipv6(self):
server = wsgi.Server("test_random_port",
None,
host="::1")
server.start()
self.assertEqual("::1", server.host)
self.assertNotEqual(0, server.port)
server.stop()
server.wait()
def test_server_pool_waitall(self):
# test pools waitall method gets called while stopping server
server = wsgi.Server("test_server", None,
host="127.0.0.1")
server.start()
with mock.patch.object(server._pool,
'waitall') as mock_waitall:
server.stop()
server.wait()
mock_waitall.assert_called_once_with()
def test_app(self):
greetings = 'Hello, World!!!'
def hello_world(env, start_response):
if env['PATH_INFO'] != '/':
start_response('404 Not Found',
[('Content-Type', 'text/plain')])
return ['Not Found\r\n']
start_response('200 OK', [('Content-Type', 'text/plain')])
return [greetings]
server = wsgi.Server("test_app", hello_world,
host="127.0.0.1", port=0)
server.start()
response = open_no_proxy('http://127.0.0.1:%d/' % server.port)
self.assertEqual(greetings, response.read())
server.stop()
def test_client_socket_timeout(self):
CONF.set_default("client_socket_timeout", 0.1)
greetings = 'Hello, World!!!'
def hello_world(env, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
return [greetings]
server = wsgi.Server("test_app", hello_world,
host="127.0.0.1", port=0)
server.start()
s = socket.socket()
s.connect(("127.0.0.1", server.port))
fd = s.makefile('rw')
fd.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
fd.flush()
buf = fd.read()
self.assertTrue(re.search(greetings, buf))
s2 = socket.socket()
s2.connect(("127.0.0.1", server.port))
time.sleep(0.2)
fd = s2.makefile('rw')
fd.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
fd.flush()
buf = fd.read()
# connection is closed so we get nothing from the server
self.assertFalse(buf)
server.stop()
def test_app_using_ssl(self):
CONF.set_default("ssl_cert_file",
os.path.join(TEST_VAR_DIR, 'certificate.crt'))
CONF.set_default("ssl_key_file",
os.path.join(TEST_VAR_DIR, 'privatekey.key'))
greetings = 'Hello, World!!!'
@webob.dec.wsgify
def hello_world(req):
return greetings
server = wsgi.Server("test_app", hello_world,
host="127.0.0.1", port=0)
server.start()
response = open_no_proxy('https://127.0.0.1:%d/' % server.port)
self.assertEqual(greetings, response.read())
server.stop()
@testtools.skipIf(not _ipv6_configured(),
"Test requires an IPV6 configured interface")
def test_app_using_ipv6_and_ssl(self):
CONF.set_default("ssl_cert_file",
os.path.join(TEST_VAR_DIR, 'certificate.crt'))
CONF.set_default("ssl_key_file",
os.path.join(TEST_VAR_DIR, 'privatekey.key'))
greetings = 'Hello, World!!!'
@webob.dec.wsgify
def hello_world(req):
return greetings
server = wsgi.Server("test_app",
hello_world,
host="::1",
port=0)
server.start()
response = open_no_proxy('https://[::1]:%d/' % server.port)
self.assertEqual(greetings, response.read())
server.stop()
def test_reset_pool_size_to_default(self):
server = wsgi.Server("test_resize", None, host="127.0.0.1")
server.start()
# Stopping the server, which in turn sets pool size to 0
server.stop()
self.assertEqual(0, server._pool.size)
# Resetting pool size to default
server.reset()
server.start()
self.assertEqual(1000, server._pool.size)
class ExceptionTest(test.TestCase):
def setUp(self):
super(ExceptionTest, self).setUp()
self.useFixture(i18n_fixture.ToggleLazy(True))
def _wsgi_app(self, inner_app):
# NOTE(luisg): In order to test localization, we need to
# make sure the lazy _() is installed in the 'fault' module
# also we don't want to install the _() system-wide and
# potentially break other test cases, so we do it here for this
# test suite only.
from cinder.api.middleware import fault
return fault.FaultWrapper(inner_app)
def _do_test_exception_safety_reflected_in_faults(self, expose):
class ExceptionWithSafety(exception.CinderException):
safe = expose
@webob.dec.wsgify
def fail(req):
raise ExceptionWithSafety('some explanation')
api = self._wsgi_app(fail)
resp = webob.Request.blank('/').get_response(api)
self.assertIn('{"computeFault', resp.body)
expected = ('ExceptionWithSafety: some explanation' if expose else
'The server has either erred or is incapable '
'of performing the requested operation.')
self.assertIn(expected, resp.body)
self.assertEqual(500, resp.status_int, resp.body)
def test_safe_exceptions_are_described_in_faults(self):
self._do_test_exception_safety_reflected_in_faults(True)
def test_unsafe_exceptions_are_not_described_in_faults(self):
self._do_test_exception_safety_reflected_in_faults(False)
def _do_test_exception_mapping(self, exception_type, msg):
@webob.dec.wsgify
def fail(req):
raise exception_type(msg)
api = self._wsgi_app(fail)
resp = webob.Request.blank('/').get_response(api)
self.assertIn(msg, resp.body)
self.assertEqual(exception_type.code, resp.status_int, resp.body)
if hasattr(exception_type, 'headers'):
for (key, value) in exception_type.headers.items():
self.assertIn(key, resp.headers)
self.assertEqual(resp.headers[key], value)
def test_quota_error_mapping(self):
self._do_test_exception_mapping(exception.QuotaError, 'too many used')
def test_non_cinder_notfound_exception_mapping(self):
class ExceptionWithCode(Exception):
code = 404
self._do_test_exception_mapping(ExceptionWithCode,
'NotFound')
def test_non_cinder_exception_mapping(self):
class ExceptionWithCode(Exception):
code = 417
self._do_test_exception_mapping(ExceptionWithCode,
'Expectation failed')
def test_exception_with_none_code_throws_500(self):
class ExceptionWithNoneCode(Exception):
code = None
@webob.dec.wsgify
def fail(req):
raise ExceptionWithNoneCode()
api = self._wsgi_app(fail)
resp = webob.Request.blank('/').get_response(api)
self.assertEqual(500, resp.status_int)
@mock.patch('cinder.i18n.translate')
def test_cinder_exception_with_localized_explanation(self, mock_t9n):
msg = 'My Not Found'
msg_translation = 'Mi No Encontrado'
message = _(msg) # noqa
@webob.dec.wsgify
def fail(req):
class MyVolumeNotFound(exception.NotFound):
def __init__(self):
self.msg = message
self.safe = True
raise MyVolumeNotFound()
# Test response without localization
def mock_get_non_localized_message(msgid, locale):
return msg
mock_t9n.side_effect = mock_get_non_localized_message
api = self._wsgi_app(fail)
resp = webob.Request.blank('/').get_response(api)
self.assertEqual(404, resp.status_int)
self.assertIn(msg, resp.body)
# Test response with localization
def mock_translate(msgid, locale):
return msg_translation
mock_t9n.side_effect = mock_translate
api = self._wsgi_app(fail)
resp = webob.Request.blank('/').get_response(api)
self.assertEqual(404, resp.status_int)
self.assertIn(msg_translation, resp.body)
| apache-2.0 |
mmmavis/bedrock | lib/l10n_utils/template.py | 28 | 5011 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from jinja2.ext import Extension, InternationalizationExtension, nodes
from tower import strip_whitespace
class I18nExtension(InternationalizationExtension):
"""
Use this instead of `tower.template.i18n` because the override of `_`
global was throwing errors.
"""
def _parse_block(self, parser, allow_pluralize):
ref, buffer = super(I18nExtension, self)._parse_block(parser,
allow_pluralize)
return ref, strip_whitespace(buffer)
class L10nBlockExtension(Extension):
"""
Add support for an L10n block that works like a regular "block" for now.
"""
tags = set(['l10n'])
def parse(self, parser):
# Jump over first token ("l10n"), grab line number.
lineno = parser.stream.next().lineno
# Block name is mandatory.
name = parser.stream.expect('name').value
locales = []
parser.stream.skip_if('comma')
# Grab the locales if provided
if parser.stream.current.type == 'name':
parser.stream.skip() # locales
parser.stream.skip() # assign (=)
prev_sub = False
while parser.stream.current.type not in ['integer', 'block_end']:
parser.stream.skip_if('comma')
parser.stream.skip_if('assign')
token = parser.stream.current
if token.type in ['integer', 'block_end']:
break
if token.type == 'name':
if prev_sub:
locales[-1] += token.value
prev_sub = False
else:
locales.append(token.value)
if token.type == 'sub':
locales[-1] += '-'
prev_sub = True
parser.stream.next()
# Add version if provided.
if parser.stream.current.type == 'integer':
version = int(parser.parse_expression().value)
else:
version = 0 # Default version for unversioned block.
# Parse content.
body = parser.parse_statements(['name:was', 'name:endl10n'],
drop_needle=False)
# Translation fallback: If this is followed by an "was" tag, render
# that block instead.
end_tag = parser.stream.expect('name') # Either was or endl10n.
if end_tag.value == 'was':
body = parser.parse_statements(['name:endl10n'], drop_needle=True)
# Build regular block node with special node name and remember version.
node = nodes.Block()
node.set_lineno(lineno)
node.name = '__l10n__{0}'.format(name)
node.version = version # For debugging only, for now.
node.locales = locales
node.body = body
# I *think*, `true` would mean that variable assignments inside this
# block do not persist beyond this block (like a `with` block).
node.scoped = False
return node
class LoadLangExtension(Extension):
"""Create a special syntax for specifying additional lang files.
It looks like this: {% lang_files "foo" "bar" %}. We convert it
into a call to a helper method because it needs to context to load
in the correct locale. As a result, this must be within a block."""
tags = set(['set_lang_files', 'add_lang_files'])
def parse(self, parser):
# Skip over the block name
name = parser.stream.next()
lineno = name.lineno
# Grab all the args
args = [parser.stream.expect('string').value]
while parser.stream.current.type == 'string':
args.append(parser.stream.current.value)
parser.stream.next()
# Make a node that calls the lang_files helper
content_nodes = [nodes.Call(nodes.Name('lang_files', 'load'),
[nodes.Const(x) for x in args], [],
None, None)]
if name == 'add_lang_files':
# If we are adding files, we need to keep the parent
# template's list of lang files as well
content_nodes.insert(0, [nodes.Call(nodes.Name('super', 'load'),
[], [], None, None)])
# Since we are a block, we must emit a block too, so make a
# random one that contains a call to the load function
node = nodes.Block().set_lineno(lineno)
node.name = '__langfiles__'
node.scoped = False
node.body = [nodes.Output(content_nodes)]
node.set_lineno(lineno)
return node
# Makes for a prettier import in settings.py
l10n_blocks = L10nBlockExtension
lang_blocks = LoadLangExtension
i18n = I18nExtension
| mpl-2.0 |
rossburton/yocto-autobuilder | lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/test/test_formmethod.py | 39 | 3653 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for formmethod module.
"""
from twisted.trial import unittest
from twisted.python import formmethod
class ArgumentTestCase(unittest.TestCase):
def argTest(self, argKlass, testPairs, badValues, *args, **kwargs):
arg = argKlass("name", *args, **kwargs)
for val, result in testPairs:
self.assertEqual(arg.coerce(val), result)
for val in badValues:
self.assertRaises(formmethod.InputError, arg.coerce, val)
def test_argument(self):
"""
Test that corce correctly raises NotImplementedError.
"""
arg = formmethod.Argument("name")
self.assertRaises(NotImplementedError, arg.coerce, "")
def testString(self):
self.argTest(formmethod.String, [("a", "a"), (1, "1"), ("", "")], ())
self.argTest(formmethod.String, [("ab", "ab"), ("abc", "abc")], ("2", ""), min=2)
self.argTest(formmethod.String, [("ab", "ab"), ("a", "a")], ("223213", "345x"), max=3)
self.argTest(formmethod.String, [("ab", "ab"), ("add", "add")], ("223213", "x"), min=2, max=3)
def testInt(self):
self.argTest(formmethod.Integer, [("3", 3), ("-2", -2), ("", None)], ("q", "2.3"))
self.argTest(formmethod.Integer, [("3", 3), ("-2", -2)], ("q", "2.3", ""), allowNone=0)
def testFloat(self):
self.argTest(formmethod.Float, [("3", 3.0), ("-2.3", -2.3), ("", None)], ("q", "2.3z"))
self.argTest(formmethod.Float, [("3", 3.0), ("-2.3", -2.3)], ("q", "2.3z", ""),
allowNone=0)
def testChoice(self):
choices = [("a", "apple", "an apple"),
("b", "banana", "ook")]
self.argTest(formmethod.Choice, [("a", "apple"), ("b", "banana")],
("c", 1), choices=choices)
def testFlags(self):
flags = [("a", "apple", "an apple"),
("b", "banana", "ook")]
self.argTest(formmethod.Flags,
[(["a"], ["apple"]), (["b", "a"], ["banana", "apple"])],
(["a", "c"], ["fdfs"]),
flags=flags)
def testBoolean(self):
tests = [("yes", 1), ("", 0), ("False", 0), ("no", 0)]
self.argTest(formmethod.Boolean, tests, ())
def test_file(self):
"""
Test the correctness of the coerce function.
"""
arg = formmethod.File("name", allowNone=0)
self.assertEqual(arg.coerce("something"), "something")
self.assertRaises(formmethod.InputError, arg.coerce, None)
arg2 = formmethod.File("name")
self.assertEqual(arg2.coerce(None), None)
def testDate(self):
goodTests = {
("2002", "12", "21"): (2002, 12, 21),
("1996", "2", "29"): (1996, 2, 29),
("", "", ""): None,
}.items()
badTests = [("2002", "2", "29"), ("xx", "2", "3"),
("2002", "13", "1"), ("1999", "12","32"),
("2002", "1"), ("2002", "2", "3", "4")]
self.argTest(formmethod.Date, goodTests, badTests)
def testRangedInteger(self):
goodTests = {"0": 0, "12": 12, "3": 3}.items()
badTests = ["-1", "x", "13", "-2000", "3.4"]
self.argTest(formmethod.IntegerRange, goodTests, badTests, 0, 12)
def testVerifiedPassword(self):
goodTests = {("foo", "foo"): "foo", ("ab", "ab"): "ab"}.items()
badTests = [("ab", "a"), ("12345", "12345"), ("", ""), ("a", "a"), ("a",), ("a", "a", "a")]
self.argTest(formmethod.VerifiedPassword, goodTests, badTests, min=2, max=4)
| gpl-2.0 |
samabhi/pstHealth | venv/lib/python2.7/site-packages/werkzeug/contrib/sessions.py | 256 | 12577 | # -*- coding: utf-8 -*-
r"""
werkzeug.contrib.sessions
~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains some helper classes that help one to add session
support to a python WSGI application. For full client-side session
storage see :mod:`~werkzeug.contrib.securecookie` which implements a
secure, client-side session storage.
Application Integration
=======================
::
from werkzeug.contrib.sessions import SessionMiddleware, \
FilesystemSessionStore
app = SessionMiddleware(app, FilesystemSessionStore())
The current session will then appear in the WSGI environment as
`werkzeug.session`. However it's recommended to not use the middleware
but the stores directly in the application. However for very simple
scripts a middleware for sessions could be sufficient.
This module does not implement methods or ways to check if a session is
expired. That should be done by a cronjob and storage specific. For
example to prune unused filesystem sessions one could check the modified
time of the files. It sessions are stored in the database the new()
method should add an expiration timestamp for the session.
For better flexibility it's recommended to not use the middleware but the
store and session object directly in the application dispatching::
session_store = FilesystemSessionStore()
def application(environ, start_response):
request = Request(environ)
sid = request.cookies.get('cookie_name')
if sid is None:
request.session = session_store.new()
else:
request.session = session_store.get(sid)
response = get_the_response_object(request)
if request.session.should_save:
session_store.save(request.session)
response.set_cookie('cookie_name', request.session.sid)
return response(environ, start_response)
:copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import re
import os
import tempfile
from os import path
from time import time
from random import random
from hashlib import sha1
from pickle import dump, load, HIGHEST_PROTOCOL
from werkzeug.datastructures import CallbackDict
from werkzeug.utils import dump_cookie, parse_cookie
from werkzeug.wsgi import ClosingIterator
from werkzeug.posixemulation import rename
from werkzeug._compat import PY2, text_type
from werkzeug.filesystem import get_filesystem_encoding
_sha1_re = re.compile(r'^[a-f0-9]{40}$')
def _urandom():
if hasattr(os, 'urandom'):
return os.urandom(30)
return text_type(random()).encode('ascii')
def generate_key(salt=None):
if salt is None:
salt = repr(salt).encode('ascii')
return sha1(b''.join([
salt,
str(time()).encode('ascii'),
_urandom()
])).hexdigest()
class ModificationTrackingDict(CallbackDict):
__slots__ = ('modified',)
def __init__(self, *args, **kwargs):
def on_update(self):
self.modified = True
self.modified = False
CallbackDict.__init__(self, on_update=on_update)
dict.update(self, *args, **kwargs)
def copy(self):
"""Create a flat copy of the dict."""
missing = object()
result = object.__new__(self.__class__)
for name in self.__slots__:
val = getattr(self, name, missing)
if val is not missing:
setattr(result, name, val)
return result
def __copy__(self):
return self.copy()
class Session(ModificationTrackingDict):
"""Subclass of a dict that keeps track of direct object changes. Changes
in mutable structures are not tracked, for those you have to set
`modified` to `True` by hand.
"""
__slots__ = ModificationTrackingDict.__slots__ + ('sid', 'new')
def __init__(self, data, sid, new=False):
ModificationTrackingDict.__init__(self, data)
self.sid = sid
self.new = new
def __repr__(self):
return '<%s %s%s>' % (
self.__class__.__name__,
dict.__repr__(self),
self.should_save and '*' or ''
)
@property
def should_save(self):
"""True if the session should be saved.
.. versionchanged:: 0.6
By default the session is now only saved if the session is
modified, not if it is new like it was before.
"""
return self.modified
class SessionStore(object):
"""Baseclass for all session stores. The Werkzeug contrib module does not
implement any useful stores besides the filesystem store, application
developers are encouraged to create their own stores.
:param session_class: The session class to use. Defaults to
:class:`Session`.
"""
def __init__(self, session_class=None):
if session_class is None:
session_class = Session
self.session_class = session_class
def is_valid_key(self, key):
"""Check if a key has the correct format."""
return _sha1_re.match(key) is not None
def generate_key(self, salt=None):
"""Simple function that generates a new session key."""
return generate_key(salt)
def new(self):
"""Generate a new session."""
return self.session_class({}, self.generate_key(), True)
def save(self, session):
"""Save a session."""
def save_if_modified(self, session):
"""Save if a session class wants an update."""
if session.should_save:
self.save(session)
def delete(self, session):
"""Delete a session."""
def get(self, sid):
"""Get a session for this sid or a new session object. This method
has to check if the session key is valid and create a new session if
that wasn't the case.
"""
return self.session_class({}, sid, True)
#: used for temporary files by the filesystem session store
_fs_transaction_suffix = '.__wz_sess'
class FilesystemSessionStore(SessionStore):
"""Simple example session store that saves sessions on the filesystem.
This store works best on POSIX systems and Windows Vista / Windows
Server 2008 and newer.
.. versionchanged:: 0.6
`renew_missing` was added. Previously this was considered `True`,
now the default changed to `False` and it can be explicitly
deactivated.
:param path: the path to the folder used for storing the sessions.
If not provided the default temporary directory is used.
:param filename_template: a string template used to give the session
a filename. ``%s`` is replaced with the
session id.
:param session_class: The session class to use. Defaults to
:class:`Session`.
:param renew_missing: set to `True` if you want the store to
give the user a new sid if the session was
not yet saved.
"""
def __init__(self, path=None, filename_template='werkzeug_%s.sess',
session_class=None, renew_missing=False, mode=0o644):
SessionStore.__init__(self, session_class)
if path is None:
path = tempfile.gettempdir()
self.path = path
if isinstance(filename_template, text_type) and PY2:
filename_template = filename_template.encode(
get_filesystem_encoding())
assert not filename_template.endswith(_fs_transaction_suffix), \
'filename templates may not end with %s' % _fs_transaction_suffix
self.filename_template = filename_template
self.renew_missing = renew_missing
self.mode = mode
def get_session_filename(self, sid):
# out of the box, this should be a strict ASCII subset but
# you might reconfigure the session object to have a more
# arbitrary string.
if isinstance(sid, text_type) and PY2:
sid = sid.encode(get_filesystem_encoding())
return path.join(self.path, self.filename_template % sid)
def save(self, session):
fn = self.get_session_filename(session.sid)
fd, tmp = tempfile.mkstemp(suffix=_fs_transaction_suffix,
dir=self.path)
f = os.fdopen(fd, 'wb')
try:
dump(dict(session), f, HIGHEST_PROTOCOL)
finally:
f.close()
try:
rename(tmp, fn)
os.chmod(fn, self.mode)
except (IOError, OSError):
pass
def delete(self, session):
fn = self.get_session_filename(session.sid)
try:
os.unlink(fn)
except OSError:
pass
def get(self, sid):
if not self.is_valid_key(sid):
return self.new()
try:
f = open(self.get_session_filename(sid), 'rb')
except IOError:
if self.renew_missing:
return self.new()
data = {}
else:
try:
try:
data = load(f)
except Exception:
data = {}
finally:
f.close()
return self.session_class(data, sid, False)
def list(self):
"""Lists all sessions in the store.
.. versionadded:: 0.6
"""
before, after = self.filename_template.split('%s', 1)
filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before),
re.escape(after)))
result = []
for filename in os.listdir(self.path):
#: this is a session that is still being saved.
if filename.endswith(_fs_transaction_suffix):
continue
match = filename_re.match(filename)
if match is not None:
result.append(match.group(1))
return result
class SessionMiddleware(object):
"""A simple middleware that puts the session object of a store provided
into the WSGI environ. It automatically sets cookies and restores
sessions.
However a middleware is not the preferred solution because it won't be as
fast as sessions managed by the application itself and will put a key into
the WSGI environment only relevant for the application which is against
the concept of WSGI.
The cookie parameters are the same as for the :func:`~dump_cookie`
function just prefixed with ``cookie_``. Additionally `max_age` is
called `cookie_age` and not `cookie_max_age` because of backwards
compatibility.
"""
def __init__(self, app, store, cookie_name='session_id',
cookie_age=None, cookie_expires=None, cookie_path='/',
cookie_domain=None, cookie_secure=None,
cookie_httponly=False, environ_key='werkzeug.session'):
self.app = app
self.store = store
self.cookie_name = cookie_name
self.cookie_age = cookie_age
self.cookie_expires = cookie_expires
self.cookie_path = cookie_path
self.cookie_domain = cookie_domain
self.cookie_secure = cookie_secure
self.cookie_httponly = cookie_httponly
self.environ_key = environ_key
def __call__(self, environ, start_response):
cookie = parse_cookie(environ.get('HTTP_COOKIE', ''))
sid = cookie.get(self.cookie_name, None)
if sid is None:
session = self.store.new()
else:
session = self.store.get(sid)
environ[self.environ_key] = session
def injecting_start_response(status, headers, exc_info=None):
if session.should_save:
self.store.save(session)
headers.append(('Set-Cookie', dump_cookie(self.cookie_name,
session.sid, self.cookie_age,
self.cookie_expires, self.cookie_path,
self.cookie_domain, self.cookie_secure,
self.cookie_httponly)))
return start_response(status, headers, exc_info)
return ClosingIterator(self.app(environ, injecting_start_response),
lambda: self.store.save_if_modified(session))
| mit |
VillageAlliance/django-cms | cms/plugins/text/migrations/0005_publisher2.py | 7 | 8958 |
from south.db import db
from django.db import models
from cms.plugins.text.models import *
class Migration:
def forwards(self, orm):
# Deleting field 'Text.public'
db.delete_column('cmsplugin_text', 'public_id')
# Deleting model 'textpublic'
db.delete_table('cmsplugin_textpublic')
def backwards(self, orm):
# Adding field 'Text.public'
db.add_column('cmsplugin_text', 'public', orm['text.text:public'])
# Adding model 'textpublic'
db.create_table('cmsplugin_textpublic', (
('body', orm['text.textpublic:body']),
('cmspluginpublic_ptr', orm['text.textpublic:cmspluginpublic_ptr']),
('mark_delete', orm['text.textpublic:mark_delete']),
))
db.send_create_signal('text', ['textpublic'])
models = {
'cms.cmsplugin': {
'creation_date': ('models.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'language': ('models.CharField', [], {'max_length': '5', 'db_index': 'True'}),
'level': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'page': ('models.ForeignKey', [], {'to': "orm['cms.Page']"}),
'parent': ('models.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
'placeholder': ('models.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'plugin_type': ('models.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'position': ('models.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'publisher_is_draft': ('models.BooleanField', [], {'default': '1', 'db_index': 'True', 'blank': 'True'}),
'publisher_public': ('models.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.CMSPlugin']"}),
'publisher_state': ('models.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}),
'rght': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('models.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.cmspluginpublic': {
'creation_date': ('models.DateTimeField', [], {'default': 'datetime.datetime(2009, 7, 2, 6, 35, 28, 96687)'}),
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'language': ('models.CharField', [], {'max_length': '5', 'db_index': 'True'}),
'level': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'mark_delete': ('models.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'page': ('models.ForeignKey', [], {'to': "orm['cms.PagePublic']"}),
'parent': ('models.ForeignKey', [], {'to': "orm['cms.CMSPluginPublic']", 'null': 'True', 'blank': 'True'}),
'placeholder': ('models.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'plugin_type': ('models.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'position': ('models.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'rght': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('models.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.page': {
'changed_by': ('models.CharField', [], {'max_length': '70'}),
'created_by': ('models.CharField', [], {'max_length': '70'}),
'creation_date': ('models.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'in_navigation': ('models.BooleanField', [], {'default': 'True', 'db_index': 'True', 'blank': 'True'}),
'level': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'login_required': ('models.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'moderator_state': ('models.SmallIntegerField', [], {'default': '1', 'blank': 'True'}),
'navigation_extenders': ('models.CharField', [], {'db_index': 'True', 'max_length': '80', 'null': 'True', 'blank': 'True'}),
'parent': ('models.ForeignKey', [], {'related_name': "'children'", 'blank': 'True', 'null': 'True', 'to': "orm['cms.Page']"}),
'publication_date': ('models.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'publication_end_date': ('models.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'published': ('models.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'publisher_is_draft': ('models.BooleanField', [], {'default': '1', 'db_index': 'True', 'blank': 'True'}),
'publisher_public': ('models.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Page']"}),
'publisher_state': ('models.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}),
'reverse_id': ('models.CharField', [], {'db_index': 'True', 'max_length': '40', 'null': 'True', 'blank': 'True'}),
'rght': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'site': ('models.ForeignKey', [], {'to': "orm['sites.Site']"}),
'soft_root': ('models.BooleanField', [], {'default': 'False', 'db_index': 'True', 'blank': 'True'}),
'template': ('models.CharField', [], {'max_length': '100'}),
'tree_id': ('models.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.pagepublic': {
'changed_by': ('models.CharField', [], {'max_length': '70'}),
'created_by': ('models.CharField', [], {'max_length': '70'}),
'creation_date': ('models.DateTimeField', [], {'default': 'datetime.datetime(2009, 7, 2, 6, 35, 27, 704298)'}),
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'in_navigation': ('models.BooleanField', [], {'default': 'True', 'blank': 'True', 'db_index': 'True'}),
'level': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'login_required': ('models.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'mark_delete': ('models.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'moderator_state': ('models.SmallIntegerField', [], {'default': '1', 'blank': 'True'}),
'navigation_extenders': ('models.CharField', [], {'blank': 'True', 'max_length': '80', 'null': 'True', 'db_index': 'True'}),
'parent': ('models.ForeignKey', [], {'related_name': "'children'", 'null': 'True', 'to': "orm['cms.PagePublic']", 'blank': 'True'}),
'publication_date': ('models.DateTimeField', [], {'blank': 'True', 'null': 'True', 'db_index': 'True'}),
'publication_end_date': ('models.DateTimeField', [], {'blank': 'True', 'null': 'True', 'db_index': 'True'}),
'published': ('models.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'reverse_id': ('models.CharField', [], {'blank': 'True', 'max_length': '40', 'null': 'True', 'db_index': 'True'}),
'rght': ('models.PositiveIntegerField', [], {'db_index': 'True'}),
'site': ('models.ForeignKey', [], {'to': "orm['sites.Site']"}),
'soft_root': ('models.BooleanField', [], {'default': 'False', 'blank': 'True', 'db_index': 'True'}),
'template': ('models.CharField', [], {'max_length': '100'}),
'tree_id': ('models.PositiveIntegerField', [], {'db_index': 'True'})
},
'sites.site': {
'Meta': {'db_table': "'django_site'"},
'domain': ('models.CharField', [], {'max_length': '100'}),
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'name': ('models.CharField', [], {'max_length': '50'})
},
'text.text': {
'Meta': {'db_table': "'cmsplugin_text'"},
'body': ('models.TextField', [], {}),
'cmsplugin_ptr': ('models.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'})
},
'text.textpublic': {
'body': 'models.TextField()',
'cmspluginpublic_ptr': "models.OneToOneField(to=orm['cms.CMSPluginPublic'], unique=True, primary_key=True)",
'mark_delete': 'models.BooleanField(default=False, blank=True)'
}
}
complete_apps = ['text']
| bsd-3-clause |
aviciimaxwell/odoo | openerp/addons/base/module/module.py | 68 | 37332 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2014 OpenERP S.A. (<http://openerp.com>).
#
# 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/>.
#
##############################################################################
from docutils import nodes
from docutils.core import publish_string
from docutils.transforms import Transform, writer_aux
from docutils.writers.html4css1 import Writer
import importlib
import logging
from operator import attrgetter
import os
import re
import shutil
import tempfile
import urllib
import urllib2
import urlparse
import zipfile
import zipimport
import lxml.html
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO # NOQA
import openerp
import openerp.exceptions
from openerp import modules, tools
from openerp.modules.db import create_categories
from openerp.modules import get_module_resource
from openerp.tools.parse_version import parse_version
from openerp.tools.translate import _
from openerp.osv import osv, orm, fields
from openerp import api, fields as fields2
_logger = logging.getLogger(__name__)
ACTION_DICT = {
'view_type': 'form',
'view_mode': 'form',
'res_model': 'base.module.upgrade',
'target': 'new',
'type': 'ir.actions.act_window',
'nodestroy': True,
}
def backup(path, raise_exception=True):
path = os.path.normpath(path)
if not os.path.exists(path):
if not raise_exception:
return None
raise OSError('path does not exists')
cnt = 1
while True:
bck = '%s~%d' % (path, cnt)
if not os.path.exists(bck):
shutil.move(path, bck)
return bck
cnt += 1
class module_category(osv.osv):
_name = "ir.module.category"
_description = "Application"
def _module_nbr(self, cr, uid, ids, prop, unknow_none, context):
cr.execute('SELECT category_id, COUNT(*) \
FROM ir_module_module \
WHERE category_id IN %(ids)s \
OR category_id IN (SELECT id \
FROM ir_module_category \
WHERE parent_id IN %(ids)s) \
GROUP BY category_id', {'ids': tuple(ids)}
)
result = dict(cr.fetchall())
for id in ids:
cr.execute('select id from ir_module_category where parent_id=%s', (id,))
result[id] = sum([result.get(c, 0) for (c,) in cr.fetchall()],
result.get(id, 0))
return result
_columns = {
'name': fields.char("Name", required=True, translate=True, select=True),
'parent_id': fields.many2one('ir.module.category', 'Parent Application', select=True),
'child_ids': fields.one2many('ir.module.category', 'parent_id', 'Child Applications'),
'module_nr': fields.function(_module_nbr, string='Number of Modules', type='integer'),
'module_ids': fields.one2many('ir.module.module', 'category_id', 'Modules'),
'description': fields.text("Description", translate=True),
'sequence': fields.integer('Sequence'),
'visible': fields.boolean('Visible'),
'xml_id': fields.function(osv.osv.get_external_id, type='char', string="External ID"),
}
_order = 'name'
_defaults = {
'visible': 1,
}
class MyFilterMessages(Transform):
"""
Custom docutils transform to remove `system message` for a document and
generate warnings.
(The standard filter removes them based on some `report_level` passed in
the `settings_override` dictionary, but if we use it, we can't see them
and generate warnings.)
"""
default_priority = 870
def apply(self):
for node in self.document.traverse(nodes.system_message):
_logger.warning("docutils' system message present: %s", str(node))
node.parent.remove(node)
class MyWriter(Writer):
"""
Custom docutils html4ccs1 writer that doesn't add the warnings to the
output document.
"""
def get_transforms(self):
return [MyFilterMessages, writer_aux.Admonitions]
class module(osv.osv):
_name = "ir.module.module"
_rec_name = "shortdesc"
_description = "Module"
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
res = super(module, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)
result = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'action_server_module_immediate_install')[1]
if view_type == 'form':
if res.get('toolbar',False):
list = [rec for rec in res['toolbar']['action'] if rec.get('id', False) != result]
res['toolbar'] = {'action': list}
return res
@classmethod
def get_module_info(cls, name):
info = {}
try:
info = modules.load_information_from_description_file(name)
except Exception:
_logger.debug('Error when trying to fetch informations for '
'module %s', name, exc_info=True)
return info
def _get_desc(self, cr, uid, ids, field_name=None, arg=None, context=None):
res = dict.fromkeys(ids, '')
for module in self.browse(cr, uid, ids, context=context):
path = get_module_resource(module.name, 'static/description/index.html')
if path:
with tools.file_open(path, 'rb') as desc_file:
doc = desc_file.read()
html = lxml.html.document_fromstring(doc)
for element, attribute, link, pos in html.iterlinks():
if element.get('src') and not '//' in element.get('src') and not 'static/' in element.get('src'):
element.set('src', "/%s/static/description/%s" % (module.name, element.get('src')))
res[module.id] = lxml.html.tostring(html)
else:
overrides = {
'embed_stylesheet': False,
'doctitle_xform': False,
'output_encoding': 'unicode',
'xml_declaration': False,
}
output = publish_string(source=module.description or '', settings_overrides=overrides, writer=MyWriter())
res[module.id] = output
return res
def _get_latest_version(self, cr, uid, ids, field_name=None, arg=None, context=None):
default_version = modules.adapt_version('1.0')
res = dict.fromkeys(ids, default_version)
for m in self.browse(cr, uid, ids):
res[m.id] = self.get_module_info(m.name).get('version', default_version)
return res
def _get_views(self, cr, uid, ids, field_name=None, arg=None, context=None):
res = {}
model_data_obj = self.pool.get('ir.model.data')
dmodels = []
if field_name is None or 'views_by_module' in field_name:
dmodels.append('ir.ui.view')
if field_name is None or 'reports_by_module' in field_name:
dmodels.append('ir.actions.report.xml')
if field_name is None or 'menus_by_module' in field_name:
dmodels.append('ir.ui.menu')
assert dmodels, "no models for %s" % field_name
for module_rec in self.browse(cr, uid, ids, context=context):
res_mod_dic = res[module_rec.id] = {
'menus_by_module': [],
'reports_by_module': [],
'views_by_module': []
}
# Skip uninstalled modules below, no data to find anyway.
if module_rec.state not in ('installed', 'to upgrade', 'to remove'):
continue
# then, search and group ir.model.data records
imd_models = dict([(m, []) for m in dmodels])
imd_ids = model_data_obj.search(cr, uid, [
('module', '=', module_rec.name),
('model', 'in', tuple(dmodels))
])
for imd_res in model_data_obj.read(cr, uid, imd_ids, ['model', 'res_id'], context=context):
imd_models[imd_res['model']].append(imd_res['res_id'])
def browse(model):
M = self.pool[model]
# as this method is called before the module update, some xmlid may be invalid at this stage
# explictly filter records before reading them
ids = M.exists(cr, uid, imd_models.get(model, []), context)
return M.browse(cr, uid, ids, context)
def format_view(v):
aa = v.inherit_id and '* INHERIT ' or ''
return '%s%s (%s)' % (aa, v.name, v.type)
res_mod_dic['views_by_module'] = map(format_view, browse('ir.ui.view'))
res_mod_dic['reports_by_module'] = map(attrgetter('name'), browse('ir.actions.report.xml'))
res_mod_dic['menus_by_module'] = map(attrgetter('complete_name'), browse('ir.ui.menu'))
for key in res.iterkeys():
for k, v in res[key].iteritems():
res[key][k] = "\n".join(sorted(v))
return res
def _get_icon_image(self, cr, uid, ids, field_name=None, arg=None, context=None):
res = dict.fromkeys(ids, '')
for module in self.browse(cr, uid, ids, context=context):
path = get_module_resource(module.name, 'static', 'description', 'icon.png')
if path:
image_file = tools.file_open(path, 'rb')
try:
res[module.id] = image_file.read().encode('base64')
finally:
image_file.close()
return res
_columns = {
'name': fields.char("Technical Name", readonly=True, required=True, select=True),
'category_id': fields.many2one('ir.module.category', 'Category', readonly=True, select=True),
'shortdesc': fields.char('Module Name', readonly=True, translate=True),
'summary': fields.char('Summary', readonly=True, translate=True),
'description': fields.text("Description", readonly=True, translate=True),
'description_html': fields.function(_get_desc, string='Description HTML', type='html', method=True, readonly=True),
'author': fields.char("Author", readonly=True),
'maintainer': fields.char('Maintainer', readonly=True),
'contributors': fields.text('Contributors', readonly=True),
'website': fields.char("Website", readonly=True),
# attention: Incorrect field names !!
# installed_version refers the latest version (the one on disk)
# latest_version refers the installed version (the one in database)
# published_version refers the version available on the repository
'installed_version': fields.function(_get_latest_version, string='Latest Version', type='char'),
'latest_version': fields.char('Installed Version', readonly=True),
'published_version': fields.char('Published Version', readonly=True),
'url': fields.char('URL', readonly=True),
'sequence': fields.integer('Sequence'),
'dependencies_id': fields.one2many('ir.module.module.dependency', 'module_id', 'Dependencies', readonly=True),
'auto_install': fields.boolean('Automatic Installation',
help='An auto-installable module is automatically installed by the '
'system when all its dependencies are satisfied. '
'If the module has no dependency, it is always installed.'),
'state': fields.selection([
('uninstallable', 'Not Installable'),
('uninstalled', 'Not Installed'),
('installed', 'Installed'),
('to upgrade', 'To be upgraded'),
('to remove', 'To be removed'),
('to install', 'To be installed')
], string='Status', readonly=True, select=True),
'demo': fields.boolean('Demo Data', readonly=True),
'license': fields.selection([
('GPL-2', 'GPL Version 2'),
('GPL-2 or any later version', 'GPL-2 or later version'),
('GPL-3', 'GPL Version 3'),
('GPL-3 or any later version', 'GPL-3 or later version'),
('AGPL-3', 'Affero GPL-3'),
('LGPL-3', 'LGPL Version 3'),
('Other OSI approved licence', 'Other OSI Approved Licence'),
('Other proprietary', 'Other Proprietary')
], string='License', readonly=True),
'menus_by_module': fields.function(_get_views, string='Menus', type='text', multi="meta", store=True),
'reports_by_module': fields.function(_get_views, string='Reports', type='text', multi="meta", store=True),
'views_by_module': fields.function(_get_views, string='Views', type='text', multi="meta", store=True),
'application': fields.boolean('Application', readonly=True),
'icon': fields.char('Icon URL'),
'icon_image': fields.function(_get_icon_image, string='Icon', type="binary"),
}
_defaults = {
'state': 'uninstalled',
'sequence': 100,
'demo': False,
'license': 'AGPL-3',
}
_order = 'sequence,name'
def _name_uniq_msg(self, cr, uid, ids, context=None):
return _('The name of the module must be unique !')
_sql_constraints = [
('name_uniq', 'UNIQUE (name)', _name_uniq_msg),
]
def unlink(self, cr, uid, ids, context=None):
if not ids:
return True
if isinstance(ids, (int, long)):
ids = [ids]
mod_names = []
for mod in self.read(cr, uid, ids, ['state', 'name'], context):
if mod['state'] in ('installed', 'to upgrade', 'to remove', 'to install'):
raise orm.except_orm(_('Error'), _('You try to remove a module that is installed or will be installed'))
mod_names.append(mod['name'])
#Removing the entry from ir_model_data
#ids_meta = self.pool.get('ir.model.data').search(cr, uid, [('name', '=', 'module_meta_information'), ('module', 'in', mod_names)])
#if ids_meta:
# self.pool.get('ir.model.data').unlink(cr, uid, ids_meta, context)
return super(module, self).unlink(cr, uid, ids, context=context)
@staticmethod
def _check_external_dependencies(terp):
depends = terp.get('external_dependencies')
if not depends:
return
for pydep in depends.get('python', []):
try:
importlib.import_module(pydep)
except ImportError:
raise ImportError('No module named %s' % (pydep,))
for binary in depends.get('bin', []):
if tools.find_in_path(binary) is None:
raise Exception('Unable to find %r in path' % (binary,))
@classmethod
def check_external_dependencies(cls, module_name, newstate='to install'):
terp = cls.get_module_info(module_name)
try:
cls._check_external_dependencies(terp)
except Exception, e:
if newstate == 'to install':
msg = _('Unable to install module "%s" because an external dependency is not met: %s')
elif newstate == 'to upgrade':
msg = _('Unable to upgrade module "%s" because an external dependency is not met: %s')
else:
msg = _('Unable to process module "%s" because an external dependency is not met: %s')
raise orm.except_orm(_('Error'), msg % (module_name, e.args[0]))
@api.multi
def state_update(self, newstate, states_to_update, level=100):
if level < 1:
raise orm.except_orm(_('Error'), _('Recursion error in modules dependencies !'))
# whether some modules are installed with demo data
demo = False
for module in self:
# determine dependency modules to update/others
update_mods, ready_mods = self.browse(), self.browse()
for dep in module.dependencies_id:
if dep.state == 'unknown':
raise orm.except_orm(_('Error'), _("You try to install module '%s' that depends on module '%s'.\nBut the latter module is not available in your system.") % (module.name, dep.name,))
if dep.depend_id.state == newstate:
ready_mods += dep.depend_id
else:
update_mods += dep.depend_id
# update dependency modules that require it, and determine demo for module
update_demo = update_mods.state_update(newstate, states_to_update, level=level-1)
module_demo = module.demo or update_demo or any(mod.demo for mod in ready_mods)
demo = demo or module_demo
# check dependencies and update module itself
self.check_external_dependencies(module.name, newstate)
if module.state in states_to_update:
module.write({'state': newstate, 'demo': module_demo})
return demo
def button_install(self, cr, uid, ids, context=None):
# Mark the given modules to be installed.
self.state_update(cr, uid, ids, 'to install', ['uninstalled'], context=context)
# Mark (recursively) the newly satisfied modules to also be installed
# Select all auto-installable (but not yet installed) modules.
domain = [('state', '=', 'uninstalled'), ('auto_install', '=', True)]
uninstalled_ids = self.search(cr, uid, domain, context=context)
uninstalled_modules = self.browse(cr, uid, uninstalled_ids, context=context)
# Keep those with:
# - all dependencies satisfied (installed or to be installed),
# - at least one dependency being 'to install'
satisfied_states = frozenset(('installed', 'to install', 'to upgrade'))
def all_depencies_satisfied(m):
states = set(d.state for d in m.dependencies_id)
return states.issubset(satisfied_states) and ('to install' in states)
to_install_modules = filter(all_depencies_satisfied, uninstalled_modules)
to_install_ids = map(lambda m: m.id, to_install_modules)
# Mark them to be installed.
if to_install_ids:
self.button_install(cr, uid, to_install_ids, context=context)
return dict(ACTION_DICT, name=_('Install'))
def button_immediate_install(self, cr, uid, ids, context=None):
""" Installs the selected module(s) immediately and fully,
returns the next res.config action to execute
:param ids: identifiers of the modules to install
:returns: next res.config item to execute
:rtype: dict[str, object]
"""
return self._button_immediate_function(cr, uid, ids, self.button_install, context=context)
def button_install_cancel(self, cr, uid, ids, context=None):
self.write(cr, uid, ids, {'state': 'uninstalled', 'demo': False})
return True
def module_uninstall(self, cr, uid, ids, context=None):
"""Perform the various steps required to uninstall a module completely
including the deletion of all database structures created by the module:
tables, columns, constraints, etc."""
ir_model_data = self.pool.get('ir.model.data')
modules_to_remove = [m.name for m in self.browse(cr, uid, ids, context)]
ir_model_data._module_data_uninstall(cr, uid, modules_to_remove, context)
self.write(cr, uid, ids, {'state': 'uninstalled', 'latest_version': False})
return True
def downstream_dependencies(self, cr, uid, ids, known_dep_ids=None,
exclude_states=['uninstalled', 'uninstallable', 'to remove'],
context=None):
"""Return the ids of all modules that directly or indirectly depend
on the given module `ids`, and that satisfy the `exclude_states`
filter"""
if not ids:
return []
known_dep_ids = set(known_dep_ids or [])
cr.execute('''SELECT DISTINCT m.id
FROM
ir_module_module_dependency d
JOIN
ir_module_module m ON (d.module_id=m.id)
WHERE
d.name IN (SELECT name from ir_module_module where id in %s) AND
m.state NOT IN %s AND
m.id NOT IN %s ''',
(tuple(ids), tuple(exclude_states), tuple(known_dep_ids or ids)))
new_dep_ids = set([m[0] for m in cr.fetchall()])
missing_mod_ids = new_dep_ids - known_dep_ids
known_dep_ids |= new_dep_ids
if missing_mod_ids:
known_dep_ids |= set(self.downstream_dependencies(cr, uid, list(missing_mod_ids),
known_dep_ids, exclude_states, context))
return list(known_dep_ids)
def _button_immediate_function(self, cr, uid, ids, function, context=None):
function(cr, uid, ids, context=context)
cr.commit()
api.Environment.reset()
registry = openerp.modules.registry.RegistryManager.new(cr.dbname, update_module=True)
config = registry['res.config'].next(cr, uid, [], context=context) or {}
if config.get('type') not in ('ir.actions.act_window_close',):
return config
# reload the client; open the first available root menu
menu_obj = registry['ir.ui.menu']
menu_ids = menu_obj.search(cr, uid, [('parent_id', '=', False)], context=context)
return {
'type': 'ir.actions.client',
'tag': 'reload',
'params': {'menu_id': menu_ids and menu_ids[0] or False}
}
#TODO remove me in master, not called anymore
def button_immediate_uninstall(self, cr, uid, ids, context=None):
"""
Uninstall the selected module(s) immediately and fully,
returns the next res.config action to execute
"""
return self._button_immediate_function(cr, uid, ids, self.button_uninstall, context=context)
def button_uninstall(self, cr, uid, ids, context=None):
if any(m.name == 'base' for m in self.browse(cr, uid, ids, context=context)):
raise orm.except_orm(_('Error'), _("The `base` module cannot be uninstalled"))
dep_ids = self.downstream_dependencies(cr, uid, ids, context=context)
self.write(cr, uid, ids + dep_ids, {'state': 'to remove'})
return dict(ACTION_DICT, name=_('Uninstall'))
def button_uninstall_cancel(self, cr, uid, ids, context=None):
self.write(cr, uid, ids, {'state': 'installed'})
return True
def button_immediate_upgrade(self, cr, uid, ids, context=None):
"""
Upgrade the selected module(s) immediately and fully,
return the next res.config action to execute
"""
return self._button_immediate_function(cr, uid, ids, self.button_upgrade, context=context)
def button_upgrade(self, cr, uid, ids, context=None):
depobj = self.pool.get('ir.module.module.dependency')
todo = list(self.browse(cr, uid, ids, context=context))
self.update_list(cr, uid)
i = 0
while i < len(todo):
mod = todo[i]
i += 1
if mod.state not in ('installed', 'to upgrade'):
raise orm.except_orm(_('Error'), _("Can not upgrade module '%s'. It is not installed.") % (mod.name,))
self.check_external_dependencies(mod.name, 'to upgrade')
iids = depobj.search(cr, uid, [('name', '=', mod.name)], context=context)
for dep in depobj.browse(cr, uid, iids, context=context):
if dep.module_id.state == 'installed' and dep.module_id not in todo:
todo.append(dep.module_id)
ids = map(lambda x: x.id, todo)
self.write(cr, uid, ids, {'state': 'to upgrade'}, context=context)
to_install = []
for mod in todo:
for dep in mod.dependencies_id:
if dep.state == 'unknown':
raise orm.except_orm(_('Error'), _('You try to upgrade a module that depends on the module: %s.\nBut this module is not available in your system.') % (dep.name,))
if dep.state == 'uninstalled':
ids2 = self.search(cr, uid, [('name', '=', dep.name)])
to_install.extend(ids2)
self.button_install(cr, uid, to_install, context=context)
return dict(ACTION_DICT, name=_('Apply Schedule Upgrade'))
def button_upgrade_cancel(self, cr, uid, ids, context=None):
self.write(cr, uid, ids, {'state': 'installed'})
return True
def button_update_translations(self, cr, uid, ids, context=None):
self.update_translations(cr, uid, ids)
return True
@staticmethod
def get_values_from_terp(terp):
return {
'description': terp.get('description', ''),
'shortdesc': terp.get('name', ''),
'author': terp.get('author', 'Unknown'),
'maintainer': terp.get('maintainer', False),
'contributors': ', '.join(terp.get('contributors', [])) or False,
'website': terp.get('website', ''),
'license': terp.get('license', 'AGPL-3'),
'sequence': terp.get('sequence', 100),
'application': terp.get('application', False),
'auto_install': terp.get('auto_install', False),
'icon': terp.get('icon', False),
'summary': terp.get('summary', ''),
}
def create(self, cr, uid, vals, context=None):
new_id = super(module, self).create(cr, uid, vals, context=context)
module_metadata = {
'name': 'module_%s' % vals['name'],
'model': 'ir.module.module',
'module': 'base',
'res_id': new_id,
'noupdate': True,
}
self.pool['ir.model.data'].create(cr, uid, module_metadata)
return new_id
# update the list of available packages
def update_list(self, cr, uid, context=None):
res = [0, 0] # [update, add]
default_version = modules.adapt_version('1.0')
known_mods = self.browse(cr, uid, self.search(cr, uid, []))
known_mods_names = dict([(m.name, m) for m in known_mods])
# iterate through detected modules and update/create them in db
for mod_name in modules.get_modules():
mod = known_mods_names.get(mod_name)
terp = self.get_module_info(mod_name)
values = self.get_values_from_terp(terp)
if mod:
updated_values = {}
for key in values:
old = getattr(mod, key)
updated = isinstance(values[key], basestring) and tools.ustr(values[key]) or values[key]
if (old or updated) and updated != old:
updated_values[key] = values[key]
if terp.get('installable', True) and mod.state == 'uninstallable':
updated_values['state'] = 'uninstalled'
if parse_version(terp.get('version', default_version)) > parse_version(mod.latest_version or default_version):
res[0] += 1
if updated_values:
self.write(cr, uid, mod.id, updated_values)
else:
mod_path = modules.get_module_path(mod_name)
if not mod_path:
continue
if not terp or not terp.get('installable', True):
continue
id = self.create(cr, uid, dict(name=mod_name, state='uninstalled', **values))
mod = self.browse(cr, uid, id)
res[1] += 1
self._update_dependencies(cr, uid, mod, terp.get('depends', []))
self._update_category(cr, uid, mod, terp.get('category', 'Uncategorized'))
# Trigger load_addons if new module have been discovered it exists on
# wsgi handlers, so they can react accordingly
if tuple(res) != (0, 0):
for handler in openerp.service.wsgi_server.module_handlers:
if hasattr(handler, 'load_addons'):
handler.load_addons()
return res
def download(self, cr, uid, ids, download=True, context=None):
return []
def install_from_urls(self, cr, uid, urls, context=None):
if not self.pool['res.users'].has_group(cr, uid, 'base.group_system'):
raise openerp.exceptions.AccessDenied()
apps_server = urlparse.urlparse(self.get_apps_server(cr, uid, context=context))
OPENERP = openerp.release.product_name.lower()
tmp = tempfile.mkdtemp()
_logger.debug('Install from url: %r', urls)
try:
# 1. Download & unzip missing modules
for module_name, url in urls.items():
if not url:
continue # nothing to download, local version is already the last one
up = urlparse.urlparse(url)
if up.scheme != apps_server.scheme or up.netloc != apps_server.netloc:
raise openerp.exceptions.AccessDenied()
try:
_logger.info('Downloading module `%s` from OpenERP Apps', module_name)
content = urllib2.urlopen(url).read()
except Exception:
_logger.exception('Failed to fetch module %s', module_name)
raise osv.except_osv(_('Module not found'),
_('The `%s` module appears to be unavailable at the moment, please try again later.') % module_name)
else:
zipfile.ZipFile(StringIO(content)).extractall(tmp)
assert os.path.isdir(os.path.join(tmp, module_name))
# 2a. Copy/Replace module source in addons path
for module_name, url in urls.items():
if module_name == OPENERP or not url:
continue # OPENERP is special case, handled below, and no URL means local module
module_path = modules.get_module_path(module_name, downloaded=True, display_warning=False)
bck = backup(module_path, False)
_logger.info('Copy downloaded module `%s` to `%s`', module_name, module_path)
shutil.move(os.path.join(tmp, module_name), module_path)
if bck:
shutil.rmtree(bck)
# 2b. Copy/Replace server+base module source if downloaded
if urls.get(OPENERP, None):
# special case. it contains the server and the base module.
# extract path is not the same
base_path = os.path.dirname(modules.get_module_path('base'))
# copy all modules in the SERVER/openerp/addons directory to the new "openerp" module (except base itself)
for d in os.listdir(base_path):
if d != 'base' and os.path.isdir(os.path.join(base_path, d)):
destdir = os.path.join(tmp, OPENERP, 'addons', d) # XXX 'openerp' subdirectory ?
shutil.copytree(os.path.join(base_path, d), destdir)
# then replace the server by the new "base" module
server_dir = openerp.tools.config['root_path'] # XXX or dirname()
bck = backup(server_dir)
_logger.info('Copy downloaded module `openerp` to `%s`', server_dir)
shutil.move(os.path.join(tmp, OPENERP), server_dir)
#if bck:
# shutil.rmtree(bck)
self.update_list(cr, uid, context=context)
with_urls = [m for m, u in urls.items() if u]
downloaded_ids = self.search(cr, uid, [('name', 'in', with_urls)], context=context)
already_installed = self.search(cr, uid, [('id', 'in', downloaded_ids), ('state', '=', 'installed')], context=context)
to_install_ids = self.search(cr, uid, [('name', 'in', urls.keys()), ('state', '=', 'uninstalled')], context=context)
post_install_action = self.button_immediate_install(cr, uid, to_install_ids, context=context)
if already_installed:
# in this case, force server restart to reload python code...
cr.commit()
openerp.service.server.restart()
return {
'type': 'ir.actions.client',
'tag': 'home',
'params': {'wait': True},
}
return post_install_action
finally:
shutil.rmtree(tmp)
def get_apps_server(self, cr, uid, context=None):
return tools.config.get('apps_server', 'https://apps.openerp.com/apps')
def _update_dependencies(self, cr, uid, mod_browse, depends=None):
if depends is None:
depends = []
existing = set(x.name for x in mod_browse.dependencies_id)
needed = set(depends)
for dep in (needed - existing):
cr.execute('INSERT INTO ir_module_module_dependency (module_id, name) values (%s, %s)', (mod_browse.id, dep))
for dep in (existing - needed):
cr.execute('DELETE FROM ir_module_module_dependency WHERE module_id = %s and name = %s', (mod_browse.id, dep))
self.invalidate_cache(cr, uid, ['dependencies_id'], [mod_browse.id])
def _update_category(self, cr, uid, mod_browse, category='Uncategorized'):
current_category = mod_browse.category_id
current_category_path = []
while current_category:
current_category_path.insert(0, current_category.name)
current_category = current_category.parent_id
categs = category.split('/')
if categs != current_category_path:
cat_id = create_categories(cr, categs)
mod_browse.write({'category_id': cat_id})
def update_translations(self, cr, uid, ids, filter_lang=None, context=None):
if not filter_lang:
res_lang = self.pool.get('res.lang')
lang_ids = res_lang.search(cr, uid, [('translatable', '=', True)])
filter_lang = [lang.code for lang in res_lang.browse(cr, uid, lang_ids)]
elif not isinstance(filter_lang, (list, tuple)):
filter_lang = [filter_lang]
modules = [m.name for m in self.browse(cr, uid, ids) if m.state == 'installed']
self.pool.get('ir.translation').load_module_terms(cr, modules, filter_lang, context=context)
def check(self, cr, uid, ids, context=None):
for mod in self.browse(cr, uid, ids, context=context):
if not mod.description:
_logger.warning('module %s: description is empty !', mod.name)
DEP_STATES = [
('uninstallable', 'Uninstallable'),
('uninstalled', 'Not Installed'),
('installed', 'Installed'),
('to upgrade', 'To be upgraded'),
('to remove', 'To be removed'),
('to install', 'To be installed'),
('unknown', 'Unknown'),
]
class module_dependency(osv.Model):
_name = "ir.module.module.dependency"
_description = "Module dependency"
# the dependency name
name = fields2.Char(index=True)
# the module that depends on it
module_id = fields2.Many2one('ir.module.module', 'Module', ondelete='cascade')
# the module corresponding to the dependency, and its status
depend_id = fields2.Many2one('ir.module.module', 'Dependency', compute='_compute_depend')
state = fields2.Selection(DEP_STATES, string='Status', compute='_compute_state')
@api.multi
@api.depends('name')
def _compute_depend(self):
# retrieve all modules corresponding to the dependency names
names = list(set(dep.name for dep in self))
mods = self.env['ir.module.module'].search([('name', 'in', names)])
# index modules by name, and assign dependencies
name_mod = dict((mod.name, mod) for mod in mods)
for dep in self:
dep.depend_id = name_mod.get(dep.name)
@api.one
@api.depends('depend_id.state')
def _compute_state(self):
self.state = self.depend_id.state or 'unknown'
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
lasote/conan | conans/client/cmd/export_linter.py | 1 | 3405 | import os
import json
import sys
import six
from six import StringIO
from pylint.reporters.json import JSONReporter
from pylint.lint import Run
from conans.client.output import Color
from conans.errors import ConanException
def conan_linter(conanfile_path, out):
apply_lint = os.environ.get("CONAN_RECIPE_LINTER", True)
if not apply_lint or apply_lint == "False":
return
try:
dirname = os.path.dirname(conanfile_path, )
sys.path.append(dirname)
py3_msgs = _lint_py3(conanfile_path)
if py3_msgs:
out.writeln("Python 3 incompatibilities\n ERROR: %s"
% "\n ERROR: ".join(py3_msgs),
front=Color.BRIGHT_MAGENTA)
msgs = _normal_linter(conanfile_path)
if msgs:
out.writeln("Linter warnings\n WARN: %s" % "\n WARN: ".join(msgs),
front=Color.MAGENTA)
pylint_werr = os.environ.get("CONAN_PYLINT_WERR", None)
if pylint_werr and (py3_msgs or msgs):
raise ConanException("Package recipe has linter errors. Please fix them.")
finally:
sys.path.pop()
class _WritableObject(object):
def __init__(self):
self.content = []
def write(self, st):
self.content.append(st)
def _runner(args):
try:
output = _WritableObject()
stdout_ = sys.stderr
stream = StringIO()
sys.stderr = stream
Run(args, reporter=JSONReporter(output), exit=False)
finally:
sys.stderr = stdout_
try:
output = "".join(output.content)
return json.loads(output)
except ValueError:
return []
def _lint_py3(conanfile_path):
if six.PY3:
return
args = ['--py3k', "--reports=no", "--disable=no-absolute-import", "--persistent=no",
conanfile_path]
output_json = _runner(args)
result = []
for msg in output_json:
if msg.get("type") in ("warning", "error"):
result.append("Py3 incompatibility. Line %s: %s"
% (msg.get("line"), msg.get("message")))
return result
def _normal_linter(conanfile_path):
args = ["--reports=no", "--disable=no-absolute-import", "--persistent=no", conanfile_path]
pylintrc = os.environ.get("CONAN_PYLINTRC", None)
if pylintrc:
if not os.path.exists(pylintrc):
raise ConanException("File %s defined by PYLINTRC doesn't exist" % pylintrc)
args.append('--rcfile=%s' % pylintrc)
output_json = _runner(args)
dynamic_fields = ("source_folder", "build_folder", "package_folder", "info_build",
"build_requires", "info")
def _accept_message(msg):
symbol = msg.get("symbol")
text = msg.get("message")
if symbol == "no-member":
for field in dynamic_fields:
if field in text:
return False
if symbol == "not-callable" and "self.copy is not callable" == text:
return False
if symbol in ("bare-except", "broad-except"): # No exception type(s) specified
return False
return True
result = []
for msg in output_json:
if msg.get("type") in ("warning", "error"):
if _accept_message(msg):
result.append("Linter. Line %s: %s" % (msg.get("line"), msg.get("message")))
return result
| mit |
lordmos/blink | Source/bindings/scripts/unstable/v8_callback_interface.py | 1 | 5661 | # Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Generate template values for a callback interface.
FIXME: Not currently used in build.
This is a rewrite of the Perl IDL compiler in Python, but is not complete.
Once it is complete, we will switch all IDL files over to Python at once.
Until then, please work on the Perl IDL compiler.
For details, see bug http://crbug.com/239771
"""
from v8_globals import includes
import v8_types
import v8_utilities
CALLBACK_INTERFACE_H_INCLUDES = set([
'bindings/v8/ActiveDOMCallback.h',
'bindings/v8/DOMWrapperWorld.h',
'bindings/v8/ScopedPersistent.h',
])
CALLBACK_INTERFACE_CPP_INCLUDES = set([
'bindings/v8/V8Binding.h',
'bindings/v8/V8Callback.h',
'core/dom/ExecutionContext.h',
'wtf/Assertions.h',
])
def cpp_to_v8_conversion(idl_type, name):
# FIXME: setting creation_context=v8::Handle<v8::Object>() is wrong,
# as toV8 then implicitly uses the current context, which causes leaks
# between isolate worlds if a different context should be used.
cpp_value_to_v8_value = v8_types.cpp_value_to_v8_value(idl_type, name,
isolate='isolate', creation_context='v8::Handle<v8::Object>()')
return 'v8::Handle<v8::Value> {name}Handle = {cpp_to_v8};'.format(
name=name, cpp_to_v8=cpp_value_to_v8_value)
def cpp_type(idl_type):
# FIXME: remove this function by making callback types consistent
# (always use usual v8_types.cpp_type)
if idl_type == 'DOMString':
return 'const String&'
if idl_type == 'void':
return 'void'
# Callbacks use raw pointers, so used_as_argument=True
usual_cpp_type = v8_types.cpp_type(idl_type, used_as_argument=True)
if usual_cpp_type.startswith('Vector'):
return 'const %s&' % usual_cpp_type
return usual_cpp_type
def generate_callback_interface(callback_interface):
includes.clear()
includes.update(CALLBACK_INTERFACE_CPP_INCLUDES)
name = callback_interface.name
methods = [generate_method(operation)
for operation in callback_interface.operations]
template_contents = {
'conditional_string': v8_utilities.conditional_string(callback_interface),
'cpp_class': name,
'v8_class': v8_utilities.v8_class_name(callback_interface),
'header_includes': CALLBACK_INTERFACE_H_INCLUDES,
'methods': methods,
}
return template_contents
def add_includes_for_operation(operation):
v8_types.add_includes_for_type(operation.idl_type)
for argument in operation.arguments:
v8_types.add_includes_for_type(argument.idl_type)
def generate_method(operation):
extended_attributes = operation.extended_attributes
idl_type = operation.idl_type
if idl_type not in ['boolean', 'void']:
raise Exception('We only support callbacks that return boolean or void values.')
is_custom = 'Custom' in extended_attributes
if not is_custom:
add_includes_for_operation(operation)
call_with = extended_attributes.get('CallWith')
call_with_this_handle = v8_utilities.extended_attribute_value_contains(call_with, 'ThisValue')
contents = {
'call_with_this_handle': call_with_this_handle,
'custom': is_custom,
'name': operation.name,
'return_cpp_type': cpp_type(idl_type),
'return_idl_type': idl_type,
}
contents.update(generate_arguments_contents(operation.arguments, call_with_this_handle))
return contents
def generate_arguments_contents(arguments, call_with_this_handle):
def generate_argument(argument):
return {
'name': argument.name,
'cpp_to_v8_conversion': cpp_to_v8_conversion(argument.idl_type, argument.name),
}
argument_declarations = [
'%s %s' % (cpp_type(argument.idl_type), argument.name)
for argument in arguments]
if call_with_this_handle:
argument_declarations.insert(0, 'ScriptValue thisValue')
return {
'argument_declarations': argument_declarations,
'arguments': [generate_argument(argument) for argument in arguments],
'handles': ['%sHandle' % argument.name for argument in arguments],
}
| mit |
vrenaville/OCB | addons/product_expiry/__init__.py | 442 | 1053 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 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 product_expiry
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
pixelated/pixelated-dispatcher | pixelated/provider/docker/__init__.py | 2 | 15096 | #
# Copyright (c) 2014 ThoughtWorks Deutschland GmbH
#
# Pixelated 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.
#
# Pixelated 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 Pixelated. If not, see <http://www.gnu.org/licenses/>.
import io
import os
import signal
from os.path import join, exists
from os import path
import stat
import subprocess
import time
import tempfile
import multiprocessing
import socket
import pkg_resources
import docker
import psutil
import requests
from psutil import Process
import shutil
import json
from pixelated.provider.base_provider import BaseProvider, _mkdir_if_not_exists
from pixelated.common import Watchdog
from pixelated.common import logger
from pixelated.exceptions import InstanceAlreadyRunningError
__author__ = 'fbernitt'
DOCKER_API_VERSION = '1.14'
DOCKER_MEMORY_LIMIT = '300m'
class CredentialsToDockerStdinWriter(object):
__slots__ = ('_docker_url', '_container_id', '_leap_provider', '_user', '_password', '_process')
def __init__(self, docker_url, container_id, leap_provider, user, password):
self._docker_url = docker_url
self._container_id = container_id
self._leap_provider = leap_provider
self._user = user
self._password = password
def start(self):
self._process = multiprocessing.Process(target=self.run)
self._process.daemon = True
self._process.start()
def run(self):
try:
params = {
'stdin': True,
'stream': True,
'stdout': False,
'stderr': False}
client = docker.Client(base_url=self._docker_url, version=DOCKER_API_VERSION)
s = client.attach_socket(container=self._container_id, params=params)
s.send("%s\n" % json.dumps({'leap_provider_hostname': self._leap_provider, 'user': self._user, 'password': self._password}))
s.shutdown(socket.SHUT_WR)
s.close()
except Exception, e:
logger.error('While passing credentials to container %s running on %s: %s' % (self._container_id, self._docker_url, str(e.message)))
def terminate(self):
self._process.terminate()
class TempDir(object):
""" class for temporary directories
creates a (named) directory which is deleted after use.
All files created within the directory are destroyed
Might not work on windows when the files are still opened
"""
def __init__(self, suffix="", prefix="tmp", basedir=None):
self.name = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=basedir)
def __del__(self):
if "name" in self.__dict__:
self.__exit__(None, None, None)
def __enter__(self):
return self.name
def __exit__(self, *errstuff):
return self.dissolve()
def dissolve(self):
"""remove all files and directories created within the tempdir"""
if self.name:
shutil.rmtree(self.name)
self.name = ""
def __str__(self):
if self.name:
return "temporary directory at: %s" % (self.name,)
else:
return "dissolved temporary directory"
class DockerProvider(BaseProvider):
__slots__ = ('_docker_url', '_docker', '_ports', '_adapter', '_leap_provider_hostname', '_leap_provider_x509', '_credentials')
DEFAULT_DOCKER_URL = 'http+unix://var/run/docker.sock'
def __init__(self, adapter, leap_provider_hostname, leap_provider_x509, docker_url=DEFAULT_DOCKER_URL):
super(DockerProvider, self).__init__()
self._docker_url = docker_url
self._docker = docker.Client(base_url=docker_url, version=DOCKER_API_VERSION)
self._ports = set()
self._adapter = adapter
self._leap_provider_hostname = leap_provider_hostname
self._leap_provider_x509 = leap_provider_x509
self._credentials = {}
self._check_docker_connection()
def _check_docker_connection(self):
try:
self._docker.info()
except Exception, e:
logger.error('Failed to talk to docker: %s' % e.message)
raise
def initialize(self):
self._initialize_logger_container()
if not self._image_exists(self._adapter.docker_image_name()):
# build the image
start = time.time()
logger.info('No docker image for %s found! Triggering build.' % self._adapter.app_name())
if '/' in self._adapter.docker_image_name():
self._download_image(self._adapter.docker_image_name())
logger.info('Finished downloading docker image')
else:
if pkg_resources.resource_exists('pixelated.resources', 'init-%s-docker-context.sh' % self._adapter.app_name()):
fileobj = None
content = pkg_resources.resource_string('pixelated.resources', 'init-%s-docker-context.sh' % self._adapter.app_name())
with TempDir() as dir:
filename = join(dir, 'run.sh')
with open(filename, 'w') as fd:
fd.write(content)
fd.close()
os.chmod(filename, stat.S_IRWXU)
subprocess.call([filename], cwd=dir)
path = dir
self._build_image(path, fileobj)
else:
fileobj = io.StringIO(self._dockerfile())
path = None
self._build_image(path, fileobj)
logger.info('Finished image %s build in %d seconds' % ('%s:latest' % self._adapter.docker_image_name(), time.time() - start))
self._initializing = False
def _image_exists(self, docker_image_name):
imgs = self._docker.images()
repo_tag = docker_image_name + ':latest'
for img in imgs:
if repo_tag in img['RepoTags']:
return True
return False
def _download_image(self, docker_image_name):
stream = self._docker.pull(repository=docker_image_name, tag='latest', stream=True)
lines = []
for event in stream:
data = json.loads(event)
if 'status' in data:
logger.debug(data['status'])
lines.append(data['status'])
if 'error' in data:
logger.error('Failed to pull image %s: %s' % (docker_image_name, data['error']))
logger.error('Replaying docker pull output')
for line in lines:
logger.error('Docker output: %s' % line)
logger.error('Terminating process by sending TERM signal')
os.kill(os.getpid(), signal.SIGTERM)
def _build_image(self, path, fileobj):
stream = self._docker.build(path=path, fileobj=fileobj, tag='%s:latest' % self._adapter.docker_image_name())
lines = []
for event in stream:
data = json.loads(event)
if 'stream' in data:
logger.debug(data['stream'])
lines.append(data['stream'])
if 'error' in data:
logger.error('Whoops! Failed to build image: %s' % data['error'])
logger.error('Replaying docker image build output')
for line in lines:
logger.error('Docker output: %s' % line)
logger.error('Terminating process by sending TERM signal')
os.kill(os.getpid(), signal.SIGTERM)
def _initialize_logger_container(self):
LOGGER_IMAGE_NAME = 'pixelated/logspout'
if not self._image_exists(LOGGER_IMAGE_NAME):
logger.info('Logger container not found. Downloading...')
self._download_image(LOGGER_IMAGE_NAME)
logger.info('Finished downloading logger container')
logger_container = self._docker.create_container(
image=LOGGER_IMAGE_NAME + ':latest',
command='syslog://localhost:514?append_tag=.user_agent',
volumes='/tmp/docker.sock',
environment={'HTTP_PORT': '51957'}
)
self._docker.start(
container=logger_container.get('Id'),
network_mode='host',
binds={'/var/run/docker.sock': {
'bind': '/tmp/docker.sock',
'ro': False
}}
)
logger.info('Logger container initialized successfully')
def pass_credentials_to_agent(self, user_config, password):
self._credentials[user_config.username] = password # remember crendentials until agent gets started
def _write_credentials_to_docker_stdin(self, user_config):
if user_config.username not in self._credentials:
return
password = self._credentials[user_config.username]
p = CredentialsToDockerStdinWriter(self._docker_url, user_config.username, self._leap_provider_hostname, user_config.username, password)
p.start()
def kill_process_after_timeout(process):
process.terminate()
Watchdog(5, userHandler=kill_process_after_timeout, args=[p])
def start(self, user_config):
self._ensure_initialized()
name = user_config.username
self._start(user_config)
cm = self._map_container_by_name(all=True)
if name not in cm:
self._setup_instance(user_config, cm)
uid = os.getuid()
c = self._docker.create_container(self._adapter.docker_image_name(), self._adapter.run_command(self._leap_provider_x509), mem_limit=DOCKER_MEMORY_LIMIT, user=uid, name=name, volumes=['/mnt/user'], ports=[self._adapter.port()], environment=self._adapter.environment('/mnt/user'), stdin_open=True)
else:
c = cm[name]
data_path = self._data_path(user_config)
self._add_leap_ca_to_user_data_path(data_path)
port = self._next_available_port()
self._ports.add(port)
self._docker.start(
c,
binds={data_path: {'bind': '/mnt/user', 'ro': False}},
extra_hosts=self._extra_hosts(),
port_bindings={self._adapter.port(): ('127.0.0.1', port)})
self._write_credentials_to_docker_stdin(user_config)
def _extra_hosts(self):
fqdn = socket.getfqdn()
domain = fqdn.split('.', 1)[1] if '.' in fqdn else fqdn
docker_ip = '172.17.42.1'
hostslist = {fqdn: docker_ip, domain: docker_ip, 'api.' + domain: docker_ip, 'nicknym.' + domain: docker_ip}
print hostslist
return hostslist
def _setup_instance(self, user_config, container_map):
data_path = join(user_config.path, 'data')
container_name = '%s_prepare' % self._adapter.app_name()
if container_name not in container_map:
c = self._docker.create_container(self._adapter.docker_image_name(), self._adapter.setup_command(), name=container_name, volumes=['/mnt/user'], environment=self._adapter.environment('/mnt/user'))
else:
c = container_map[container_name]
self._docker.start(c, binds={data_path: {'bind': '/mnt/user', 'ro': False}})
s = self._docker.wait(c)
if s != 0:
raise Exception('Failed to initialize mailbox: %d!' % s)
def _add_leap_ca_to_user_data_path(self, data_path):
if self._leap_provider_x509.has_ca_bundle():
cert_file = self._leap_provider_x509.ca_bundle
if exists(cert_file):
shutil.copyfile(cert_file, join(data_path, 'dispatcher-leap-provider-ca.crt'))
def list_running(self):
self._ensure_initialized()
running = []
for name in self._map_container_by_name().keys():
running.append(name)
return running
def _map_container_by_name(self, all=False):
containers = self._docker.containers(all=all)
names = {}
for c in containers:
name = c['Names'][0][1:] # skip leading slash in container name
names[name] = c
return names
def stop(self, name):
self._stop(name)
if name in self._credentials:
del self._credentials[name]
for cname, c in self._map_container_by_name().iteritems():
if name == cname:
port = self._docker_container_port(name)
try:
self._docker.stop(c, timeout=10)
except requests.exceptions.Timeout:
self._docker.kill(c)
self._ports.remove(port)
return
raise ValueError
def reset_data(self, user_config):
self._ensure_initialized()
if user_config.username in self.list_running():
raise InstanceAlreadyRunningError('Container %s is currently running. Please stop before resetting data!' % user_config.username)
if path.exists(user_config.path):
data_path = self._data_path(user_config)
if path.exists(data_path):
shutil.rmtree(data_path)
else:
raise ValueError('No agent with name %s' % user_config.username)
def _agent_port(self, name):
return self._docker_container_port(name)
def _dockerfile(self):
return unicode(pkg_resources.resource_string('pixelated.resources', 'Dockerfile.%s' % self._adapter.app_name()))
def _docker_container_by_name(self, name):
return self._map_container_by_name()[name]
def _docker_container_port(self, name):
c = self._docker_container_by_name(name)
return c['Ports'][0]['PublicPort']
def _next_available_port(self):
inital_port = 5000
port = inital_port
while port in self._ports:
port += 1
return port
def _used_ports(self):
return self._ports
def memory_usage(self):
self._ensure_initialized()
usage = 0
agents = []
for name, container in self._map_container_by_name().iteritems():
info = self._docker.inspect_container(container)
pid = info['State']['Pid']
process = Process(pid)
try:
mem = process.memory_info()
except AttributeError:
mem = process.get_memory_info()
usage = usage + mem.rss
agents.append({'name': name, 'memory_usage': mem.rss})
avg = usage / len(agents) if len(agents) > 0 else 0
return {'total_usage': usage, 'average_usage': avg, 'agents': agents}
def _free_memory(self):
return psutil.virtual_memory().free
| agpl-3.0 |
sephalon/python-ivi | ivi/agilent/agilentDSO91304A.py | 7 | 1687 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2014 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from .agilent90000 import *
class agilentDSO91304A(agilent90000):
"Agilent Infiniium DSO91304A IVI oscilloscope driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', 'DSO91304A')
super(agilentDSO91304A, self).__init__(*args, **kwargs)
self._analog_channel_count = 4
self._digital_channel_count = 0
self._channel_count = self._analog_channel_count + self._digital_channel_count
self._bandwidth = 13e9
self._init_channels()
| mit |
txemagon/1984 | modules/Telegram-bot-python/telegram/contact.py | 3 | 1903 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Contact."""
from telegram import TelegramObject
class Contact(TelegramObject):
"""This object represents a Telegram Contact.
Attributes:
phone_number (str):
first_name (str):
last_name (str):
user_id (int):
Args:
phone_number (str):
first_name (str):
last_name (Optional[str]):
user_id (Optional[int]):
**kwargs: Arbitrary keyword arguments.
"""
def __init__(self, phone_number, first_name, last_name=None, user_id=None, **kwargs):
# Required
self.phone_number = str(phone_number)
self.first_name = first_name
# Optionals
self.last_name = last_name
self.user_id = user_id
self._id_attrs = (self.phone_number,)
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.Contact:
"""
if not data:
return None
return Contact(**data)
| gpl-3.0 |
balabit/typesafety | scripts/copyright.py | 3 | 6472 | #!/usr/bin/python3
#
# Copyright (c) 2013-2018 Balabit
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
#
import collections
import argparse
import os.path
import datetime
import re
import sys
def load_pattern_file(fn):
res = []
with open(fn) as f:
for line in f:
line = line.split('#', 1)[0].strip()
if not line:
continue
res.append(re.compile(line))
return res
def match_patterns(text, patterns):
return any(pattern.search(text) is not None for pattern in patterns)
THIS_YEAR = datetime.datetime.now().year
BASE_PATH = os.path.dirname(__file__)
EXCLUDE_DIRS = load_pattern_file(os.path.join(BASE_PATH, 'copyright_dirs.exclude'))
EXCLUDE_FILES = load_pattern_file(os.path.join(BASE_PATH, 'copyright_files.exclude'))
with open(os.path.join(BASE_PATH, 'copyright.txt')) as f:
COPYRIGHT_TEXT = f.read()
FILTER_EXTENSION = {'.py', '.sh'}
BEGIN_PATTERN = re.compile(r"^Copyright \(c\) 2013-(20[0-9]{2}) Balabit$")
UPDATE_COPYRIGHT_HEADER = '''
Copyright (c) 2013-{year} Balabit
{copyright}\
'''.format(year=THIS_YEAR, copyright=COPYRIGHT_TEXT)
class CommentError(Exception):
def __init__(self, filename, message):
super().__init__(message)
self.filename = filename
self.message = message
def locate_files(base_path):
for name in os.listdir(base_path):
fullpath = os.path.join(base_path, name)
if os.path.isfile(fullpath):
ext = os.path.splitext(name)[1]
if ext not in FILTER_EXTENSION:
continue
if match_patterns(fullpath, EXCLUDE_FILES):
continue
if os.lstat(fullpath).st_size == 0:
continue
yield fullpath
elif os.path.isdir(fullpath):
if match_patterns(fullpath, EXCLUDE_DIRS):
continue
for res in locate_files(fullpath):
yield res
HeaderComment = collections.namedtuple('HeaderComment', ['begin_line', 'end_line', 'body', 'has_hashbang'])
def get_header_comment(filename):
begin_line = None
end_line = 0
has_hashbang = False
comment = []
with open(filename) as f:
for index, line in enumerate(f):
line = line.strip()
if not line or line[0] != '#':
end_line = index
break
if line[:2].startswith('#!'):
has_hashbang = True
continue
if begin_line is None:
begin_line = index
if line == '#':
comment.append('')
continue
if line[:2] != '# ':
raise CommentError(filename, "Invalid comment line format")
comment.append(line[2:])
if begin_line is None:
begin_line = end_line
return HeaderComment(
begin_line=begin_line,
end_line=end_line,
body=comment,
has_hashbang=has_hashbang
)
def check_file_header(filename):
comment = get_header_comment(filename)
if not comment.body:
raise CommentError(filename, 'Missing copyright header')
if comment.body[0] != '' or comment.body[-1] != '':
raise CommentError(filename, 'Copyright header format invalid')
match = BEGIN_PATTERN.match(comment.body[1])
if match is None:
raise CommentError(filename, 'Copyright header format invalid')
if int(match.group(1)) != THIS_YEAR:
raise CommentError(filename, 'Copyright year in headers invalid')
if '\n'.join(comment.body[2:]) != COPYRIGHT_TEXT:
raise CommentError(filename, 'Copyright text not the expected one')
def update_file_header(filename):
try:
check_file_header(filename)
return
except CommentError:
pass
with open(filename) as f:
data = f.read().split('\n')
header = get_header_comment(filename)
new_header_block = ['# {}'.format(line).rstrip() for line in UPDATE_COPYRIGHT_HEADER.split('\n')]
if not header.body:
# New comment line, add a newline after the block
new_header_block.append('')
data[header.begin_line:header.end_line] = new_header_block
with open(filename, 'w') as f:
f.write('\n'.join(data))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Copyright header manager script')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--update', action='store_true',
help='Update existing headers and add missing ones.')
group.add_argument('--check', action='store_true',
help='Check existence and correctness of the header copyright information.')
parser.add_argument('path', help='Path to check the files in.')
options = parser.parse_args()
rc = 0
if options.check:
header_printed = False
for filename in locate_files(options.path):
try:
check_file_header(filename)
except CommentError as exc:
if not header_printed:
header_printed = True
print('Errors:', file=sys.stderr)
print(' {}: {}'.format(exc.filename, exc.message), file=sys.stderr)
rc = 1
if rc != 0:
print(file=sys.stderr)
print('You should run the following command:', file=sys.stderr)
print(file=sys.stderr)
print(' $ {} --update {}'.format(sys.argv[0], options.path), file=sys.stderr)
print(file=sys.stderr)
elif options.update:
for filename in locate_files(options.path):
update_file_header(filename)
else:
assert False, "Not reachable code"
exit(rc)
| lgpl-2.1 |
FireBladeNooT/Medusa_1_6 | lib/unidecode/x082.py | 252 | 4649 | data = (
'Yao ', # 0x00
'Yu ', # 0x01
'Chong ', # 0x02
'Xi ', # 0x03
'Xi ', # 0x04
'Jiu ', # 0x05
'Yu ', # 0x06
'Yu ', # 0x07
'Xing ', # 0x08
'Ju ', # 0x09
'Jiu ', # 0x0a
'Xin ', # 0x0b
'She ', # 0x0c
'She ', # 0x0d
'Yadoru ', # 0x0e
'Jiu ', # 0x0f
'Shi ', # 0x10
'Tan ', # 0x11
'Shu ', # 0x12
'Shi ', # 0x13
'Tian ', # 0x14
'Dan ', # 0x15
'Pu ', # 0x16
'Pu ', # 0x17
'Guan ', # 0x18
'Hua ', # 0x19
'Tan ', # 0x1a
'Chuan ', # 0x1b
'Shun ', # 0x1c
'Xia ', # 0x1d
'Wu ', # 0x1e
'Zhou ', # 0x1f
'Dao ', # 0x20
'Gang ', # 0x21
'Shan ', # 0x22
'Yi ', # 0x23
'[?] ', # 0x24
'Pa ', # 0x25
'Tai ', # 0x26
'Fan ', # 0x27
'Ban ', # 0x28
'Chuan ', # 0x29
'Hang ', # 0x2a
'Fang ', # 0x2b
'Ban ', # 0x2c
'Que ', # 0x2d
'Hesaki ', # 0x2e
'Zhong ', # 0x2f
'Jian ', # 0x30
'Cang ', # 0x31
'Ling ', # 0x32
'Zhu ', # 0x33
'Ze ', # 0x34
'Duo ', # 0x35
'Bo ', # 0x36
'Xian ', # 0x37
'Ge ', # 0x38
'Chuan ', # 0x39
'Jia ', # 0x3a
'Lu ', # 0x3b
'Hong ', # 0x3c
'Pang ', # 0x3d
'Xi ', # 0x3e
'[?] ', # 0x3f
'Fu ', # 0x40
'Zao ', # 0x41
'Feng ', # 0x42
'Li ', # 0x43
'Shao ', # 0x44
'Yu ', # 0x45
'Lang ', # 0x46
'Ting ', # 0x47
'[?] ', # 0x48
'Wei ', # 0x49
'Bo ', # 0x4a
'Meng ', # 0x4b
'Nian ', # 0x4c
'Ju ', # 0x4d
'Huang ', # 0x4e
'Shou ', # 0x4f
'Zong ', # 0x50
'Bian ', # 0x51
'Mao ', # 0x52
'Die ', # 0x53
'[?] ', # 0x54
'Bang ', # 0x55
'Cha ', # 0x56
'Yi ', # 0x57
'Sao ', # 0x58
'Cang ', # 0x59
'Cao ', # 0x5a
'Lou ', # 0x5b
'Dai ', # 0x5c
'Sori ', # 0x5d
'Yao ', # 0x5e
'Tong ', # 0x5f
'Yofune ', # 0x60
'Dang ', # 0x61
'Tan ', # 0x62
'Lu ', # 0x63
'Yi ', # 0x64
'Jie ', # 0x65
'Jian ', # 0x66
'Huo ', # 0x67
'Meng ', # 0x68
'Qi ', # 0x69
'Lu ', # 0x6a
'Lu ', # 0x6b
'Chan ', # 0x6c
'Shuang ', # 0x6d
'Gen ', # 0x6e
'Liang ', # 0x6f
'Jian ', # 0x70
'Jian ', # 0x71
'Se ', # 0x72
'Yan ', # 0x73
'Fu ', # 0x74
'Ping ', # 0x75
'Yan ', # 0x76
'Yan ', # 0x77
'Cao ', # 0x78
'Cao ', # 0x79
'Yi ', # 0x7a
'Le ', # 0x7b
'Ting ', # 0x7c
'Qiu ', # 0x7d
'Ai ', # 0x7e
'Nai ', # 0x7f
'Tiao ', # 0x80
'Jiao ', # 0x81
'Jie ', # 0x82
'Peng ', # 0x83
'Wan ', # 0x84
'Yi ', # 0x85
'Chai ', # 0x86
'Mian ', # 0x87
'Mie ', # 0x88
'Gan ', # 0x89
'Qian ', # 0x8a
'Yu ', # 0x8b
'Yu ', # 0x8c
'Shuo ', # 0x8d
'Qiong ', # 0x8e
'Tu ', # 0x8f
'Xia ', # 0x90
'Qi ', # 0x91
'Mang ', # 0x92
'Zi ', # 0x93
'Hui ', # 0x94
'Sui ', # 0x95
'Zhi ', # 0x96
'Xiang ', # 0x97
'Bi ', # 0x98
'Fu ', # 0x99
'Tun ', # 0x9a
'Wei ', # 0x9b
'Wu ', # 0x9c
'Zhi ', # 0x9d
'Qi ', # 0x9e
'Shan ', # 0x9f
'Wen ', # 0xa0
'Qian ', # 0xa1
'Ren ', # 0xa2
'Fou ', # 0xa3
'Kou ', # 0xa4
'Jie ', # 0xa5
'Lu ', # 0xa6
'Xu ', # 0xa7
'Ji ', # 0xa8
'Qin ', # 0xa9
'Qi ', # 0xaa
'Yuan ', # 0xab
'Fen ', # 0xac
'Ba ', # 0xad
'Rui ', # 0xae
'Xin ', # 0xaf
'Ji ', # 0xb0
'Hua ', # 0xb1
'Hua ', # 0xb2
'Fang ', # 0xb3
'Wu ', # 0xb4
'Jue ', # 0xb5
'Gou ', # 0xb6
'Zhi ', # 0xb7
'Yun ', # 0xb8
'Qin ', # 0xb9
'Ao ', # 0xba
'Chu ', # 0xbb
'Mao ', # 0xbc
'Ya ', # 0xbd
'Fei ', # 0xbe
'Reng ', # 0xbf
'Hang ', # 0xc0
'Cong ', # 0xc1
'Yin ', # 0xc2
'You ', # 0xc3
'Bian ', # 0xc4
'Yi ', # 0xc5
'Susa ', # 0xc6
'Wei ', # 0xc7
'Li ', # 0xc8
'Pi ', # 0xc9
'E ', # 0xca
'Xian ', # 0xcb
'Chang ', # 0xcc
'Cang ', # 0xcd
'Meng ', # 0xce
'Su ', # 0xcf
'Yi ', # 0xd0
'Yuan ', # 0xd1
'Ran ', # 0xd2
'Ling ', # 0xd3
'Tai ', # 0xd4
'Tiao ', # 0xd5
'Di ', # 0xd6
'Miao ', # 0xd7
'Qiong ', # 0xd8
'Li ', # 0xd9
'Yong ', # 0xda
'Ke ', # 0xdb
'Mu ', # 0xdc
'Pei ', # 0xdd
'Bao ', # 0xde
'Gou ', # 0xdf
'Min ', # 0xe0
'Yi ', # 0xe1
'Yi ', # 0xe2
'Ju ', # 0xe3
'Pi ', # 0xe4
'Ruo ', # 0xe5
'Ku ', # 0xe6
'Zhu ', # 0xe7
'Ni ', # 0xe8
'Bo ', # 0xe9
'Bing ', # 0xea
'Shan ', # 0xeb
'Qiu ', # 0xec
'Yao ', # 0xed
'Xian ', # 0xee
'Ben ', # 0xef
'Hong ', # 0xf0
'Ying ', # 0xf1
'Zha ', # 0xf2
'Dong ', # 0xf3
'Ju ', # 0xf4
'Die ', # 0xf5
'Nie ', # 0xf6
'Gan ', # 0xf7
'Hu ', # 0xf8
'Ping ', # 0xf9
'Mei ', # 0xfa
'Fu ', # 0xfb
'Sheng ', # 0xfc
'Gu ', # 0xfd
'Bi ', # 0xfe
'Wei ', # 0xff
)
| gpl-3.0 |
theflofly/tensorflow | tensorflow/python/training/supervisor.py | 11 | 43560 | # 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.
# ==============================================================================
"""Training helper that checkpoints models and computes summaries."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import os
import time
from tensorflow.core.framework.summary_pb2 import Summary
from tensorflow.core.util.event_pb2 import SessionLog
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import meta_graph
from tensorflow.python.framework import ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import lookup_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary as _summary
from tensorflow.python.training import coordinator
from tensorflow.python.training import saver as saver_mod
from tensorflow.python.training import session_manager as session_manager_mod
from tensorflow.python.training import training_util
from tensorflow.python.util import deprecation
from tensorflow.python.util.tf_export import tf_export
@tf_export(v1=["train.Supervisor"])
class Supervisor(object):
"""A training helper that checkpoints models and computes summaries.
This class is deprecated. Please use
`tf.train.MonitoredTrainingSession` instead.
The Supervisor is a small wrapper around a `Coordinator`, a `Saver`,
and a `SessionManager` that takes care of common needs of TensorFlow
training programs.
#### Use for a single program
```python
with tf.Graph().as_default():
...add operations to the graph...
# Create a Supervisor that will checkpoint the model in '/tmp/mydir'.
sv = Supervisor(logdir='/tmp/mydir')
# Get a TensorFlow session managed by the supervisor.
with sv.managed_session(FLAGS.master) as sess:
# Use the session to train the graph.
while not sv.should_stop():
sess.run(<my_train_op>)
```
Within the `with sv.managed_session()` block all variables in the graph have
been initialized. In addition, a few services have been started to
checkpoint the model and add summaries to the event log.
If the program crashes and is restarted, the managed session automatically
reinitialize variables from the most recent checkpoint.
The supervisor is notified of any exception raised by one of the services.
After an exception is raised, `should_stop()` returns `True`. In that case
the training loop should also stop. This is why the training loop has to
check for `sv.should_stop()`.
Exceptions that indicate that the training inputs have been exhausted,
`tf.errors.OutOfRangeError`, also cause `sv.should_stop()` to return `True`
but are not re-raised from the `with` block: they indicate a normal
termination.
#### Use for multiple replicas
To train with replicas you deploy the same program in a `Cluster`.
One of the tasks must be identified as the *chief*: the task that handles
initialization, checkpoints, summaries, and recovery. The other tasks
depend on the *chief* for these services.
The only change you have to do to the single program code is to indicate
if the program is running as the *chief*.
```python
# Choose a task as the chief. This could be based on server_def.task_index,
# or job_def.name, or job_def.tasks. It's entirely up to the end user.
# But there can be only one *chief*.
is_chief = (server_def.task_index == 0)
server = tf.train.Server(server_def)
with tf.Graph().as_default():
...add operations to the graph...
# Create a Supervisor that uses log directory on a shared file system.
# Indicate if you are the 'chief'
sv = Supervisor(logdir='/shared_directory/...', is_chief=is_chief)
# Get a Session in a TensorFlow server on the cluster.
with sv.managed_session(server.target) as sess:
# Use the session to train the graph.
while not sv.should_stop():
sess.run(<my_train_op>)
```
In the *chief* task, the `Supervisor` works exactly as in the first example
above. In the other tasks `sv.managed_session()` waits for the Model to have
been initialized before returning a session to the training code. The
non-chief tasks depend on the chief task for initializing the model.
If one of the tasks crashes and restarts, `managed_session()`
checks if the Model is initialized. If yes, it just creates a session and
returns it to the training code that proceeds normally. If the model needs
to be initialized, the chief task takes care of reinitializing it; the other
tasks just wait for the model to have been initialized.
NOTE: This modified program still works fine as a single program.
The single program marks itself as the chief.
#### What `master` string to use
Whether you are running on your machine or in the cluster you can use the
following values for the --master flag:
* Specifying `''` requests an in-process session that does not use RPC.
* Specifying `'local'` requests a session that uses the RPC-based
"Master interface" to run TensorFlow programs. See
`tf.train.Server.create_local_server` for
details.
* Specifying `'grpc://hostname:port'` requests a session that uses
the RPC interface to a specific host, and also allows the in-process
master to access remote tensorflow workers. Often, it is
appropriate to pass `server.target` (for some `tf.train.Server`
named `server).
#### Advanced use
##### Launching additional services
`managed_session()` launches the Checkpoint and Summary services (threads).
If you need more services to run you can simply launch them in the block
controlled by `managed_session()`.
Example: Start a thread to print losses. We want this thread to run
every 60 seconds, so we launch it with `sv.loop()`.
```python
...
sv = Supervisor(logdir='/tmp/mydir')
with sv.managed_session(FLAGS.master) as sess:
sv.loop(60, print_loss, (sess, ))
while not sv.should_stop():
sess.run(my_train_op)
```
##### Launching fewer services
`managed_session()` launches the "summary" and "checkpoint" threads which use
either the optionally `summary_op` and `saver` passed to the constructor, or
default ones created automatically by the supervisor. If you want to run
your own summary and checkpointing logic, disable these services by passing
`None` to the `summary_op` and `saver` parameters.
Example: Create summaries manually every 100 steps in the chief.
```python
# Create a Supervisor with no automatic summaries.
sv = Supervisor(logdir='/tmp/mydir', is_chief=is_chief, summary_op=None)
# As summary_op was None, managed_session() does not start the
# summary thread.
with sv.managed_session(FLAGS.master) as sess:
for step in xrange(1000000):
if sv.should_stop():
break
if is_chief and step % 100 == 0:
# Create the summary every 100 chief steps.
sv.summary_computed(sess, sess.run(my_summary_op))
else:
# Train normally
sess.run(my_train_op)
```
##### Custom model initialization
`managed_session()` only supports initializing the model by running an
`init_op` or restoring from the latest checkpoint. If you have special
initialization needs, see how to specify a `local_init_op` when creating the
supervisor. You can also use the `SessionManager` directly to create a
session and check if it could be initialized automatically.
"""
# Value to pass for the 'ready_op', 'init_op', 'summary_op', 'saver',
# and 'global_step' parameters of Supervisor.__init__() to indicate that
# the default behavior should be used.
USE_DEFAULT = 0
@deprecation.deprecated(None,
"Please switch to tf.train.MonitoredTrainingSession")
def __init__(self,
graph=None,
ready_op=USE_DEFAULT,
ready_for_local_init_op=USE_DEFAULT,
is_chief=True,
init_op=USE_DEFAULT,
init_feed_dict=None,
local_init_op=USE_DEFAULT,
logdir=None,
summary_op=USE_DEFAULT,
saver=USE_DEFAULT,
global_step=USE_DEFAULT,
save_summaries_secs=120,
save_model_secs=600,
recovery_wait_secs=30,
stop_grace_secs=120,
checkpoint_basename="model.ckpt",
session_manager=None,
summary_writer=USE_DEFAULT,
init_fn=None,
local_init_run_options=None):
"""Create a `Supervisor`.
Args:
graph: A `Graph`. The graph that the model will use. Defaults to the
default `Graph`. The supervisor may add operations to the graph before
creating a session, but the graph should not be modified by the caller
after passing it to the supervisor.
ready_op: 1-D string `Tensor`. This tensor is evaluated by supervisors in
`prepare_or_wait_for_session()` to check if the model is ready to use.
The model is considered ready if it returns an empty array. Defaults to
the tensor returned from `tf.report_uninitialized_variables()` If
`None`, the model is not checked for readiness.
ready_for_local_init_op: 1-D string `Tensor`. This tensor is evaluated by
supervisors in `prepare_or_wait_for_session()` to check if the model is
ready to run the local_init_op.
The model is considered ready if it returns an empty array. Defaults to
`None`. If `None`, the model is not checked for readiness before running
local_init_op.
is_chief: If True, create a chief supervisor in charge of initializing
and restoring the model. If False, create a supervisor that relies
on a chief supervisor for inits and restore.
init_op: `Operation`. Used by chief supervisors to initialize the model
when it can not be recovered. Defaults to an `Operation` that
initializes all global variables. If `None`, no initialization is done
automatically unless you pass a value for `init_fn`, see below.
init_feed_dict: A dictionary that maps `Tensor` objects to feed values.
This feed dictionary will be used when `init_op` is evaluated.
local_init_op: `Operation`. Used by all supervisors to run initializations
that should run for every new supervisor instance. By default these
are table initializers and initializers for local variables.
If `None`, no further per supervisor-instance initialization is
done automatically.
logdir: A string. Optional path to a directory where to checkpoint the
model and log events for the visualizer. Used by chief supervisors.
The directory will be created if it does not exist.
summary_op: An `Operation` that returns a Summary for the event logs.
Used by chief supervisors if a `logdir` was specified. Defaults to the
operation returned from summary.merge_all(). If `None`, summaries are
not computed automatically.
saver: A Saver object. Used by chief supervisors if a `logdir` was
specified. Defaults to the saved returned by Saver().
If `None`, the model is not saved automatically.
global_step: An integer Tensor of size 1 that counts steps. The value
from 'global_step' is used in summaries and checkpoint filenames.
Default to the op named 'global_step' in the graph if it exists, is of
rank 1, size 1, and of type tf.int32 or tf.int64. If `None` the global
step is not recorded in summaries and checkpoint files. Used by chief
supervisors if a `logdir` was specified.
save_summaries_secs: Number of seconds between the computation of
summaries for the event log. Defaults to 120 seconds. Pass 0 to
disable summaries.
save_model_secs: Number of seconds between the creation of model
checkpoints. Defaults to 600 seconds. Pass 0 to disable checkpoints.
recovery_wait_secs: Number of seconds between checks that the model
is ready. Used by supervisors when waiting for a chief supervisor
to initialize or restore the model. Defaults to 30 seconds.
stop_grace_secs: Grace period, in seconds, given to running threads to
stop when `stop()` is called. Defaults to 120 seconds.
checkpoint_basename: The basename for checkpoint saving.
session_manager: `SessionManager`, which manages Session creation and
recovery. If it is `None`, a default `SessionManager` will be created
with the set of arguments passed in for backwards compatibility.
summary_writer: `SummaryWriter` to use or `USE_DEFAULT`. Can be `None`
to indicate that no summaries should be written.
init_fn: Optional callable used to initialize the model. Called
after the optional `init_op` is called. The callable must accept one
argument, the session being initialized.
local_init_run_options: RunOptions to be passed as the SessionManager
local_init_run_options parameter.
Returns:
A `Supervisor`.
Raises:
RuntimeError: If called with eager execution enabled.
@compatibility(eager)
`Supervisor`s are not supported when eager execution is enabled.
@end_compatibility
"""
if context.executing_eagerly():
raise RuntimeError("Supervisors are compatible with eager execution.")
# Set default values of arguments.
if graph is None:
graph = ops.get_default_graph()
with graph.as_default():
self._init_ready_op(
ready_op=ready_op, ready_for_local_init_op=ready_for_local_init_op)
self._init_init_op(init_op=init_op, init_feed_dict=init_feed_dict)
self._init_local_init_op(local_init_op=local_init_op)
self._init_saver(saver=saver)
self._init_summary_op(summary_op=summary_op)
self._init_global_step(global_step=global_step)
self._graph = graph
self._meta_graph_def = meta_graph.create_meta_graph_def(
graph_def=graph.as_graph_def(add_shapes=True),
saver_def=self._saver.saver_def if self._saver else None)
self._is_chief = is_chief
self._coord = coordinator.Coordinator()
self._recovery_wait_secs = recovery_wait_secs
self._stop_grace_secs = stop_grace_secs
self._init_fn = init_fn
self._local_init_run_options = local_init_run_options
# Set all attributes related to checkpointing and writing events to None.
# Afterwards, set them appropriately for chief supervisors, as these are
# the only supervisors that can write checkpoints and events.
self._logdir = None
self._save_summaries_secs = None
self._save_model_secs = None
self._save_path = None
self._summary_writer = None
if self._is_chief:
self._logdir = logdir
self._save_summaries_secs = save_summaries_secs
self._save_model_secs = save_model_secs
if self._logdir:
self._save_path = os.path.join(self._logdir, checkpoint_basename)
if summary_writer is Supervisor.USE_DEFAULT:
if self._logdir:
self._summary_writer = _summary.FileWriter(self._logdir)
else:
self._summary_writer = summary_writer
self._graph_added_to_summary = False
self._init_session_manager(session_manager=session_manager)
self._verify_setup()
# The graph is not allowed to change anymore.
graph.finalize()
def _init_session_manager(self, session_manager=None):
if session_manager is None:
self._session_manager = session_manager_mod.SessionManager(
local_init_op=self._local_init_op,
ready_op=self._ready_op,
ready_for_local_init_op=self._ready_for_local_init_op,
graph=self._graph,
recovery_wait_secs=self._recovery_wait_secs,
local_init_run_options=self._local_init_run_options)
else:
self._session_manager = session_manager
def _get_first_op_from_collection(self, key):
"""Returns the first `Operation` from a collection.
Args:
key: A string collection key.
Returns:
The first Op found in a collection, or `None` if the collection is empty.
"""
try:
op_list = ops.get_collection(key)
if len(op_list) > 1:
logging.info("Found %d %s operations. Returning the first one.",
len(op_list), key)
if op_list:
return op_list[0]
except LookupError:
pass
return None
def _init_ready_op(self,
ready_op=USE_DEFAULT,
ready_for_local_init_op=USE_DEFAULT):
"""Initializes ready_op.
Args:
ready_op: `Tensor` to check if the model is initialized.
If it's set to USE_DEFAULT, creates an op that checks all
the variables are initialized.
ready_for_local_init_op: `Tensor` to check if the model is ready to run
local_init_op.
If it's set to USE_DEFAULT, creates an op that checks all
the global variables are initialized.
"""
if ready_op is Supervisor.USE_DEFAULT:
ready_op = self._get_first_op_from_collection(ops.GraphKeys.READY_OP)
if ready_op is None:
ready_op = variables.report_uninitialized_variables()
ops.add_to_collection(ops.GraphKeys.READY_OP, ready_op)
self._ready_op = ready_op
# ready_for_local_init_op defaults to None for backward compatibility
if ready_for_local_init_op is Supervisor.USE_DEFAULT:
ready_for_local_init_op = self._get_first_op_from_collection(
ops.GraphKeys.READY_FOR_LOCAL_INIT_OP)
self._ready_for_local_init_op = ready_for_local_init_op
def _init_init_op(self, init_op=USE_DEFAULT, init_feed_dict=None):
"""Initializes init_op.
Args:
init_op: `Operation` to initialize the variables. If set to USE_DEFAULT,
create an op that initializes all variables and tables.
init_feed_dict: A dictionary that maps `Tensor` objects to feed values.
This feed dictionary will be used when `init_op` is evaluated.
"""
if init_op is Supervisor.USE_DEFAULT:
init_op = self._get_first_op_from_collection(ops.GraphKeys.INIT_OP)
if init_op is None:
init_op = variables.global_variables_initializer()
ops.add_to_collection(ops.GraphKeys.INIT_OP, init_op)
self._init_op = init_op
self._init_feed_dict = init_feed_dict
def _init_local_init_op(self, local_init_op=USE_DEFAULT):
"""Initializes local_init_op.
Args:
local_init_op: `Operation` run for every new supervisor instance. If set
to USE_DEFAULT, use the first op from the GraphKeys.LOCAL_INIT_OP
collection. If the collection is empty, create an op that initializes
all local variables and all tables.
"""
if local_init_op is Supervisor.USE_DEFAULT:
local_init_op = self._get_first_op_from_collection(
ops.GraphKeys.LOCAL_INIT_OP)
if local_init_op is None:
op_list = [
variables.local_variables_initializer(),
lookup_ops.tables_initializer()
]
if op_list:
local_init_op = control_flow_ops.group(*op_list)
ops.add_to_collection(ops.GraphKeys.LOCAL_INIT_OP, local_init_op)
self._local_init_op = local_init_op
def _init_saver(self, saver=USE_DEFAULT):
"""Initializes saver.
Args:
saver: A `Saver` object. If set to USE_DEFAULT, create one that
saves all the variables.
"""
if saver is Supervisor.USE_DEFAULT:
saver = self._get_first_op_from_collection(ops.GraphKeys.SAVERS)
if saver is None and variables.global_variables():
saver = saver_mod.Saver()
ops.add_to_collection(ops.GraphKeys.SAVERS, saver)
self._saver = saver
def _init_summary_op(self, summary_op=USE_DEFAULT):
"""Initializes summary_op.
Args:
summary_op: An Operation that returns a Summary for the event logs.
If set to USE_DEFAULT, create an op that merges all the summaries.
"""
if summary_op is Supervisor.USE_DEFAULT:
summary_op = self._get_first_op_from_collection(ops.GraphKeys.SUMMARY_OP)
if summary_op is None:
summary_op = _summary.merge_all()
if summary_op is not None:
ops.add_to_collection(ops.GraphKeys.SUMMARY_OP, summary_op)
self._summary_op = summary_op
def _init_global_step(self, global_step=USE_DEFAULT):
"""Initializes global_step.
Args:
global_step: An integer Tensor of size 1 that counts steps. If
set to USE_DEFAULT, creates global_step tensor.
"""
if global_step is Supervisor.USE_DEFAULT:
global_step = self._get_first_op_from_collection(
ops.GraphKeys.GLOBAL_STEP)
if global_step is None:
global_step = self._default_global_step_tensor()
if global_step is not None:
ops.add_to_collection(ops.GraphKeys.GLOBAL_STEP, global_step)
self._global_step = global_step
@property
def is_chief(self):
"""Return True if this is a chief supervisor.
Returns:
A bool.
"""
return self._is_chief
@property
def session_manager(self):
"""Return the SessionManager used by the Supervisor.
Returns:
A SessionManager object.
"""
return self._session_manager
@property
def coord(self):
"""Return the Coordinator used by the Supervisor.
The Coordinator can be useful if you want to run multiple threads
during your training.
Returns:
A Coordinator object.
"""
return self._coord
@property
def init_op(self):
"""Return the Init Op used by the supervisor.
Returns:
An Op or `None`.
"""
return self._init_op
@property
def init_feed_dict(self):
"""Return the feed dictionary used when evaluating the `init_op`.
Returns:
A feed dictionary or `None`.
"""
return self._init_feed_dict
@property
def ready_op(self):
"""Return the Ready Op used by the supervisor.
Returns:
An Op or `None`.
"""
return self._ready_op
@property
def ready_for_local_init_op(self):
return self._ready_for_local_init_op
@property
def summary_writer(self):
"""Return the SummaryWriter used by the chief supervisor.
Returns:
A SummaryWriter.
"""
return self._summary_writer
@property
def summary_op(self):
"""Return the Summary Tensor used by the chief supervisor.
Returns:
A string Tensor for the summary or `None`.
"""
return self._summary_op
@property
def save_summaries_secs(self):
"""Return the delay between summary computations.
Returns:
A timestamp.
"""
return self._save_summaries_secs
@property
def global_step(self):
"""Return the global_step Tensor used by the supervisor.
Returns:
An integer Tensor for the global_step.
"""
return self._global_step
@property
def saver(self):
"""Return the Saver used by the supervisor.
Returns:
A Saver object.
"""
return self._saver
@property
def save_model_secs(self):
"""Return the delay between checkpoints.
Returns:
A timestamp.
"""
return self._save_model_secs
@property
def save_path(self):
"""Return the save path used by the supervisor.
Returns:
A string.
"""
return self._save_path
def _write_graph(self):
"""Writes graph_def to `logdir` and adds it to summary if applicable."""
assert self._is_chief
if self._logdir:
training_util.write_graph(self._graph.as_graph_def(add_shapes=True),
self._logdir, "graph.pbtxt")
if self._summary_writer and not self._graph_added_to_summary:
self._summary_writer.add_graph(self._graph)
self._summary_writer.add_meta_graph(self._meta_graph_def)
self._graph_added_to_summary = True
def start_standard_services(self, sess):
"""Start the standard services for 'sess'.
This starts services in the background. The services started depend
on the parameters to the constructor and may include:
- A Summary thread computing summaries every save_summaries_secs.
- A Checkpoint thread saving the model every save_model_secs.
- A StepCounter thread measure step time.
Args:
sess: A Session.
Returns:
A list of threads that are running the standard services. You can use
the Supervisor's Coordinator to join these threads with:
sv.coord.Join(<list of threads>)
Raises:
RuntimeError: If called with a non-chief Supervisor.
ValueError: If not `logdir` was passed to the constructor as the
services need a log directory.
"""
if not self._is_chief:
raise RuntimeError("Only chief supervisor can start standard services. "
"Because only chief supervisors can write events.")
if not self._logdir:
logging.warning("Standard services need a 'logdir' "
"passed to the SessionManager")
return
if self._global_step is not None and self._summary_writer:
# Only add the session log if we keep track of global step.
# TensorBoard cannot use START message for purging expired events
# if there is no step value.
current_step = training_util.global_step(sess, self._global_step)
self._summary_writer.add_session_log(
SessionLog(status=SessionLog.START),
current_step)
threads = []
if self._save_summaries_secs and self._summary_writer:
if self._summary_op is not None:
threads.append(SVSummaryThread(self, sess))
if self._global_step is not None:
threads.append(SVStepCounterThread(self, sess))
if self.saver and self._save_model_secs:
threads.append(SVTimerCheckpointThread(self, sess))
for t in threads:
t.start()
return threads
def prepare_or_wait_for_session(self, master="", config=None,
wait_for_checkpoint=False,
max_wait_secs=7200,
start_standard_services=True):
"""Make sure the model is ready to be used.
Create a session on 'master', recovering or initializing the model as
needed, or wait for a session to be ready. If running as the chief
and `start_standard_service` is set to True, also call the session
manager to start the standard services.
Args:
master: name of the TensorFlow master to use. See the `tf.Session`
constructor for how this is interpreted.
config: Optional ConfigProto proto used to configure the session,
which is passed as-is to create the session.
wait_for_checkpoint: Whether we should wait for the availability of a
checkpoint before creating Session. Defaults to False.
max_wait_secs: Maximum time to wait for the session to become available.
start_standard_services: Whether to start the standard services and the
queue runners.
Returns:
A Session object that can be used to drive the model.
"""
# For users who recreate the session with prepare_or_wait_for_session(), we
# need to clear the coordinator's stop_event so that threads managed by the
# coordinator can run.
self._coord.clear_stop()
if self._summary_writer:
self._summary_writer.reopen()
if self._is_chief:
sess = self._session_manager.prepare_session(
master, init_op=self.init_op, saver=self.saver,
checkpoint_dir=self._logdir, wait_for_checkpoint=wait_for_checkpoint,
max_wait_secs=max_wait_secs, config=config,
init_feed_dict=self._init_feed_dict, init_fn=self._init_fn)
self._write_graph()
if start_standard_services:
logging.info("Starting standard services.")
self.start_standard_services(sess)
else:
sess = self._session_manager.wait_for_session(master,
config=config,
max_wait_secs=max_wait_secs)
if start_standard_services:
logging.info("Starting queue runners.")
self.start_queue_runners(sess)
return sess
def start_queue_runners(self, sess, queue_runners=None):
"""Start threads for `QueueRunners`.
Note that the queue runners collected in the graph key `QUEUE_RUNNERS`
are already started automatically when you create a session with the
supervisor, so unless you have non-collected queue runners to start
you do not need to call this explicitly.
Args:
sess: A `Session`.
queue_runners: A list of `QueueRunners`. If not specified, we'll use the
list of queue runners gathered in the graph under the key
`GraphKeys.QUEUE_RUNNERS`.
Returns:
The list of threads started for the `QueueRunners`.
Raises:
RuntimeError: If called with eager execution enabled.
@compatibility(eager)
Queues are not compatible with eager execution. To ingest data when eager
execution is enabled, use the `tf.data` API.
@end_compatibility
"""
if context.executing_eagerly():
raise RuntimeError("Queues are not compatible with eager execution.")
if queue_runners is None:
queue_runners = self._graph.get_collection(ops.GraphKeys.QUEUE_RUNNERS)
threads = []
for qr in queue_runners:
threads.extend(qr.create_threads(sess, coord=self._coord, daemon=True,
start=True))
return threads
def loop(self, timer_interval_secs, target, args=None, kwargs=None):
"""Start a LooperThread that calls a function periodically.
If `timer_interval_secs` is None the thread calls `target(*args, **kwargs)`
repeatedly. Otherwise it calls it every `timer_interval_secs`
seconds. The thread terminates when a stop is requested.
The started thread is added to the list of threads managed by the supervisor
so it does not need to be passed to the `stop()` method.
Args:
timer_interval_secs: Number. Time boundaries at which to call `target`.
target: A callable object.
args: Optional arguments to pass to `target` when calling it.
kwargs: Optional keyword arguments to pass to `target` when calling it.
Returns:
The started thread.
"""
looper = coordinator.LooperThread(self._coord, timer_interval_secs,
target=target, args=args, kwargs=kwargs)
looper.start()
return looper
def stop(self,
threads=None,
close_summary_writer=True,
ignore_live_threads=False):
"""Stop the services and the coordinator.
This does not close the session.
Args:
threads: Optional list of threads to join with the coordinator. If
`None`, defaults to the threads running the standard services, the
threads started for `QueueRunners`, and the threads started by the
`loop()` method. To wait on additional threads, pass the
list in this parameter.
close_summary_writer: Whether to close the `summary_writer`. Defaults to
`True` if the summary writer was created by the supervisor, `False`
otherwise.
ignore_live_threads: If `True` ignores threads that remain running after
a grace period when joining threads via the coordinator, instead of
raising a RuntimeError.
"""
self._coord.request_stop()
try:
# coord.join() re-raises the first reported exception; the "finally"
# block ensures that we clean up whether or not an exception was
# reported.
self._coord.join(
threads,
stop_grace_period_secs=self._stop_grace_secs,
ignore_live_threads=ignore_live_threads)
finally:
# Close the writer last, in case one of the running threads was using it.
if close_summary_writer and self._summary_writer:
# Stop messages are not logged with event.step,
# since the session may have already terminated.
self._summary_writer.add_session_log(SessionLog(status=SessionLog.STOP))
self._summary_writer.close()
self._graph_added_to_summary = False
def request_stop(self, ex=None):
"""Request that the coordinator stop the threads.
See `Coordinator.request_stop()`.
Args:
ex: Optional `Exception`, or Python `exc_info` tuple as returned by
`sys.exc_info()`. If this is the first call to `request_stop()` the
corresponding exception is recorded and re-raised from `join()`.
"""
self._coord.request_stop(ex=ex)
def should_stop(self):
"""Check if the coordinator was told to stop.
See `Coordinator.should_stop()`.
Returns:
True if the coordinator was told to stop, False otherwise.
"""
return self._coord.should_stop()
def stop_on_exception(self):
"""Context handler to stop the supervisor when an exception is raised.
See `Coordinator.stop_on_exception()`.
Returns:
A context handler.
"""
return self._coord.stop_on_exception()
def wait_for_stop(self):
"""Block waiting for the coordinator to stop."""
self._coord.wait_for_stop()
def summary_computed(self, sess, summary, global_step=None):
"""Indicate that a summary was computed.
Args:
sess: A `Session` object.
summary: A Summary proto, or a string holding a serialized summary proto.
global_step: Int. global step this summary is associated with. If `None`,
it will try to fetch the current step.
Raises:
TypeError: if 'summary' is not a Summary proto or a string.
RuntimeError: if the Supervisor was created without a `logdir`.
"""
if not self._summary_writer:
raise RuntimeError("Writing a summary requires a summary writer.")
if global_step is None and self.global_step is not None:
global_step = training_util.global_step(sess, self.global_step)
self._summary_writer.add_summary(summary, global_step)
def _default_global_step_tensor(self):
"""Returns the global_step from the default graph.
Returns:
The global step `Tensor` or `None`.
"""
try:
gs = ops.get_default_graph().get_tensor_by_name("global_step:0")
if gs.dtype.base_dtype in [dtypes.int32, dtypes.int64]:
return gs
else:
logging.warning("Found 'global_step' is not an int type: %s", gs.dtype)
return None
except KeyError:
return None
def _verify_setup(self):
"""Check that all is good.
Raises:
ValueError: If something is not good.
"""
# Not running as chief means that replicas are used.
# In that case all Variables must have their device set.
if not self._is_chief:
for op in self._graph.get_operations():
if op.type in ["Variable", "VariableV2"] and not op.device:
raise ValueError("When using replicas, all Variables must have "
"their device set: %s" % op)
# pylint: disable=g-doc-return-or-yield,broad-except
@contextlib.contextmanager
def managed_session(self, master="", config=None,
start_standard_services=True,
close_summary_writer=True):
"""Returns a context manager for a managed session.
This context manager creates and automatically recovers a session. It
optionally starts the standard services that handle checkpoints and
summaries. It monitors exceptions raised from the `with` block or from the
services and stops the supervisor as needed.
The context manager is typically used as follows:
```python
def train():
sv = tf.train.Supervisor(...)
with sv.managed_session(<master>) as sess:
for step in xrange(..):
if sv.should_stop():
break
sess.run(<my training op>)
...do other things needed at each training step...
```
An exception raised from the `with` block or one of the service threads is
raised again when the block exits. This is done after stopping all threads
and closing the session. For example, an `AbortedError` exception, raised
in case of preemption of one of the workers in a distributed model, is
raised again when the block exits.
If you want to retry the training loop in case of preemption you can do it
as follows:
```python
def main(...):
while True
try:
train()
except tf.errors.Aborted:
pass
```
As a special case, exceptions used for control flow, such as
`OutOfRangeError` which reports that input queues are exhausted, are not
raised again from the `with` block: they indicate a clean termination of
the training loop and are considered normal termination.
Args:
master: name of the TensorFlow master to use. See the `tf.Session`
constructor for how this is interpreted.
config: Optional `ConfigProto` proto used to configure the session.
Passed as-is to create the session.
start_standard_services: Whether to start the standard services,
such as checkpoint, summary and step counter.
close_summary_writer: Whether to close the summary writer when
closing the session. Defaults to True.
Returns:
A context manager that yields a `Session` restored from the latest
checkpoint or initialized from scratch if not checkpoint exists. The
session is closed when the `with` block exits.
"""
try:
sess = self.prepare_or_wait_for_session(
master=master, config=config,
start_standard_services=start_standard_services)
yield sess
except Exception as e:
self.request_stop(e)
finally:
try:
# Request all the threads to stop and wait for them to do so. Any
# exception raised by the threads is raised again from stop().
# Passing stop_grace_period_secs is for blocked enqueue/dequeue
# threads which are not checking for `should_stop()`. They
# will be stopped when we close the session further down.
self.stop(close_summary_writer=close_summary_writer)
finally:
# Close the session to finish up all pending calls. We do not care
# about exceptions raised when closing. This takes care of
# blocked enqueue/dequeue calls.
try:
sess.close()
except Exception:
# Silently ignore exceptions raised by close().
pass
# pylint: enable=g-doc-return-or-yield,broad-except
class SVSummaryThread(coordinator.LooperThread):
"""A thread to save summaries on a timer."""
def __init__(self, sv, sess):
"""Create a SVSummaryThread.
Args:
sv: A `Supervisor`.
sess: A `Session`.
"""
super(SVSummaryThread, self).__init__(sv.coord, sv.save_summaries_secs)
self._sv = sv
self._sess = sess
def run_loop(self):
if self._sv.global_step is not None:
summary_strs, global_step = self._sess.run([self._sv.summary_op,
self._sv.global_step])
else:
summary_strs = self._sess.run(self._sv.summary_op)
global_step = None
if self._sv.summary_writer:
logging.info("Recording summary at step %s.", global_step)
self._sv.summary_writer.add_summary(summary_strs, global_step)
class SVStepCounterThread(coordinator.LooperThread):
"""Threads to count steps and measure their duration."""
def __init__(self, sv, sess, step_counter=None):
"""Create a `SVStepCounterThread`.
Args:
sv: A `Supervisor`.
sess: A `Session`.
step_counter: A `Tensor` holding the step counter. By defaults, it uses
sv.global_step.
"""
super(SVStepCounterThread, self).__init__(sv.coord, sv.save_summaries_secs)
self._sv = sv
self._sess = sess
self._last_time = 0.0
self._last_step = 0
step_counter = sv.global_step if step_counter is None else step_counter
self._step_counter = step_counter
self._summary_tag = "%s/sec" % self._step_counter.op.name
def start_loop(self):
self._last_time = time.time()
self._last_step = training_util.global_step(
self._sess, self._step_counter)
def run_loop(self):
# Count the steps.
current_step = training_util.global_step(self._sess, self._step_counter)
added_steps = current_step - self._last_step
self._last_step = current_step
# Measure the elapsed time.
current_time = time.time()
elapsed_time = current_time - self._last_time
self._last_time = current_time
# Reports the number of steps done per second
if elapsed_time > 0.:
steps_per_sec = added_steps / elapsed_time
else:
steps_per_sec = float("inf")
summary = Summary(value=[Summary.Value(tag=self._summary_tag,
simple_value=steps_per_sec)])
if self._sv.summary_writer:
self._sv.summary_writer.add_summary(summary, current_step)
logging.log_first_n(logging.INFO, "%s: %g", 10,
self._summary_tag, steps_per_sec)
class SVTimerCheckpointThread(coordinator.LooperThread):
"""A thread to checkpoint on a timer."""
def __init__(self, sv, sess):
"""Create a `SVTimerCheckpointThread`.
Args:
sv: A `Supervisor`.
sess: A `Session`.
"""
super(SVTimerCheckpointThread, self).__init__(sv.coord, sv.save_model_secs)
self._sv = sv
self._sess = sess
def run_loop(self):
logging.info("Saving checkpoint to path %s", self._sv.save_path)
self._sv.saver.save(self._sess, self._sv.save_path,
global_step=self._sv.global_step)
if self._sv.summary_writer and self._sv.global_step is not None:
current_step = training_util.global_step(self._sess, self._sv.global_step)
self._sv.summary_writer.add_session_log(
SessionLog(status=SessionLog.CHECKPOINT,
checkpoint_path=self._sv.save_path),
current_step)
# TODO(sherrym): All non-PEP8 compliant names will be deprecated shortly.
setattr(Supervisor, "PrepareSession", Supervisor.prepare_or_wait_for_session)
setattr(Supervisor, "StartQueueRunners", Supervisor.start_queue_runners)
setattr(Supervisor, "StartStandardServices", Supervisor.start_standard_services)
setattr(Supervisor, "Stop", Supervisor.stop)
setattr(Supervisor, "RequestStop", Supervisor.request_stop)
setattr(Supervisor, "Loop", Supervisor.loop)
setattr(Supervisor, "ShouldStop", Supervisor.should_stop)
setattr(Supervisor, "StopOnException", Supervisor.stop_on_exception)
setattr(Supervisor, "WaitForStop", Supervisor.wait_for_stop)
setattr(Supervisor, "SummaryComputed", Supervisor.summary_computed)
| apache-2.0 |
mcanthony/nupic | tests/unit/nupic/support/object_json_test.py | 30 | 5618 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# 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 Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""Unit tests for object_json module."""
import datetime
import StringIO
from nupic.data.inference_shifter import InferenceShifter
from nupic.swarming import object_json as json
from nupic.support.unittesthelpers.testcasebase import (TestCaseBase,
unittest)
class TestObjectJson(TestCaseBase):
"""Unit tests for object_json module."""
def testPrimitives(self):
self.assertEqual(json.loads(json.dumps(None)), None)
self.assertEqual(json.loads(json.dumps(True)), True)
self.assertEqual(json.loads(json.dumps(False)), False)
self.assertEqual(json.loads(json.dumps(-5)), -5)
self.assertEqual(json.loads(json.dumps(0)), 0)
self.assertEqual(json.loads(json.dumps(5)), 5)
self.assertEqual(json.loads(json.dumps(7.7)), 7.7)
self.assertEqual(json.loads(json.dumps('hello')), 'hello')
self.assertEqual(json.loads(json.dumps(5L)), 5L)
self.assertEqual(json.loads(json.dumps(u'hello')), u'hello')
self.assertEqual(json.loads(json.dumps([5, 6, 7])), [5, 6, 7])
self.assertEqual(json.loads(json.dumps({'5': 6, '7': 8})), {'5': 6, '7': 8})
def testDates(self):
d = datetime.date(year=2012, month=9, day=25)
serialized = json.dumps(d)
self.assertEqual(serialized,
'{"py/object": "datetime.date", '
'"py/repr": "datetime.date(2012, 9, 25)"}')
deserialized = json.loads(serialized)
self.assertEqual(type(deserialized), datetime.date)
self.assertEqual(deserialized.isoformat(), d.isoformat())
def testDatetimes(self):
d = datetime.datetime(year=2012, month=9, day=25, hour=14, minute=33,
second=8, microsecond=455969)
serialized = json.dumps(d)
self.assertEqual(serialized,
'{"py/object": "datetime.datetime", "py/repr": '
'"datetime.datetime(2012, 9, 25, 14, 33, 8, 455969)"}')
deserialized = json.loads(serialized)
self.assertEqual(type(deserialized), datetime.datetime)
self.assertEqual(deserialized.isoformat(), d.isoformat())
def testDumpsTuple(self):
self.assertEqual(json.dumps((5, 6, 7)), '{"py/tuple": [5, 6, 7]}')
def testTuple(self):
self.assertTupleEqual(json.loads(json.dumps((5, 6, 7))), (5, 6, 7))
def testComplex(self):
self.assertEqual(json.loads(json.dumps(2 + 1j)), 2 + 1j)
def testBasicDumps(self):
d = {'a': 1, 'b': {'c': 2}}
s = json.dumps(d, sort_keys=True)
self.assertEqual(s, '{"a": 1, "b": {"c": 2}}')
def testDumpsWithIndent(self):
d = {'a': 1, 'b': {'c': 2}}
s = json.dumps(d, indent=2, sort_keys=True)
self.assertEqual(s, '{\n "a": 1,\n "b": {\n "c": 2\n }\n}')
def testDump(self):
d = {'a': 1, 'b': {'c': 2}}
f = StringIO.StringIO()
json.dump(d, f)
self.assertEqual(f.getvalue(), '{"a": 1, "b": {"c": 2}}')
def testLoads(self):
s = '{"a": 1, "b": {"c": 2}}'
d = json.loads(s)
self.assertDictEqual(d, {'a': 1, 'b': {'c': 2}})
def testLoadsWithIndent(self):
s = '{\n "a": 1,\n "b": {\n "c": 2\n }\n}'
d = json.loads(s)
self.assertDictEqual(d, {'a': 1, 'b': {'c': 2}})
def testLoad(self):
f = StringIO.StringIO('{"a": 1, "b": {"c": 2}}')
d = json.load(f)
self.assertDictEqual(d, {'a': 1, 'b': {'c': 2}})
def testNonStringKeys(self):
original = {1.1: 1, 5: {(7, 8, 9): {1.1: 5}}}
result = json.loads(json.dumps(original))
self.assertEqual(original, result)
def testDumpsObject(self):
testClass = InferenceShifter()
testClass.a = 5
testClass.b = {'b': (17,)}
encoded = json.dumps(testClass, sort_keys=True)
self.assertEqual(
encoded,
'{"_inferenceBuffer": null, "a": 5, "b": {"b": {"py/tuple": [17]}}, '
'"py/object": "nupic.data.inference_shifter.InferenceShifter"}')
def testObjectWithNonStringKeys(self):
testClass = InferenceShifter()
testClass.a = 5
testClass.b = {(4, 5): (17,)}
encoded = json.dumps(testClass, sort_keys=True)
self.assertEqual(
encoded,
'{"_inferenceBuffer": null, "a": 5, "b": {"py/dict/keys": '
'["{\\"py/tuple\\": [4, 5]}"], "{\\"py/tuple\\": [4, 5]}": '
'{"py/tuple": [17]}}, "py/object": '
'"nupic.data.inference_shifter.InferenceShifter"}')
decoded = json.loads(encoded)
self.assertEqual(decoded.a, 5)
self.assertEqual(type(decoded.b), dict)
self.assertEqual(len(decoded.b.keys()), 1)
self.assertTupleEqual(decoded.b.keys()[0], (4, 5))
self.assertTupleEqual(decoded.b[(4, 5)], (17,))
if __name__ == '__main__':
unittest.main()
| agpl-3.0 |
ludwiktrammer/odoo | addons/event/report/report_event_registration.py | 45 | 3236 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp import models, fields
from openerp import tools
class report_event_registration(models.Model):
"""Events Analysis"""
_name = "report.event.registration"
_order = 'event_date desc'
_auto = False
create_date = fields.Datetime('Creation Date', readonly=True)
event_date = fields.Datetime('Event Date', readonly=True)
event_id = fields.Many2one('event.event', 'Event', required=True)
draft_state = fields.Integer(' # No of Draft Registrations')
cancel_state = fields.Integer(' # No of Cancelled Registrations')
confirm_state = fields.Integer(' # No of Confirmed Registrations')
seats_max = fields.Integer('Max Seats')
nbevent = fields.Integer('Number of Events')
nbregistration = fields.Integer('Number of Registrations')
event_type_id = fields.Many2one('event.type', 'Event Type')
registration_state = fields.Selection([('draft', 'Draft'), ('confirm', 'Confirmed'), ('done', 'Attended'), ('cancel', 'Cancelled')], 'Registration State', readonly=True, required=True)
event_state = fields.Selection([('draft', 'Draft'), ('confirm', 'Confirmed'), ('done', 'Done'), ('cancel', 'Cancelled')], 'Event State', readonly=True, required=True)
user_id = fields.Many2one('res.users', 'Event Responsible', readonly=True)
name_registration = fields.Char('Participant / Contact Name', readonly=True)
company_id = fields.Many2one('res.company', 'Company', readonly=True)
def init(self, cr):
"""Initialize the sql view for the event registration """
tools.drop_view_if_exists(cr, 'report_event_registration')
# TOFIX this request won't select events that have no registration
cr.execute(""" CREATE VIEW report_event_registration AS (
SELECT
e.id::varchar || '/' || coalesce(r.id::varchar,'') AS id,
e.id AS event_id,
e.user_id AS user_id,
r.name AS name_registration,
r.create_date AS create_date,
e.company_id AS company_id,
e.date_begin AS event_date,
count(r.id) AS nbevent,
count(r.event_id) AS nbregistration,
CASE WHEN r.state IN ('draft') THEN count(r.event_id) ELSE 0 END AS draft_state,
CASE WHEN r.state IN ('open','done') THEN count(r.event_id) ELSE 0 END AS confirm_state,
CASE WHEN r.state IN ('cancel') THEN count(r.event_id) ELSE 0 END AS cancel_state,
e.event_type_id AS event_type_id,
e.seats_max AS seats_max,
e.state AS event_state,
r.state AS registration_state
FROM
event_event e
LEFT JOIN event_registration r ON (e.id=r.event_id)
GROUP BY
event_id,
r.id,
registration_state,
event_type_id,
e.id,
e.date_begin,
e.user_id,
event_state,
e.company_id,
e.seats_max,
name_registration
)
""")
| agpl-3.0 |
Stanford-Online/edx-platform | openedx/core/djangoapps/credit/email_utils.py | 13 | 10740 | """
This file contains utility functions which will responsible for sending emails.
"""
import HTMLParser
import logging
import os
import urlparse
import uuid
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.staticfiles import finders
from django.core.cache import cache
from django.core.mail import EmailMessage, SafeMIMEText
from django.urls import reverse
from django.utils.translation import ugettext as _
from edxmako.shortcuts import render_to_string
from edxmako.template import Template
from eventtracking import tracker
from openedx.core.djangoapps.commerce.utils import ecommerce_api_client
from openedx.core.djangoapps.credit.models import CreditConfig, CreditProvider
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from xmodule.modulestore.django import modulestore
log = logging.getLogger(__name__)
def send_credit_notifications(username, course_key):
"""Sends email notification to user on different phases during credit
course e.g., credit eligibility, credit payment etc.
"""
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
log.error('No user with %s exist', username)
return
course = modulestore().get_course(course_key, depth=0)
course_display_name = course.display_name
tracking_context = tracker.get_tracker().resolve_context()
tracking_id = str(tracking_context.get('user_id'))
client_id = str(tracking_context.get('client_id'))
events = '&t=event&ec=email&ea=open'
tracking_pixel = 'https://www.google-analytics.com/collect?v=1&tid' + tracking_id + '&cid' + client_id + events
dashboard_link = _email_url_parser('dashboard')
credit_course_link = _email_url_parser('courses', '?type=credit')
# get attached branded logo
logo_image = cache.get('credit.email.attached-logo')
if logo_image is None:
branded_logo = {
'title': 'Logo',
'path': settings.NOTIFICATION_EMAIL_EDX_LOGO,
'cid': str(uuid.uuid4())
}
logo_image_id = branded_logo['cid']
logo_image = attach_image(branded_logo, 'Header Logo')
if logo_image:
cache.set('credit.email.attached-logo', logo_image, settings.CREDIT_NOTIFICATION_CACHE_TIMEOUT)
else:
# strip enclosing angle brackets from 'logo_image' cache 'Content-ID'
logo_image_id = logo_image.get('Content-ID', '')[1:-1]
providers_names = get_credit_provider_display_names(course_key)
providers_string = make_providers_strings(providers_names)
context = {
'full_name': user.get_full_name(),
'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME),
'course_name': course_display_name,
'branded_logo': logo_image_id,
'dashboard_link': dashboard_link,
'credit_course_link': credit_course_link,
'tracking_pixel': tracking_pixel,
'providers': providers_string,
}
# create the root email message
notification_msg = MIMEMultipart('related')
# add 'alternative' part to root email message to encapsulate the plain and
# HTML versions, so message agents can decide which they want to display.
msg_alternative = MIMEMultipart('alternative')
notification_msg.attach(msg_alternative)
# render the credit notification templates
subject = _(u'Course Credit Eligibility')
if providers_string:
subject = _(u'You are eligible for credit from {providers_string}').format(
providers_string=providers_string
)
# add alternative plain text message
email_body_plain = render_to_string('credit_notifications/credit_eligibility_email.txt', context)
msg_alternative.attach(SafeMIMEText(email_body_plain, _subtype='plain', _charset='utf-8'))
# add alternative html message
email_body_content = cache.get('credit.email.css-email-body')
if email_body_content is None:
html_file_path = file_path_finder('templates/credit_notifications/credit_eligibility_email.html')
if html_file_path:
with open(html_file_path, 'r') as cur_file:
cur_text = cur_file.read()
# use html parser to unescape html characters which are changed
# by the 'pynliner' while adding inline css to html content
html_parser = HTMLParser.HTMLParser()
email_body_content = html_parser.unescape(with_inline_css(cur_text))
# cache the email body content before rendering it since the
# email context will change for each user e.g., 'full_name'
cache.set('credit.email.css-email-body', email_body_content, settings.CREDIT_NOTIFICATION_CACHE_TIMEOUT)
else:
email_body_content = ''
email_body = Template(email_body_content).render(context)
msg_alternative.attach(SafeMIMEText(email_body, _subtype='html', _charset='utf-8'))
# attach logo image
if logo_image:
notification_msg.attach(logo_image)
# add email addresses of sender and receiver
from_address = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)
to_address = user.email
# send the root email message
msg = EmailMessage(subject, '', from_address, [to_address])
msg.attach(notification_msg)
msg.send()
def with_inline_css(html_without_css):
"""Returns html with inline css if the css file path exists
else returns html with out the inline css.
"""
css_filepath = settings.NOTIFICATION_EMAIL_CSS
if not css_filepath.startswith('/'):
css_filepath = file_path_finder(settings.NOTIFICATION_EMAIL_CSS)
if css_filepath:
with open(css_filepath, "r") as _file:
css_content = _file.read()
# pynliner imports cssutils, which has an expensive initialization. All
# told, it can account for 15-20% of "fast" LMS startup (without asset
# compilation). So we're going to load it locally here so that we delay
# that one-time hit until we actually do the (rare) operation that is
# sending a credit notification email.
import pynliner
# insert style tag in the html and run pyliner.
html_with_inline_css = pynliner.fromString('<style>' + css_content + '</style>' + html_without_css)
return html_with_inline_css
return html_without_css
def attach_image(img_dict, filename):
"""
Attach images in the email headers.
"""
img_path = img_dict['path']
if not img_path.startswith('/'):
img_path = file_path_finder(img_path)
if img_path:
with open(img_path, 'rb') as img:
msg_image = MIMEImage(img.read(), name=os.path.basename(img_path))
msg_image.add_header('Content-ID', '<{}>'.format(img_dict['cid']))
msg_image.add_header("Content-Disposition", "inline", filename=filename)
return msg_image
def file_path_finder(path):
"""
Return physical path of file if found.
"""
return finders.FileSystemFinder().find(path)
def _email_url_parser(url_name, extra_param=None):
"""Parse url according to 'SITE_NAME' which will be used in the mail.
Args:
url_name(str): Name of the url to be parsed
extra_param(str): Any extra parameters to be added with url if any
Returns:
str
"""
site_name = configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME)
dashboard_url_path = reverse(url_name) + extra_param if extra_param else reverse(url_name)
dashboard_link_parts = ("https", site_name, dashboard_url_path, '', '', '')
return urlparse.urlunparse(dashboard_link_parts)
def get_credit_provider_display_names(course_key):
"""Get the course information from ecommerce and parse the data to get providers.
Arguments:
course_key (CourseKey): The identifier for the course.
Returns:
List of credit provider display names.
"""
course_id = unicode(course_key)
credit_config = CreditConfig.current()
cache_key = None
provider_names = None
if credit_config.is_cache_enabled:
cache_key = '{key_prefix}.{course_key}'.format(
key_prefix=credit_config.CACHE_KEY, course_key=course_id
)
provider_names = cache.get(cache_key)
if provider_names is not None:
return provider_names
try:
user = User.objects.get(username=settings.ECOMMERCE_SERVICE_WORKER_USERNAME)
response = ecommerce_api_client(user).courses(course_id).get(include_products=1)
except Exception: # pylint: disable=broad-except
log.exception("Failed to receive data from the ecommerce course API for Course ID '%s'.", course_id)
return provider_names
if not response:
log.info("No Course information found from ecommerce API for Course ID '%s'.", course_id)
return provider_names
provider_ids = []
for product in response.get('products'):
provider_ids += [
attr.get('value') for attr in product.get('attribute_values') if attr.get('name') == 'credit_provider'
]
provider_names = []
credit_providers = CreditProvider.get_credit_providers()
for provider in credit_providers:
if provider['id'] in provider_ids:
provider_names.append(provider['display_name'])
if credit_config.is_cache_enabled:
cache.set(cache_key, provider_names, credit_config.cache_ttl)
return provider_names
def make_providers_strings(providers):
"""Get the list of course providers and make them comma seperated string.
Arguments:
providers : List containing the providers names
Returns:
strings containing providers names in readable way .
"""
if not providers:
return None
if len(providers) == 1:
providers_string = providers[0]
elif len(providers) == 2:
# Translators: The join of two university names (e.g., Harvard and MIT).
providers_string = _("{first_provider} and {second_provider}").format(
first_provider=providers[0],
second_provider=providers[1]
)
else:
# Translators: The join of three or more university names. The first of these formatting strings
# represents a comma-separated list of names (e.g., MIT, Harvard, Dartmouth).
providers_string = _("{first_providers}, and {last_provider}").format(
first_providers=u", ".join(providers[:-1]),
last_provider=providers[-1]
)
return providers_string
| agpl-3.0 |
CenturylinkTechnology/ansible-modules-extras | windows/win_uri.py | 11 | 4353 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Corwin Brown <corwin@corwinbrown.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/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
DOCUMENTATION = """
---
module: win_uri
version_added: "2.1"
short_description: Interacts with webservices.
description:
- Interacts with HTTP and HTTPS web services and supports Digest, Basic and WSSE HTTP authentication mechanisms.
options:
url:
description:
- HTTP or HTTPS URL in the form of (http|https)://host.domain:port/path
method:
description:
- The HTTP Method of the request or response.
default: GET
choices:
- GET
- POST
- PUT
- HEAD
- DELETE
- OPTIONS
- PATCH
- TRACE
- CONNECT
- REFRESH
content_type:
description:
- Sets the "Content-Type" header.
body:
description:
- The body of the HTTP request/response to the web service.
headers:
description:
- 'Key Value pairs for headers. Example "Host: www.somesite.com"'
use_basic_parsing:
description:
- This module relies upon 'Invoke-WebRequest', which by default uses the Internet Explorer Engine to parse a webpage. There's an edge-case where if a user hasn't run IE before, this will fail. The only advantage to using the Internet Explorer praser is that you can traverse the DOM in a powershell script. That isn't useful for Ansible, so by default we toggle 'UseBasicParsing'. However, you can toggle that off here.
choices:
- True
- False
default: True
author: Corwin Brown (@blakfeld)
"""
EXAMPLES = """
# Send a GET request and store the output:
---
- name: Perform a GET and Store Output
win_uri:
url: http://www.somesite.com/myendpoint
register: http_output
# Set a HOST header to hit an internal webserver:
---
- name: Hit a Specific Host on the Server
win_uri:
url: http://my.internal.server.com
method: GET
headers:
host: "www.somesite.com"
# Do a HEAD request on an endpoint
---
- name: Perform a HEAD on an Endpoint
win_uri:
url: http://www.somesite.com
method: HEAD
# Post a body to an endpoint
---
- name: POST a Body to an Endpoint
win_uri:
url: http://www.somesite.com
method: POST
body: "{ 'some': 'json' }"
"""
RETURN = """
url:
description: The Target URL
returned: always
type: string
sample: "https://www.ansible.com"
method:
description: The HTTP method used.
returned: always
type: string
sample: "GET"
content_type:
description: The "content-type" header used.
returned: always
type: string
sample: "application/json"
use_basic_parsing:
description: The state of the "use_basic_parsing" flag.
returned: always
type: bool
sample: True
body:
description: The content of the body used
returned: when body is specified
type: string
sample: '{"id":1}'
version_added: "2.3"
status_code:
description: The HTTP Status Code of the response.
returned: success
type: int
sample: 200
status_description:
description: A summery of the status.
returned: success
type: string
stample: "OK"
raw_content:
description: The raw content of the HTTP response.
returned: success
type: string
sample: 'HTTP/1.1 200 OK\nX-XSS-Protection: 1; mode=block\nX-Frame-Options: SAMEORIGIN\nAlternate-Protocol: 443:quic,p=1\nAlt-Svc: quic="www.google.com:443"; ma=2592000; v="30,29,28,27,26,25",quic=":443"; ma=2...'
headers:
description: The Headers of the response.
returned: success
type: dict
sample: {"Content-Type": "application/json"}
raw_content_length:
description: The byte size of the response.
returned: success
type: int
sample: 54447
"""
| gpl-3.0 |
publicRoman/spark | examples/src/main/python/mllib/hypothesis_testing_kolmogorov_smirnov_test_example.py | 128 | 1658 | #
# 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 __future__ import print_function
from pyspark import SparkContext
# $example on$
from pyspark.mllib.stat import Statistics
# $example off$
if __name__ == "__main__":
sc = SparkContext(appName="HypothesisTestingKolmogorovSmirnovTestExample")
# $example on$
parallelData = sc.parallelize([0.1, 0.15, 0.2, 0.3, 0.25])
# run a KS test for the sample versus a standard normal distribution
testResult = Statistics.kolmogorovSmirnovTest(parallelData, "norm", 0, 1)
# summary of the test including the p-value, test statistic, and null hypothesis
# if our p-value indicates significance, we can reject the null hypothesis
# Note that the Scala functionality of calling Statistics.kolmogorovSmirnovTest with
# a lambda to calculate the CDF is not made available in the Python API
print(testResult)
# $example off$
sc.stop()
| apache-2.0 |
romanoid/buck | scripts/jardiffer.py | 4 | 7071 | #!/usr/bin/env python
# Copyright 2018-present Facebook, 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.
# Diffing two jar files can be a surprisingly subtle task. It is possible
# for jar files to differ in packaging, but have the same content (examples:
# when they are zipped using different compresssion levels, or if the
# timestamps for entries differ, or if the ordering inside the jar is
# different.
#
# A common trick to diff two jar files is to unzip their contents to a
# directory and recursively diff the two directories, but this is subtly
# tricky: zip files may have duplicate entries with the same name, in
# which case one must be careful not to allow later entries to overwrite
# earlier entries, since the default Java classloader will only see the
# first entry in the zipfile.
from __future__ import print_function
import argparse
import os
import re
import shutil
import subprocess
import sys
import tempfile
from zipfile import ZipFile
class JarDiffer(object):
def __init__(self, args):
self.parse_args(args)
self.tmpdir = tempfile.mkdtemp()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
shutil.rmtree(self.tmpdir)
def parse_args(self, args):
parser = argparse.ArgumentParser(
prog=args[0],
description="Compares the contents of two jar files.",
add_help=True,
)
parser.add_argument(
"-d",
"--diff-flags",
help="Flags to pass to diff when comparing non-class files",
default="-d",
)
parser.add_argument(
"-p",
"--javap-flags",
help="Flags to pass to javap when comparing class files",
default="-p -s -sysinfo",
)
parser.add_argument(
"-r",
"--raw-javap-output",
help="Show raw (unsanitized) javap output.",
action="store_true",
)
parser.add_argument(
"-o",
"--output",
help="File to direct output (default: stdout)",
type=argparse.FileType("w", 0),
default=sys.stdout,
)
parser.add_argument("jarfile", help="The jar files to compare", nargs=2)
options = parser.parse_args(args[1:])
self.jar1 = options.jarfile[0]
self.jar2 = options.jarfile[1]
self.javap_flags = [f for f in options.javap_flags.split() if f]
self.should_sanitize_javap = not options.raw_javap_output
self.diff_flags = [f for f in options.diff_flags.split() if f]
self.output = options.output
def write_contents(self, index, entry_name, entry_contents):
dest = os.path.join(self.tmpdir, str(index), entry_name)
if not os.path.exists(os.path.dirname(dest)):
os.makedirs(os.path.dirname(dest))
with open(dest, "wb") as f:
f.write(entry_contents)
return os.path.join(str(index), entry_name)
@staticmethod
def sanitize_javap_output(content):
content = re.sub(r"\d+:", "_:", content)
content = re.sub(r"#\d+", "#_", content)
return content
def javap(self, index, entry_name, entry_contents):
flags = self.javap_flags
filename = self.write_contents(index, entry_name, entry_contents)
cmd = ["javap"] + flags + [filename]
output = subprocess.check_output(cmd, cwd=self.tmpdir)
if self.should_sanitize_javap:
output = JarDiffer.sanitize_javap_output(output)
return output
def diff_content(self, entry_name, entry_contents1, entry_contents2):
filename1 = self.write_contents(1, entry_name, entry_contents1)
filename2 = self.write_contents(2, entry_name, entry_contents2)
cmd = ["diff"] + self.diff_flags + [filename1, filename2]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=self.tmpdir)
(stdoutdata, _) = p.communicate()
return p.returncode, stdoutdata
def diff_classes(self, entry_name, entry_contents1, entry_contents2):
javap1 = self.javap(1, entry_name, entry_contents1)
javap2 = self.javap(2, entry_name, entry_contents2)
return self.diff_content(entry_name + ".javap", javap1, javap2)
def diff_zipinfos(self, zipfile1, zipinfo1, zipfile2, zipinfo2):
contents1 = zipfile1.read(zipinfo1)
contents2 = zipfile2.read(zipinfo2)
if contents1 == contents2:
return True
filename = zipinfo1.filename
if filename.endswith(".class"):
returncode, out = self.diff_classes(filename, contents1, contents2)
else:
returncode, out = self.diff_content(filename, contents1, contents2)
if returncode != 0:
print("Files differ: %s\n%s" % (filename, out), file=self.output)
return returncode
@staticmethod
def zipinfo_by_name(zipfile):
result = {}
for zipinfo in zipfile.infolist():
result.setdefault(zipinfo.filename, []).append(zipinfo)
return result
def run(self):
return_code = 0
absjar1 = os.path.abspath(self.jar1)
absjar2 = os.path.abspath(self.jar2)
print("Comparing:\n1: %s\n2: %s" % (absjar1, absjar2), file=sys.stderr)
with ZipFile(absjar1) as zipfile1, ZipFile(absjar2) as zipfile2:
zipinfos1_by_name = JarDiffer.zipinfo_by_name(zipfile1)
zipinfos2_by_name = JarDiffer.zipinfo_by_name(zipfile2)
all_files = sorted(set(zipinfos1_by_name.keys() + zipinfos2_by_name.keys()))
for name in all_files:
zipinfos1 = zipinfos1_by_name.get(name, [])
zipinfos2 = zipinfos2_by_name.get(name, [])
while zipinfos1 or zipinfos2:
if not zipinfos1:
print("Only in %s: %s" % (self.jar2, name), file=self.output)
zipinfos2.pop()
return_code = 1
elif not zipinfos2:
print("Only in %s: %s" % (self.jar1, name), file=self.output)
zipinfos1.pop()
return_code = 1
continue
elif not self.diff_zipinfos(
zipfile1, zipinfos1.pop(), zipfile2, zipinfos2.pop()
):
return_code = 1
return return_code
if __name__ == "__main__":
with JarDiffer(sys.argv) as differ:
differ.run()
| apache-2.0 |
MziRintu/kitsune | kitsune/sumo/helpers.py | 6 | 14962 | import datetime
import json as jsonlib
import re
import urlparse
from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse
from django.http import QueryDict
from django.utils.encoding import smart_str
from django.utils.http import urlencode
from django.utils.tzinfo import LocalTimezone
import bleach
import jinja2
from babel import localedata
from babel.dates import format_date, format_time, format_datetime
from babel.numbers import format_decimal
from jingo import register, env
from jinja2.utils import Markup
from pytz import timezone
from tower import ugettext_lazy as _lazy, ugettext as _, ungettext
from kitsune.sumo import parser
from kitsune.sumo.urlresolvers import reverse
from kitsune.users.models import Profile
from kitsune.wiki.showfor import showfor_data as _showfor_data
class DateTimeFormatError(Exception):
"""Called by the datetimeformat function when receiving invalid format."""
pass
@register.filter
def paginator(pager):
"""Render list of pages."""
return Paginator(pager).render()
@register.filter
def simple_paginator(pager):
t = env.get_template('includes/simple_paginator.html')
return jinja2.Markup(t.render({'pager': pager}))
@register.filter
def quick_paginator(pager):
t = env.get_template('includes/quick_paginator.html')
return jinja2.Markup(t.render({'pager': pager}))
@register.filter
def mobile_paginator(pager):
t = env.get_template('includes/mobile/paginator.html')
return jinja2.Markup(t.render({'pager': pager}))
@register.function
def url(viewname, *args, **kwargs):
"""Helper for Django's ``reverse`` in templates.
Uses sumo's locale-aware reverse."""
locale = kwargs.pop('locale', None)
return reverse(viewname, locale=locale, args=args, kwargs=kwargs)
@register.function
def unlocalized_url(viewname, *args, **kwargs):
"""Helper for Django's ``reverse`` in templates.
Uses django's default reverse."""
return django_reverse(viewname, args=args, kwargs=kwargs)
@register.filter
def urlparams(url_, hash=None, query_dict=None, **query):
"""
Add a fragment and/or query parameters to a URL.
New query params will be appended to exising parameters, except duplicate
names, which will be replaced.
"""
url_ = urlparse.urlparse(url_)
fragment = hash if hash is not None else url_.fragment
q = url_.query
new_query_dict = (QueryDict(smart_str(q), mutable=True) if
q else QueryDict('', mutable=True))
if query_dict:
for k, l in query_dict.lists():
new_query_dict[k] = None # Replace, don't append.
for v in l:
new_query_dict.appendlist(k, v)
for k, v in query.items():
new_query_dict[k] = v # Replace, don't append.
query_string = urlencode([(k, v) for k, l in new_query_dict.lists() for
v in l if v is not None])
new = urlparse.ParseResult(url_.scheme, url_.netloc, url_.path,
url_.params, query_string, fragment)
return new.geturl()
@register.filter
def wiki_to_html(wiki_markup, locale=settings.WIKI_DEFAULT_LANGUAGE,
nofollow=True):
"""Wiki Markup -> HTML jinja2.Markup object"""
return jinja2.Markup(parser.wiki_to_html(wiki_markup, locale=locale,
nofollow=nofollow))
@register.filter
def truncate_question(text, length, longtext=None):
if len(text) > length:
if longtext is None:
longtext = text
stripped_text = bleach.clean(text, tags=[], strip=True)
f = ('<p class="short-text">%s… ' +
'<span class="show-more-link">(' + _('read more') + ')</span>' +
'</p><div class="long-text">%s</div>')
return f % (stripped_text[:length], longtext)
return text
class Paginator(object):
def __init__(self, pager):
self.pager = pager
self.max = 10
self.span = (self.max - 1) / 2
self.page = pager.number
self.num_pages = pager.paginator.num_pages
self.count = pager.paginator.count
pager.page_range = self.range()
pager.dotted_upper = self.num_pages not in pager.page_range
pager.dotted_lower = 1 not in pager.page_range
def range(self):
"""Return a list of page numbers to show in the paginator."""
page, total, span = self.page, self.num_pages, self.span
if total < self.max:
lower, upper = 0, total
elif page < span + 1:
lower, upper = 0, span * 2
elif page > total - span:
lower, upper = total - span * 2, total
else:
lower, upper = page - span, page + span - 1
return range(max(lower + 1, 1), min(total, upper) + 1)
def render(self):
c = {'pager': self.pager, 'num_pages': self.num_pages,
'count': self.count}
t = env.get_template('layout/paginator.html').render(c)
return jinja2.Markup(t)
@register.function
@jinja2.contextfunction
def breadcrumbs(context, items=list(), add_default=True, id=None):
"""
Show a list of breadcrumbs. If url is None, it won't be a link.
Accepts: [(url, label)]
"""
if add_default:
first_crumb = u'Home'
crumbs = [(reverse('home'), _lazy(first_crumb))]
else:
crumbs = []
# add user-defined breadcrumbs
if items:
try:
crumbs += items
except TypeError:
crumbs.append(items)
c = {'breadcrumbs': crumbs, 'id': id}
t = env.get_template('layout/breadcrumbs.html').render(c)
return jinja2.Markup(t)
def _babel_locale(locale):
"""Return the Babel locale code, given a normal one."""
# Babel uses underscore as separator.
return locale.replace('-', '_')
def _contextual_locale(context):
"""Return locale from the context, falling back to a default if invalid."""
request = context.get('request')
locale = request.LANGUAGE_CODE
if not localedata.exists(locale):
locale = settings.LANGUAGE_CODE
return locale
@register.function
@jinja2.contextfunction
def datetimeformat(context, value, format='shortdatetime'):
"""
Returns a formatted date/time using Babel's locale settings. Uses the
timezone from settings.py, if the user has not been authenticated.
"""
if not isinstance(value, datetime.datetime):
# Expecting date value
raise ValueError(
'Unexpected value {value} passed to datetimeformat'.format(
value=value))
request = context.get('request')
default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE)
if value.tzinfo is None:
value = default_tzinfo.localize(value)
new_value = value.astimezone(default_tzinfo)
else:
new_value = value
if 'timezone' not in request.session:
if request.user.is_authenticated():
try:
convert_tzinfo = (Profile.objects.get(user=request.user).timezone or
default_tzinfo)
except (Profile.DoesNotExist, AttributeError):
pass
request.session['timezone'] = convert_tzinfo
else:
convert_tzinfo = request.session['timezone']
convert_value = new_value.astimezone(convert_tzinfo)
locale = _babel_locale(_contextual_locale(context))
# If within a day, 24 * 60 * 60 = 86400s
if format == 'shortdatetime':
# Check if the date is today
today = datetime.datetime.now(tz=convert_tzinfo).toordinal()
if convert_value.toordinal() == today:
formatted = _lazy(u'Today at %s') % format_time(
convert_value, format='short', tzinfo=convert_tzinfo,
locale=locale)
else:
formatted = format_datetime(convert_value,
format='short',
tzinfo=convert_tzinfo,
locale=locale)
elif format == 'longdatetime':
formatted = format_datetime(convert_value, format='long',
tzinfo=convert_tzinfo, locale=locale)
elif format == 'date':
formatted = format_date(convert_value, locale=locale)
elif format == 'time':
formatted = format_time(convert_value, tzinfo=convert_tzinfo,
locale=locale)
elif format == 'datetime':
formatted = format_datetime(convert_value, tzinfo=convert_tzinfo,
locale=locale)
else:
# Unknown format
raise DateTimeFormatError
return jinja2.Markup('<time datetime="%s">%s</time>' %
(convert_value.isoformat(), formatted))
_whitespace_then_break = re.compile(r'[\r\n\t ]+[\r\n]+')
@register.filter
def collapse_linebreaks(text):
"""Replace consecutive CRs and/or LFs with single CRLFs.
CRs or LFs with nothing but whitespace between them are still considered
consecutive.
As a nice side effect, also strips trailing whitespace from lines that are
followed by line breaks.
"""
# I previously tried an heuristic where we'd cut the number of linebreaks
# in half until there remained at least one lone linebreak in the text.
# However, about:support in some versions of Firefox does yield some hard-
# wrapped paragraphs using single linebreaks.
return _whitespace_then_break.sub('\r\n', text)
@register.filter
def json(s):
return jsonlib.dumps(s)
@register.function
@jinja2.contextfunction
def number(context, n):
"""Return the localized representation of an integer or decimal.
For None, print nothing.
"""
if n is None:
return ''
return format_decimal(n, locale=_babel_locale(_contextual_locale(context)))
@register.filter
def timesince(d, now=None):
"""Take two datetime objects and return the time between d and now as a
nicely formatted string, e.g. "10 minutes". If d is None or occurs after
now, return ''.
Units used are years, months, weeks, days, hours, and minutes. Seconds and
microseconds are ignored. Just one unit is displayed. For example,
"2 weeks" and "1 year" are possible outputs, but "2 weeks, 3 days" and "1
year, 5 months" are not.
Adapted from django.utils.timesince to have better i18n (not assuming
commas as list separators and including "ago" so order of words isn't
assumed), show only one time unit, and include seconds.
"""
if d is None:
return u''
chunks = [
(60 * 60 * 24 * 365, lambda n: ungettext('%(number)d year ago',
'%(number)d years ago', n)),
(60 * 60 * 24 * 30, lambda n: ungettext('%(number)d month ago',
'%(number)d months ago', n)),
(60 * 60 * 24 * 7, lambda n: ungettext('%(number)d week ago',
'%(number)d weeks ago', n)),
(60 * 60 * 24, lambda n: ungettext('%(number)d day ago',
'%(number)d days ago', n)),
(60 * 60, lambda n: ungettext('%(number)d hour ago',
'%(number)d hours ago', n)),
(60, lambda n: ungettext('%(number)d minute ago',
'%(number)d minutes ago', n)),
(1, lambda n: ungettext('%(number)d second ago',
'%(number)d seconds ago', n))]
if not now:
if d.tzinfo:
now = datetime.datetime.now(LocalTimezone(d))
else:
now = datetime.datetime.now()
# Ignore microsecond part of 'd' since we removed it from 'now'
delta = now - (d - datetime.timedelta(0, 0, d.microsecond))
since = delta.days * 24 * 60 * 60 + delta.seconds
if since <= 0:
# d is in the future compared to now, stop processing.
return u''
for i, (seconds, name) in enumerate(chunks):
count = since // seconds
if count != 0:
break
return name(count) % {'number': count}
@register.filter
def label_with_help(f):
"""Print the label tag for a form field, including the help_text
value as a title attribute."""
label = u'<label for="%s" title="%s">%s</label>'
return jinja2.Markup(label % (f.auto_id, f.help_text, f.label))
@register.filter
def yesno(boolean_value):
return jinja2.Markup(_lazy(u'Yes') if boolean_value else _lazy(u'No'))
@register.filter
def remove(list_, item):
"""Removes an item from a list."""
return [i for i in list_ if i != item]
IDEVICE_USER_AGENTS = re.compile('iphone|ipad|ipod')
@register.function
def is_idevice(request):
"""Return True if the user agent is detected to be an i{phone,pad,pod}."""
if hasattr(request, 'META'):
ua = request.META.get('HTTP_USER_AGENT', '').lower()
return IDEVICE_USER_AGENTS.search(ua)
return False
@register.function
@jinja2.contextfunction
def ga_push_attribute(context):
"""Return the json for the data-ga-push attribute.
This is used to defined custom variables and other special tracking with
Google Analytics.
"""
request = context.get('request')
ga_push = context.get('ga_push', [])
# If the user is on the first page after logging in,
# we add a "User Type" custom variable.
if request.GET.get('fpa') == '1' and request.user.is_authenticated():
user = request.user
group_names = user.groups.values_list('name', flat=True)
# If they belong to the Administrator group:
if 'Administrators' in group_names:
ga_push.append(
['_setCustomVar', 1, 'User Type', 'Contributor - Admin', 1])
# If they belong to the Contributors group:
elif 'Contributors' in group_names:
ga_push.append(['_setCustomVar', 1, 'User Type', 'Contributor', 1])
# If they don't belong to any of these groups:
else:
ga_push.append(['_setCustomVar', 1, 'User Type', 'Registered', 1])
return jsonlib.dumps(ga_push)
@register.function
@jinja2.contextfunction
def is_secure(context):
request = context.get('request')
if request and hasattr(request, 'is_secure'):
return context.get('request').is_secure()
return False
@register.filter
def linkify(text):
return bleach.linkify(text)
@register.function
def showfor_data(products):
# Markup() marks this data as safe.
return Markup(jsonlib.dumps(_showfor_data(products)))
@register.function
def add_utm(url_, campaign, source='notification', medium='email'):
"""Add the utm_* tracking parameters to a URL."""
return urlparams(
url_, utm_campaign=campaign, utm_source=source, utm_medium=medium)
@register.function
def to_unicode(str):
return unicode(str)
| bsd-3-clause |
cloudera/hue | desktop/core/ext-py/boto-2.46.1/boto/cloudsearch/sourceattribute.py | 153 | 3156 | # Copyright (c) 202 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates.
# All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class SourceAttribute(object):
"""
Provide information about attributes for an index field.
A maximum of 20 source attributes can be configured for
each index field.
:ivar default: Optional default value if the source attribute
is not specified in a document.
:ivar name: The name of the document source field to add
to this ``IndexField``.
:ivar data_function: Identifies the transformation to apply
when copying data from a source attribute.
:ivar data_map: The value is a dict with the following keys:
* cases - A dict that translates source field values
to custom values.
* default - An optional default value to use if the
source attribute is not specified in a document.
* name - the name of the document source field to add
to this ``IndexField``
:ivar data_trim_title: Trims common title words from a source
document attribute when populating an ``IndexField``.
This can be used to create an ``IndexField`` you can
use for sorting. The value is a dict with the following
fields:
* default - An optional default value.
* language - an IETF RFC 4646 language code.
* separator - The separator that follows the text to trim.
* name - The name of the document source field to add.
"""
ValidDataFunctions = ('Copy', 'TrimTitle', 'Map')
def __init__(self):
self.data_copy = {}
self._data_function = self.ValidDataFunctions[0]
self.data_map = {}
self.data_trim_title = {}
@property
def data_function(self):
return self._data_function
@data_function.setter
def data_function(self, value):
if value not in self.ValidDataFunctions:
valid = '|'.join(self.ValidDataFunctions)
raise ValueError('data_function must be one of: %s' % valid)
self._data_function = value
| apache-2.0 |
niboshi/chainer | onnx_chainer/functions/pooling.py | 1 | 6244 | import warnings
from chainer.utils import conv
import numpy as np
from onnx_chainer.functions.opset_version import support
from onnx_chainer import onnx_helper
@support((1, 7))
def convert_AveragePooling2D(
func, opset_version, input_names, output_names, context):
pad = [func.ph, func.pw]
stride = [func.sy, func.sx]
ksize = [func.kh, func.kw]
if func.cover_all:
# Supports cover_all by setting extra padding
# NOTE: onnxruntime may not run when "k <= p + s - 1".
pad.extend([p + s - 1 for p, s in zip(pad, stride)])
else:
pad = pad * 2
if opset_version == 1:
raise ValueError(
'AveragePooling2D is not compatible with ONNX\'s AveragePool-1. '
'Use operation set version >= 7.')
elif opset_version == 7:
return onnx_helper.make_node(
'AveragePool', input_names, output_names,
kernel_shape=ksize,
pads=pad,
strides=stride,
count_include_pad=1,
),
@support((1, 7))
def convert_AveragePoolingND(
func, opset_version, input_names, output_names, context):
pad = list(func.pad[:])
if func.cover_all:
# Supports cover_all by setting extra padding
# NOTE: onnxruntime may not run when "k <= p + s - 1".
pad.extend([p + s - 1 for p, s in zip(pad, func.stride)])
else:
pad = pad * 2
if opset_version == 1:
raise ValueError(
'AveragePoolingND is not compatible with ONNX\'s AveragePool-1. '
'Use operation set version >= 7.')
elif opset_version == 7:
return onnx_helper.make_node(
'AveragePool', input_names, output_names,
kernel_shape=func.ksize,
pads=pad,
strides=func.stride,
count_include_pad=1,
),
@support((1, 8))
def convert_MaxPooling2D(
func, opset_version, input_names, output_names, context):
pad = [func.ph, func.pw]
stride = [func.sy, func.sx]
ksize = [func.kh, func.kw]
if func.cover_all:
# Supports cover_all by setting extra padding
# NOTE: onnxruntime may not run when "k <= p + s - 1".
pad.extend([p + s - 1 for p, s in zip(pad, stride)])
else:
pad = pad * 2
if opset_version == 1:
return onnx_helper.make_node(
'MaxPool', input_names, output_names,
kernel_shape=ksize,
pads=pad,
strides=stride
),
elif opset_version == 8:
return onnx_helper.make_node(
'MaxPool', input_names, output_names,
kernel_shape=ksize,
pads=pad,
strides=stride,
storage_order=0, # row major
),
@support((1, 8))
def convert_MaxPoolingND(
func, opset_version, input_names, output_names, context):
pad = list(func.pad[:])
if func.cover_all:
# Supports cover_all by setting extra padding
# NOTE: onnxruntime may not run when "k <= p + s - 1".
pad.extend([p + s - 1 for p, s in zip(pad, func.stride)])
else:
pad = pad * 2
if opset_version == 1:
return onnx_helper.make_node(
'MaxPool', input_names, output_names,
kernel_shape=func.ksize,
pads=pad,
strides=func.stride
),
elif opset_version == 8:
return onnx_helper.make_node(
'MaxPool', input_names, output_names,
kernel_shape=func.ksize,
pads=pad,
strides=func.stride,
storage_order=0, # row major
),
def convert_ROIPooling2D(
func, opset_version, input_names, output_names, context):
warnings.warn(
'It\'s possible that output does not match with Chainer, please check '
'each runtime\'s implementation. For example, when input x has '
'negative values, some runtimes set max(output, 0) unlike Chainer.',
UserWarning)
return onnx_helper.make_node(
'MaxRoiPool', input_names, output_names,
pooled_shape=[func.outh, func.outw],
spatial_scale=func.spatial_scale,
),
@support((7, 9, 10, 11))
def convert_Unpooling2D(
func, opset_version, input_names, output_names, context):
pad = [func.ph, func.pw]
stride = [func.sy, func.sx]
ksize = [func.kh, func.kw]
outsize = [func.outh, func.outw]
# TODO(hamaji): These could be implemented by `Slice` and `Pad`.
if func.cover_all:
raise RuntimeError('ONNX-chainer does not support `cover_all=True` '
'for Unpooling2D')
h, w = func.inputs[0].shape[2:]
expected_outsize = [
conv.get_deconv_outsize(
h, func.kh, func.sy, func.ph, cover_all=func.cover_all),
conv.get_deconv_outsize(
w, func.kh, func.sy, func.ph, cover_all=func.cover_all)
]
if outsize != expected_outsize:
raise RuntimeError('ONNX-chainer does not support `outsize!=None` '
'for Unpooling2D: expected={} actual={}'.format(
expected_outsize, outsize))
if pad != [0, 0]:
raise RuntimeError('ONNX-chainer does not support `pad!=0` '
'for Unpooling2D')
# This one would require an extra 1x1 MaxPool.
if stride != ksize:
raise RuntimeError('ONNX-chainer does not support `stride!=ksize` '
'for Unpooling2D: stride={} ksize={}'.format(
stride, ksize))
scales = [1.0, 1.0, float(func.kh), float(func.kw)]
if opset_version == 7:
return onnx_helper.make_node('Upsample', input_names, output_names,
scales=scales),
scales_name = context.add_const(
np.array(scales, dtype=np.float32), 'scales')
if opset_version in [9, 10]:
input_names.append(scales_name)
op = 'Upsample' if opset_version == 9 else 'Resize'
return onnx_helper.make_node(op, input_names, output_names),
if opset_version == 11:
roi_name = context.add_const(np.array([]), 'roi')
input_names.extend([roi_name, scales_name])
return onnx_helper.make_node('Resize', input_names, output_names),
| mit |
shifter/rekall | rekall-core/rekall/entities/manager.py | 4 | 34772 | # Rekall Memory Forensics
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
"""
The Rekall Entity Layer.
"""
__author__ = "Adam Sindelar <adamsh@google.com>"
import copy
import itertools
import logging
import traceback
from rekall.entities import collector as entity_collector
from rekall.entities import component as entity_component
from rekall.entities import entity as entity_module
from rekall.entities import definitions
from rekall.entities import identity as entity_id
from rekall.entities import lookup_table as entity_lookup
from efilter import expression
from efilter import query as entity_query
from efilter.engines import matcher as query_matcher
class IngestionPipeline(object):
"""Keeps track of new and updated entities during collection."""
empty = True
def __init__(self, queries):
self.queues = {}
self.matchers = {}
self.outcomes = {}
for query in queries:
self.queues[query] = []
self.matchers[query] = query_matcher.ObjectMatcher(query)
def seed(self, query, entities):
"""Set up the queue for query with entities."""
self.queues[query] = list(entities)
if self.queues[query]:
self.empty = False
def find(self, query):
"""Return entities available to satisfy the query."""
if isinstance(query, dict):
results = {}
for key, value in query.iteritems():
results[key] = self.find(value)
return results
return self.queues[query]
def fill(self, ingest, collector, wanted_matcher=None, wanted_handler=None):
"""Fills appropriate queues with entities from ingest.
Arguments:
ingest: An iterable containing entities and effects of adding them.
The effects are a dict of:
None: How many entities were duplicates, including contents.
entity_collector.EffectEnum.Merged: How many entities
changed by merging.
entity_collector.EffectEnum.Added: How many new entities
created.
"fill": How many entities were enqueued for ingestion by
other collectors.
collector: The collector object from which ingest was collected.
"""
counts = {entity_collector.EffectEnum.Duplicate: 0,
entity_collector.EffectEnum.Merged: 0,
entity_collector.EffectEnum.Added: 0,
entity_collector.EffectEnum.Enqueued: 0}
for entity, effect in ingest:
counts[effect] += 1
if effect == entity_collector.EffectEnum.Duplicate:
continue
if wanted_handler and wanted_matcher.run(entity):
wanted_handler(entity)
for query in self.queries:
if self.matchers[query].run(entity):
self.queues[query].append(entity)
counts[entity_collector.EffectEnum.Enqueued] += 1
self.empty = False
if any(counts.itervalues()):
logging.debug(
"%s results: %d new, %d updated, %d requeued, %d duplicates.",
collector.name,
counts[entity_collector.EffectEnum.Added],
counts[entity_collector.EffectEnum.Merged],
counts[entity_collector.EffectEnum.Enqueued],
counts[entity_collector.EffectEnum.Duplicate])
self.outcomes[collector] = counts
return counts
def flush(self):
queries = self.queues.keys()
for query in queries:
self.queues[query] = []
self.empty = True
def __getitem__(self, key):
return self.queues[key]
@property
def queries(self):
return set(self.queues.keys())
class EntityManager(object):
"""Database of entities."""
# Names of collectors that have produced all they're going to produce.
finished_collectors = None
# Dict of entities keyed by their identity.
entities = None
def __init__(self, session):
self.session = session
self.reset()
def reset(self):
self.entities = {}
self._collectors = {}
self.finished_collectors = set()
self._cached_query_analyses = {}
self._cached_matchers = {}
# Lookup table on component name is such a common use case that we
# always have it on. This actually speeds up searches by attribute that
# don't have a specific lookup table too.
def _component_indexer(entity):
for component in entity_component.Component.classes.keys():
if getattr(entity.components, component):
yield component
def _collector_indexer(entity):
for collector_name in entity.components.Entity.collectors:
yield collector_name
self.lookup_tables = {
"components": entity_lookup.EntityLookupTable(
key_name="components",
key_func=_component_indexer,
entity_manager=self),
"collectors": entity_lookup.EntityLookupTable(
key_name="collectors",
key_func=_collector_indexer,
entity_manager=self)}
@property
def collectors(self):
self.update_collectors()
return self._collectors
def update_collectors(self):
"""Refresh the list of active collectors. Do a diff if possible."""
for key, cls in entity_collector.EntityCollector.classes.iteritems():
if key in self._collectors:
if cls.is_active(self.session):
continue
else:
del self._collectors[key]
else:
if cls.is_active(self.session):
self._collectors[key] = cls(entity_manager=self)
@property
def identity_prefix(self):
"""Returns the prefix for all identities on this machine.
Currently this just returns "LOCALHOST", but in the future this will
be a way of semi-uniquelly identifying the image/machine of origin.
"""
# TODO: Implement proper machine identification.
return "LOCALHOST"
def identify(self, identity_dict):
"""Generate the appropriate type of identity based on identity dict.
Arguments:
identity_dict: a dictionary of attribute names (format being the
usual "Component/member") and expected values.
Returns:
An instance of Identity initialized with the identity dict and this
manager's global prefix.
"""
# Cast values to their correct types.
cast_dict = {}
for key, val in identity_dict.iteritems():
if isinstance(key, tuple):
cast_vals = []
for idx, attr in enumerate(key):
attribute = entity_module.Entity.reflect_attribute(attr)
cast_vals.append(attribute.typedesc.coerce(val[idx]))
cast_val = tuple(cast_vals)
else:
attribute = entity_module.Entity.reflect_attribute(key)
cast_val = attribute.typedesc.coerce(val)
cast_dict[key] = cast_val
return entity_id.Identity.from_dict(global_prefix=self.identity_prefix,
identity_dict=cast_dict)
def identify_no_cast(self, identity_dict):
return entity_id.Identity.from_dict(global_prefix=self.identity_prefix,
identity_dict=identity_dict)
# pylint: disable=protected-access
def register_components(self, identity, components, source_collector):
"""Find or create an entity for identity and add components to it.
Arguments:
identity: What the components are about. Should be a subclass of
Identity. As a special case, we also accept BaseObjects.
components: An iterable of components about the identity.
source_collector: Anything that responds to __unicode__ or __name__
and describes the source of this information (usually the
string name of the collector function).
Returns:
Tuple of entity and the effect of the new information.
The effect can be one of:
EffectEnum.Duplicate: No new information learned.
EffectEnum.Merged: As result of this call, data in one or more
entities was updated and entities may have merged.
EffectEnum.Added: A new entity was added.
"""
kwargs = {}
for component in components:
kwargs[component.component_name] = component
kwargs["Entity"] = definitions.Entity(
identity=identity,
collectors=frozenset((source_collector,)))
entity = entity_module.Entity(
entity_manager=self,
components=entity_component.CONTAINER_PROTOTYPE._replace(**kwargs))
indices = set(entity.indices)
existing_entities = list(self.find_by_identity(identity))
effect = entity_collector.EffectEnum.Added
if existing_entities:
if (len(existing_entities) == 1 and
existing_entities[0].issuperset(entity)):
# No new data, but let's give the collector credit for finding
# what we already knew.
entity_comp = existing_entities[0].components.Entity
entity_comp._mutate(
member="collectors",
value=entity_comp.collectors.union([source_collector]))
return (existing_entities[0],
entity_collector.EffectEnum.Duplicate)
for existing_entity in existing_entities:
# Entities exist for this already, but are not equivalent to
# the entity we found. Merge everything.
effect = entity_collector.EffectEnum.Merged
entity.update(existing_entity)
indices.update(existing_entity.indices)
# Overwrite all old indices with reference to the new entity.
for index in indices:
self.entities[index] = entity
for lookup_table in self.lookup_tables.itervalues():
lookup_table.update_index((entity,))
return entity, effect
def add_attribute_lookup(self, key):
"""Adds a fast-lookup index for the component/attribute key path.
This also causes the newly-created lookup table to rebuild its index.
Depending on how many entities already exist, building the index could
take a couple of seconds.
"""
# Don't add the same one twice.
if self.lookup_tables.get(key, None):
return
attribute = entity_module.Entity.reflect_attribute(key)
if not isinstance(attribute, entity_component.Field):
logging.info(
("Can't create a lookup for %s, because it's not a simple "
"field."), attribute)
return
logging.debug("Creating a lookup table for %s", key)
component, _ = key.split("/")
lookup_table = entity_lookup.AttributeLookupTable(
attribute=key,
entity_manager=self)
# Only use the entities that actually have the component to build the
# index.
lookup_table.update_index(
self.find(expression.ComponentLiteral(component), complete=False,
keep_cache=True))
self.lookup_tables[key] = lookup_table
def find_by_identity(self, identity, complete=False):
"""Yield the entities that matches the identity.
The number of entities yielded is almost always one or zero. The single
exception to that rule is when the identity parameter is both: (a) a
alternate identity and (b) not yet present in this entity manager. In
that case, multiple entities may match.
Arguments:
identity: The identity to search for.
complete: Should collectors be run to ensure complete results?
"""
if complete:
self.collect_for(identity.as_query())
results = set()
for index in identity.indices:
entity = self.entities.get(index, None)
if entity:
results.add(entity)
if complete:
results = [self.parse(entity) for entity in results]
return list(results)
def find_by_component(self, component, complete=True):
"""Finds all entities that have the component.
Arguments:
complete: If True, will attempt to collect the component.
"""
query = entity_query.Query(expression.ComponentLiteral(component))
if complete:
self.collect_for(query)
return list(self.lookup_tables["components"].lookup(component))
def find_by_collector(self, collector):
"""Find all entities touched by the collector."""
return list(self.lookup_tables["collectors"].lookup(str(collector)))
def matcher_for(self, query):
"""Returns a query matcher for the query (cached)."""
matcher = self._cached_matchers.setdefault(
query, query_matcher.ObjectMatcher(query))
return matcher
def parsers_for(self, entity):
"""Finds collectors that can parse this entity.
Yields: tuples of:
- collector instance
- name of the keyword argument on the collect method under which
the entity should be passed to the collector.
"""
for collector in self.collectors.itervalues():
if len(collector.collect_queries) != 1:
continue
for query_name, query in collector.collect_queries.iteritems():
matcher = self.matcher_for(query)
if matcher.run(entity):
yield collector, query_name
def parse(self, entity):
"""Parses the entity using available higher-order collectors."""
result = entity
for collector, collect_kwarg in self.parsers_for(entity):
collector_input = {collect_kwarg: [result]}
for parsed, effect in self.collect(collector=collector,
collector_input=collector_input,
hint=None):
if effect != entity_collector.EffectEnum.Duplicate:
logging.debug(
"Collector %s produced a hit in parser mode.",
collector.name)
result = parsed
return result
def analyze(self, wanted):
"""Finds collectors and indexing suggestions for the query.
Returns a dict of:
- collectors: list of collectors to run
- lookups: list of attributes to consider indexing for
- dependencies: list of SimpleDependency instances to include
- exclusions: list of SimpleDependency instances to exclude
"""
if not isinstance(wanted, entity_query.Query):
wanted = entity_query.Query(wanted)
# We cache by the source and not the query because we want to reanalyze
# queries that are logically equivalent, but expressed differently, in
# order to have the right cursor positions stored for highlighting in
# GUI.
cache_key = wanted.source
analysis = self._cached_query_analyses.get(cache_key, None)
if analysis:
# We want to make a copy exactly one level deep.
analysis_copy = {}
for key, value in analysis.iteritems():
analysis_copy[key] = copy.copy(value)
return analysis_copy
analyzer = wanted.run_engine("slashy_analyzer")
include = set()
for dependency in analyzer.include:
# Skip over general dependencies on Entity.
if dependency.component == "Entity" and not dependency.attribute:
continue
include.add(dependency)
exclude = analyzer.exclude
suggested_indices = analyzer.latest_indices
# A collector is a match if any of its promises match any of the
# dependencies of the query.
matched_collectors = []
for collector in self.collectors.itervalues():
for promise, dependency in itertools.product(
collector.promises, include):
if dependency.match(promise):
matched_collectors.append(collector)
break
# A collector is yielded unless each one of its promises matches
# an exclusion from dependencies.
collectors = set()
for collector in matched_collectors:
for promise, exclusion in itertools.product(
collector.promises, exclude):
if not exclusion.match(promise):
collectors.add(collector)
break
else:
# No exclusions.
collectors.add(collector)
# A component is guaranteed if any dependency lists it. It is likely
# if collectors we depend on output it (though not guaranteed).
guaranteed_components = set(analyzer.expected_components)
possible_components = set()
for dependency in include:
component = dependency.component
if component in guaranteed_components:
continue
possible_components.add(dependency.component)
for collector in collectors:
for promise in collector.promises:
component = promise.component
if component in guaranteed_components:
continue
possible_components.add(component)
analysis = dict(collectors=list(collectors),
lookups=suggested_indices,
dependencies=include,
exclusions=exclude,
guaranteed_components=guaranteed_components,
possible_components=possible_components)
self._cached_query_analyses[cache_key] = analysis
return analysis
def find(self, query, complete=True, validate=True, query_params=None,
retry_on_error=False, keep_cache=False, syntax="slashy"):
"""Runs the query and yields entities that match.
Arguments:
query: Either an instance of the query AST, a query string, or a
dictionary of queries. If a dict is given, a new dict will
be returned with the same keys and values replaced with
results.
query_params: If query accepts parameters (it's a template), you
may pass them here.
complete: If True, will trigger collectors as necessary, to ensure
completness of results.
validate: Will cause the query to be validated first (mostly for
type errors).
Arguments (live analysis only):
retry_on_error: Should query be retried on failed collection?
This argument is only respected on live systems.
keep_cache: Should we reuse cached data from previous searches?
This will greatly speed up analysis, but may lead to
outdated or inconsistent results on running systems.
This argument is only respected on live systems.
"""
if not self.session.volatile:
keep_cache = True
retry_on_error = False
if not keep_cache:
if not complete:
raise ValueError(
"keep_cache and complete cannot both be False.")
self.reset()
if isinstance(query, dict):
results = {}
for query_name, expr in query.iteritems():
results[query_name] = self.find(expr, complete=complete,
validate=validate,
query_params=query_params,
retry_on_error=retry_on_error,
keep_cache=keep_cache)
return results
if not isinstance(query, entity_query.Query):
query = entity_query.Query(query, params=query_params,
syntax=syntax)
if validate:
query.run_engine("validator")
if complete:
try:
self.collect_for(query)
except (entity_id.IdentityError, TypeError) as e:
if retry_on_error:
logging.error(
"Collect failed for query %r. It would appear Rekall "
"is running on live memory - it is possible contents "
"of memory changed between reads, causing a collector "
"to fail. Going to try again. Original error: %r\n%s",
query, e, traceback.format_exc())
self.reset()
return self.find(query=query, complete=True,
validate=validate,
query_params=query_params,
keep_cache=keep_cache,
retry_on_error=False)
else:
# We're not retrying and/or running on an image. Just
# rethrow the exception here.
raise
# Try to satisfy the query using available lookup tables.
search = entity_lookup.EntityQuerySearch(query)
return search.search(self.entities, self.lookup_tables)
def stream(self, query, handler, query_params=None):
query = entity_query.Query(query, params=query_params)
seen = set()
def _deduplicator(entity):
if entity in seen:
return
seen.add(entity)
handler(entity)
self.collect_for(query, result_stream_handler=_deduplicator)
for entity in self.find(query, complete=False, keep_cache=True):
_deduplicator(entity)
def find_first(self, query, complete=True, validate=True,
query_params=None):
"""Like find, but returns just the first result."""
for entity in self.find(query, complete, validate, query_params):
return entity
# pylint: disable=protected-access
def collect_for(self, wanted, use_hint=False, result_stream_handler=None):
"""Will find and run the appropriate collectors to satisfy the query.
If use_hint is set to True, 'wanted' will be passed on as hint to
the collectors. This may result in faster collection, but may result
in collectors having to run repeatedly.
"""
# Planning stage.
if callable(result_stream_handler):
wanted_matcher = query_matcher.ObjectMatcher(wanted)
else:
wanted_matcher = None
self.update_collectors()
# to_process is used as a FIFO queue below.
analysis = self.analyze(wanted)
to_process = analysis["collectors"][:]
suggested_indices = analysis["lookups"]
# Create indices as suggested by the analyzer.
for attribute in suggested_indices:
self.add_attribute_lookup(attribute)
collectors_seen = set(self.finished_collectors)
# Collectors with an ingest query are de-facto parsers for things
# produced by collectors with no ingest query. They may run repeatedly
# as required.
repeated = list()
# Collectors with no dependencies (my favorite).
simple = list()
# Queries that collectors depend on.
queries = set()
# Build up a list of collectors to run, based on dependencies.
while to_process:
collector = to_process.pop(0)
if collector.name in collectors_seen:
continue
collectors_seen.add(collector.name)
if collector.collect_queries:
logging.debug("Collector %s deferred until stage 2.",
collector.name)
repeated.append(collector)
queries |= set(collector.collect_queries.itervalues())
# Discard the indexing suggestions for ingestion queries
# because they don't represent normal usage.
additional = set()
for query in collector.collect_queries.itervalues():
additional |= set(self.analyze(query)["collectors"])
for dependency in additional:
logging.debug("Collector %s depends on collector %s.",
collector.name, dependency.name)
if dependency.name not in collectors_seen:
to_process.append(dependency)
else:
logging.debug("%s will run in stage 1.",
collector.name)
simple.append(collector)
if not collectors_seen.difference(self.finished_collectors):
# Looks like we're already populated - no need to do anything.
return
logging.info(
"Will now run %d first-order collectors and %d collectors with "
"dependencies to satisfy query %s.",
len(simple), len(repeated), wanted)
# Execution stage 1: no dependencies.
for collector in simple:
effects = {entity_collector.EffectEnum.Duplicate: 0,
entity_collector.EffectEnum.Merged: 0,
entity_collector.EffectEnum.Added: 0}
if use_hint or collector.enforce_hint:
hint = wanted
else:
hint = None
self.finished_collectors.add(collector.name)
for entity, effect in self.collect(collector, hint=hint):
if result_stream_handler and wanted_matcher.run(entity):
result_stream_handler(entity)
effects[effect] += 1
logging.debug(
"%s produced %d new entities, %d updated and %d duplicates",
collector.name,
effects[entity_collector.EffectEnum.Added],
effects[entity_collector.EffectEnum.Merged],
effects[entity_collector.EffectEnum.Duplicate])
if not repeated:
# No higher-order collectors scheduled. We're done.
return
# Seeding stage for higher-order collectors.
in_pipeline = IngestionPipeline(queries=queries)
out_pipeline = IngestionPipeline(queries=queries)
for query in queries:
results = self.find(query, complete=False, keep_cache=True)
in_pipeline.seed(query, results)
if results:
logging.debug("Pipeline seeded with %d entities matching '%s'",
len(results), query)
# Execution stage 2: collectors with dependencies.
# Collectors should run in FIFO order:
repeated.reverse()
repeat_counter = 0
# This will spin until none of the remaining collectors want to run.
while not in_pipeline.empty:
# Collectors will read from the in_pipeline and fill the
# out_pipeline. At the end of each spin the pipelines swap and
# the new out_pipeline is flushed.
for collector in repeated:
# If the collector wants complete input, we pull it from the
# database. If it just wants one entity at a time, we can use
# the ingestion pipeline. The semantics of both find methods
# are identical.
if collector.complete_input:
collector_input = self.find(collector.collect_queries,
complete=False,
keep_cache=True)
else:
collector_input = in_pipeline.find(
collector.collect_queries)
# The collector requests its prefilter to be called.
if collector.filter_input:
collector_input_filtered = {}
for key, val in collector_input.iteritems():
collector_input_filtered[key] = collector.input_filter(
hint=hint, entities=val)
collector_input = collector_input_filtered
# The collector requests that we always pass the query hint.
if use_hint or collector.enforce_hint:
hint = wanted
else:
hint = None
try:
# Feed output back into the pipeline.
results = self.collect(collector=collector,
collector_input=collector_input,
hint=hint)
out_pipeline.fill(collector=collector,
ingest=results,
wanted_handler=result_stream_handler,
wanted_matcher=wanted_matcher)
except entity_id.IdentityError as e:
logging.error(
"Collector %r has encountered invalid or inconsistent "
"data and could not recover. Details available with "
"debug logging." % collector)
logging.debug(
"Collector %r (hint %r) raised %r\n%s.\n"
"Collector input was %r."
% (collector, e, traceback.format_exc(),
collector_input, hint))
# Check for endless loops.
if in_pipeline.outcomes == out_pipeline.outcomes:
repeat_counter += 1
if repeat_counter < 5:
logging.warning(
"Detected a loop in collection run (%d cycles)." %
repeat_counter)
else:
logging.warning(
"Maximum number of cycles in collection run exceeded. "
"Terminating collection.")
break
else:
repeat_counter = 0
# Swap & flush, rinse & repeat.
in_pipeline, out_pipeline = out_pipeline, in_pipeline
out_pipeline.flush()
for collector in repeated:
if not use_hint and not collector.enforce_hint:
self.finished_collectors.add(collector.name)
def collect(self, collector, hint, collector_input=None):
"""Runs the collector, registers output and yields any new entities."""
if collector_input is None:
collector_input = {}
result_counter = 0
if self.session:
self.session.report_progress(
"Collecting %(collector)s %(spinner)s",
collector=collector.name)
for results in collector.collect(hint=hint, **collector_input):
if not isinstance(results, list):
# Just one component yielded.
results = [results]
# First result is either the first component or an identity.
first_result = results[0]
if isinstance(first_result, entity_id.Identity):
# If the collector gave as an identity then use that.
identity = first_result
results.pop(0)
else:
# If collector didn't give us an identity then we build
# one from the first component's first field. This is
# a good heuristic for about 90% of the time.
first_field = first_result.component_fields[0].name
attribute = "%s/%s" % (type(first_result).__name__,
first_field)
try:
identity = self.identify({attribute: first_result[0]})
except entity_id.IdentityError:
logging.warning(
("Invalid identity %r inferred from output of %r. "
"Entity skipped. Full results: %r"),
{attribute: first_result[0]},
collector,
results)
continue
try:
entity, effect = self.register_components(
identity=identity,
components=results,
source_collector=collector.name)
except entity_id.IdentityError as e:
logging.warning(
("Invalid identity %r inferred from output of %r. "
"Entity skipped. Full results: %r. "
"Original error: %s"),
identity, collector, results, e)
continue
result_counter += 1
if result_counter % 100 == 0 and self.session:
self.session.report_progress(
"Collecting %(collector)s %(spinner)s (%(count)d results)",
collector=collector.name,
count=result_counter)
yield entity, effect
| gpl-2.0 |
jylaxp/django | tests/select_related_onetoone/tests.py | 301 | 10516 | from __future__ import unicode_literals
import unittest
from django.core.exceptions import FieldError
from django.test import SimpleTestCase, TestCase
from .models import (
AdvancedUserStat, Child1, Child2, Child3, Child4, Image, Parent1, Parent2,
Product, StatDetails, User, UserProfile, UserStat, UserStatResult,
)
class ReverseSelectRelatedTestCase(TestCase):
def setUp(self):
user = User.objects.create(username="test")
UserProfile.objects.create(user=user, state="KS", city="Lawrence")
results = UserStatResult.objects.create(results='first results')
userstat = UserStat.objects.create(user=user, posts=150,
results=results)
StatDetails.objects.create(base_stats=userstat, comments=259)
user2 = User.objects.create(username="bob")
results2 = UserStatResult.objects.create(results='moar results')
advstat = AdvancedUserStat.objects.create(user=user2, posts=200, karma=5,
results=results2)
StatDetails.objects.create(base_stats=advstat, comments=250)
p1 = Parent1(name1="Only Parent1")
p1.save()
c1 = Child1(name1="Child1 Parent1", name2="Child1 Parent2", value=1)
c1.save()
p2 = Parent2(name2="Child2 Parent2")
p2.save()
c2 = Child2(name1="Child2 Parent1", parent2=p2, value=2)
c2.save()
def test_basic(self):
with self.assertNumQueries(1):
u = User.objects.select_related("userprofile").get(username="test")
self.assertEqual(u.userprofile.state, "KS")
def test_follow_next_level(self):
with self.assertNumQueries(1):
u = User.objects.select_related("userstat__results").get(username="test")
self.assertEqual(u.userstat.posts, 150)
self.assertEqual(u.userstat.results.results, 'first results')
def test_follow_two(self):
with self.assertNumQueries(1):
u = User.objects.select_related("userprofile", "userstat").get(username="test")
self.assertEqual(u.userprofile.state, "KS")
self.assertEqual(u.userstat.posts, 150)
def test_follow_two_next_level(self):
with self.assertNumQueries(1):
u = User.objects.select_related("userstat__results", "userstat__statdetails").get(username="test")
self.assertEqual(u.userstat.results.results, 'first results')
self.assertEqual(u.userstat.statdetails.comments, 259)
def test_forward_and_back(self):
with self.assertNumQueries(1):
stat = UserStat.objects.select_related("user__userprofile").get(user__username="test")
self.assertEqual(stat.user.userprofile.state, 'KS')
self.assertEqual(stat.user.userstat.posts, 150)
def test_back_and_forward(self):
with self.assertNumQueries(1):
u = User.objects.select_related("userstat").get(username="test")
self.assertEqual(u.userstat.user.username, 'test')
def test_not_followed_by_default(self):
with self.assertNumQueries(2):
u = User.objects.select_related().get(username="test")
self.assertEqual(u.userstat.posts, 150)
def test_follow_from_child_class(self):
with self.assertNumQueries(1):
stat = AdvancedUserStat.objects.select_related('user', 'statdetails').get(posts=200)
self.assertEqual(stat.statdetails.comments, 250)
self.assertEqual(stat.user.username, 'bob')
def test_follow_inheritance(self):
with self.assertNumQueries(1):
stat = UserStat.objects.select_related('user', 'advanceduserstat').get(posts=200)
self.assertEqual(stat.advanceduserstat.posts, 200)
self.assertEqual(stat.user.username, 'bob')
with self.assertNumQueries(1):
self.assertEqual(stat.advanceduserstat.user.username, 'bob')
def test_nullable_relation(self):
im = Image.objects.create(name="imag1")
p1 = Product.objects.create(name="Django Plushie", image=im)
p2 = Product.objects.create(name="Talking Django Plushie")
with self.assertNumQueries(1):
result = sorted(Product.objects.select_related("image"), key=lambda x: x.name)
self.assertEqual([p.name for p in result], ["Django Plushie", "Talking Django Plushie"])
self.assertEqual(p1.image, im)
# Check for ticket #13839
self.assertIsNone(p2.image)
def test_missing_reverse(self):
"""
Ticket #13839: select_related() should NOT cache None
for missing objects on a reverse 1-1 relation.
"""
with self.assertNumQueries(1):
user = User.objects.select_related('userprofile').get(username='bob')
with self.assertRaises(UserProfile.DoesNotExist):
user.userprofile
def test_nullable_missing_reverse(self):
"""
Ticket #13839: select_related() should NOT cache None
for missing objects on a reverse 0-1 relation.
"""
Image.objects.create(name="imag1")
with self.assertNumQueries(1):
image = Image.objects.select_related('product').get()
with self.assertRaises(Product.DoesNotExist):
image.product
def test_parent_only(self):
with self.assertNumQueries(1):
p = Parent1.objects.select_related('child1').get(name1="Only Parent1")
with self.assertNumQueries(0):
with self.assertRaises(Child1.DoesNotExist):
p.child1
def test_multiple_subclass(self):
with self.assertNumQueries(1):
p = Parent1.objects.select_related('child1').get(name1="Child1 Parent1")
self.assertEqual(p.child1.name2, 'Child1 Parent2')
def test_onetoone_with_subclass(self):
with self.assertNumQueries(1):
p = Parent2.objects.select_related('child2').get(name2="Child2 Parent2")
self.assertEqual(p.child2.name1, 'Child2 Parent1')
def test_onetoone_with_two_subclasses(self):
with self.assertNumQueries(1):
p = Parent2.objects.select_related('child2', "child2__child3").get(name2="Child2 Parent2")
self.assertEqual(p.child2.name1, 'Child2 Parent1')
with self.assertRaises(Child3.DoesNotExist):
p.child2.child3
p3 = Parent2(name2="Child3 Parent2")
p3.save()
c2 = Child3(name1="Child3 Parent1", parent2=p3, value=2, value3=3)
c2.save()
with self.assertNumQueries(1):
p = Parent2.objects.select_related('child2', "child2__child3").get(name2="Child3 Parent2")
self.assertEqual(p.child2.name1, 'Child3 Parent1')
self.assertEqual(p.child2.child3.value3, 3)
self.assertEqual(p.child2.child3.value, p.child2.value)
self.assertEqual(p.child2.name1, p.child2.child3.name1)
def test_multiinheritance_two_subclasses(self):
with self.assertNumQueries(1):
p = Parent1.objects.select_related('child1', 'child1__child4').get(name1="Child1 Parent1")
self.assertEqual(p.child1.name2, 'Child1 Parent2')
self.assertEqual(p.child1.name1, p.name1)
with self.assertRaises(Child4.DoesNotExist):
p.child1.child4
Child4(name1='n1', name2='n2', value=1, value4=4).save()
with self.assertNumQueries(1):
p = Parent2.objects.select_related('child1', 'child1__child4').get(name2="n2")
self.assertEqual(p.name2, 'n2')
self.assertEqual(p.child1.name1, 'n1')
self.assertEqual(p.child1.name2, p.name2)
self.assertEqual(p.child1.value, 1)
self.assertEqual(p.child1.child4.name1, p.child1.name1)
self.assertEqual(p.child1.child4.name2, p.child1.name2)
self.assertEqual(p.child1.child4.value, p.child1.value)
self.assertEqual(p.child1.child4.value4, 4)
@unittest.expectedFailure
def test_inheritance_deferred(self):
c = Child4.objects.create(name1='n1', name2='n2', value=1, value4=4)
with self.assertNumQueries(1):
p = Parent2.objects.select_related('child1').only(
'id2', 'child1__value').get(name2="n2")
self.assertEqual(p.id2, c.id2)
self.assertEqual(p.child1.value, 1)
p = Parent2.objects.select_related('child1').only(
'id2', 'child1__value').get(name2="n2")
with self.assertNumQueries(1):
self.assertEqual(p.name2, 'n2')
p = Parent2.objects.select_related('child1').only(
'id2', 'child1__value').get(name2="n2")
with self.assertNumQueries(1):
self.assertEqual(p.child1.name2, 'n2')
@unittest.expectedFailure
def test_inheritance_deferred2(self):
c = Child4.objects.create(name1='n1', name2='n2', value=1, value4=4)
qs = Parent2.objects.select_related('child1', 'child4').only(
'id2', 'child1__value', 'child1__child4__value4')
with self.assertNumQueries(1):
p = qs.get(name2="n2")
self.assertEqual(p.id2, c.id2)
self.assertEqual(p.child1.value, 1)
self.assertEqual(p.child1.child4.value4, 4)
self.assertEqual(p.child1.child4.id2, c.id2)
p = qs.get(name2="n2")
with self.assertNumQueries(1):
self.assertEqual(p.child1.name2, 'n2')
p = qs.get(name2="n2")
with self.assertNumQueries(1):
self.assertEqual(p.child1.name1, 'n1')
with self.assertNumQueries(1):
self.assertEqual(p.child1.child4.name1, 'n1')
class ReverseSelectRelatedValidationTests(SimpleTestCase):
"""
Rverse related fields should be listed in the validation message when an
invalid field is given in select_related().
"""
non_relational_error = "Non-relational field given in select_related: '%s'. Choices are: %s"
invalid_error = "Invalid field name(s) given in select_related: '%s'. Choices are: %s"
def test_reverse_related_validation(self):
fields = 'userprofile, userstat'
with self.assertRaisesMessage(FieldError, self.invalid_error % ('foobar', fields)):
list(User.objects.select_related('foobar'))
with self.assertRaisesMessage(FieldError, self.non_relational_error % ('username', fields)):
list(User.objects.select_related('username'))
| bsd-3-clause |
races1986/SafeLanguage | CEM/speedy_delete.py | 1 | 32436 | # -*- coding: utf-8 -*-
"""
This bot is used to quickly trawl through candidates for speedy deletion in a
fast and semi-automated fashion. The bot displays the contents of each page
one at a time and provides a prompt for the user to skip or delete the page.
Of course, this will require a sysop account.
Future upcoming options include the ability to untag a page as not being
eligible for speedy deletion, as well as the option to commute its sentence to
Proposed Deletion (see [[en:WP:PROD]] for more details). Also, if the article
text is long, to prevent terminal spamming, it might be a good idea to truncate
it just to the first so many bytes.
WARNING: This tool shows the contents of the top revision only. It is possible
that a vandal has replaced a perfectly good article with nonsense, which has
subsequently been tagged by someone who didn't realize it was previously a good
article. The onus is on you to avoid making these mistakes.
NOTE: This script currently only works for the Wikipedia project.
"""
#
# (C) Pywikipedia bot team, 2007-2010
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id: ae86a1c040f3e409c3d88dbe943c2729789379c7 $'
#
import wikipedia as pywikibot
import pagegenerators, catlib
import time
class SpeedyRobot:
""" This robot will load a list of pages from the category of candidates for
speedy deletion on the language's wiki and give the user an interactive
prompt to decide whether each should be deleted or not.
"""
csd_cat={
'wikipedia':{
'ab': u'Категория:Candidates for speedy deletion',
'ak': u'Category:Candidates for speedy deletion',
'ang': u'Flocc:Candidates for speedy deletion',
'ar': u'تصنيف:صفحات للحذف السريع',
'arc': u'Category:Candidates for speedy deletion',
'av': u'Категория:Candidates for speedy deletion',
'ay': u'Categoría:Candidates for speedy deletion',
'az': u'Kateqoriya:Vikipediya:Silinəcək səhifələr',
'ba': u'Категория:Delete',
'bar': u'Kategorie:Wikipedia:Schnelllöschen',
'bat-smg': u'Kateguorėjė:Kandėdatā skobē trintė',
'be': u'Катэгорыя:Артыкулы да выдалення',
'be-x-old': u'Катэгорыя:Вікіпэдыя:Кандыдатуры на выдаленьне',
'bh': u'Category:Candidates for speedy deletion',
'bi': u'Category:Candidates for speedy deletion',
'bn': u'বিষয়শ্রেণী:Candidates for speedy deletion',
'bo': u'Category:Candidates for speedy deletion',
'br': u'Rummad:Candidates for speedy deletion',
'bug': u'Kategori:Candidates for speedy deletion',
'bxr': u'Category:Candidates for speedy deletion',
'ca': u'Categoria:Sol·licituds de supressió immediata',
'cbk-zam': u'Categoría:Candidates for speedy deletion',
'ce': u'Тоба:Candidates for speedy deletion',
'ch': u'Katigoria:Candidates for speedy deletion',
'chr': u'Category:Candidates for speedy deletion',
'chy': u'Category:Candidates for speedy deletion',
'cr': u'Category:Candidates for speedy deletion',
'cs': u'Kategorie:Stránky ke smazání',
'cu': u'Катигорі́ꙗ:Страни́цѧ ничьжє́ниꙗ дѣлꙗ́',
'cv': u'Категори:Тӳрех кăларса пăрахмалли статьясем',
'de': u'Kategorie:Wikipedia:Schnelllöschen',
'diq': u'Category:Candidates for speedy deletion',
'dsb': u'Kategorija:Boki k malsnemu lašowanju',
'dv': u'ޤިސްމު:Candidates for speedy deletion',
'ee': u'Category:Candidates for speedy deletion',
'en': u'Category:Candidates for speedy deletion',
'es': u'Categoría:Wikipedia:Borrar (definitivo)',
'et': u'Kategooria:Kustutada',
'fa': u'رده:مقالههای نامزد حذف سریع',
'ff': u'Catégorie:Candidates for speedy deletion',
'fi': u'Luokka:Roskaa',
'fj': u'Category:Candidates for speedy deletion',
'fr': u'Catégorie:Wikipédia:Suppression immédiate demandée',
'frp': u'Catègorie:Candidates for speedy deletion',
'gd': u'Category:Candidates for speedy deletion',
'glk': u'رده:Candidates for speedy deletion',
'gn': u'Ñemohenda:Candidates for speedy deletion',
'gu': u'શ્રેણી:Candidates for speedy deletion',
'ha': u'Category:Candidates for speedy deletion',
'hak': u'Category:Candidates for speedy deletion',
'haw': u'Māhele:Candidates for speedy deletion',
'he': u'קטגוריה:ויקיפדיה: למחיקה מהירה',
'hsb': u'Kategorija:Strony k spěšnemu wušmórnjenju',
'ht': u'Kategori:Candidates for speedy deletion',
'ia': u'Categoria:Wikipedia:Eliminar',
'ie': u'Category:Candidates for speedy deletion',
'ig': u'Category:Candidates for speedy deletion',
'ik': u'Category:Candidates for speedy deletion',
'ilo': u'Category:Candidates for speedy deletion',
'it': u'Categoria:Da cancellare subito',
'iu': u'Category:Candidates for speedy deletion',
'ja': u'Category:即時削除対象のページ',
'jbo': u'Category:Candidates for speedy deletion',
'ka': u'კატეგორია:სწრაფი წაშლის კანდიდატები',
'kg': u'Category:Candidates for speedy deletion',
'ki': u'Category:Candidates for speedy deletion',
'kl': u'Kategori:Candidates for speedy deletion',
'ko': u'분류:삭제 신청 문서',
'ks': u'Category:Candidates for speedy deletion',
'kv': u'Категория:Wikipedia:Candidates for speedy deletion',
'kw': u'Category:Candidates for speedy deletion',
'ky': u'Category:Deletion',
'lad': u'Categoría:Candidates for speedy deletion',
'lg': u'Category:Candidates for speedy deletion',
'lij': u'Categorîa:Candidates for speedy deletion',
'ln': u'Catégorie:Candidates for speedy deletion',
'lt': u'Kategorija:Kandidatai skubiai trinti',
'mg': u'Sokajy:Candidates for speedy deletion',
'mk': u'Категорија:Страници за брзо бришење',
'ml': u'വര്ഗ്ഗം:Candidates for speedy deletion',
'mn': u'Ангилал:Устгалд орох хуудсууд',
'na': u'Category:Candidates for speedy deletion',
'nah': u'Neneuhcāyōtl:Huiquipedia:Borrar (definitivo)',
'nds': u'Kategorie:Wikipedia:Gauweg',
'ng': u'Category:Candidates for speedy deletion',
'nl': u'Categorie:Wikipedia:Nuweg',
'no': u'Kategori:Sider som er foreslått raskt slettet',
'nov': u'Category:Candidates for speedy deletion',
'nrm': u'Category:Candidates for speedy deletion',
'nv': u'T\'ááłáhági át\'éego:Candidates for speedy deletion',
'ny': u'Category:Candidates for speedy deletion',
'om': u'Category:Wikipedia:Candidates for speedy deletion',
'or': u'Category:Candidates for speedy deletion',
'os': u'Категори:Википеди:Аппарынмæ лæвæрд фæрстæ',
'pa': u'ਸ਼੍ਰੇਣੀ:Delete',
'pag': u'Category:Candidates for speedy deletion',
'pam': u'Category:Candidates for speedy deletion',
'pdc': u'Kategorie:Wikipedia:Lösche',
'pih': u'Category:Candidates for speedy deletion',
'pl': u'Kategoria:Ekspresowe kasowanko',
'pt': u'Categoria:Páginas para eliminação rápida',
'rn': u'Category:Candidates for speedy deletion',
'ro': u'Categorie:Pagini de şters rapid',
'roa-tara': u'Category:Candidates for speedy deletion',
'ru': u'Категория:Википедия:К быстрому удалению',
'rw': u'Category:Candidates for speedy deletion',
'sa': u'वर्गः:Candidates for speedy deletion',
'sco': u'Category:Candidates for speedy deletion',
'sd': u'زمرو:ترت ڊاٺ جا اميدوار',
'simple': u'Category:Quick deletion requests',
'sl': u'Kategorija:Predlogi za hitro brisanje',
'sm': u'Category:Candidates for speedy deletion',
'sn': u'Category:Candidates for speedy deletion',
'sr': u'Категорија:Брзо брисање',
'ss': u'Category:Candidates for speedy deletion',
'st': u'Category:Candidates for speedy deletion',
'stq': u'Kategorie:Candidates for speedy deletion',
'sv': u'Kategori:Snabba raderingar',
'sw': u'Jamii:Deleteme',
'te': u'వర్గం:Candidates for speedy deletion',
'tg': u'Гурӯҳ:Мақолаҳои номзади ҳазф',
'th': u'หมวดหมู่:หน้าที่ถูกแจ้งลบ',
'ti': u'Category:Candidates for speedy deletion',
'tk': u'Category:Deleteme',
'tr': u'Kategori:Vikipedi silinecek sayfalar',
'ts': u'Category:Candidates for speedy deletion',
'tt': u'Törkem:Candidates for speedy deletion',
'tum': u'Category:Candidates for speedy deletion',
'tw': u'Category:Candidates for speedy deletion',
'ug': u'Category:Candidates for speedy deletion',
'uk': u'Категорія:Статті до швидкого вилучення',
'uz': u'Turkum:Vikipediya:Yoʻqotilish uchun maqolalar',
've': u'Category:Candidates for speedy deletion',
'vec': u'Categoria:Da cancełare subito',
'vi': u'Thể loại:Chờ xoá',
'vls': u'Categorie:Wikipedia:Nuweg',
'vo': u'Klad:Pads moükabik',
'war': u'Category:Candidates for speedy deletion',
'xal': u'Янз:Candidates for speedy deletion',
'xh': u'Category:Candidates for speedy deletion',
'yo': u'Ẹ̀ka:Candidates for speedy deletion',
'za': u'分类:Candidates for speedy deletion',
'zh': u'Category:快速删除候选',
'zh-classical': u'Category:速刪候',
'zh-yue': u'Category:快速刪除候選',
'zu': u'Category:Candidates for speedy deletion',
},
'wikinews':{
'ar': u'تصنيف:صفحات حذف سريع',
'en': u'Category:Speedy deletion',
'ja': u'Category:即時削除',
'zh': u'Category:快速删除候选',
},
'wikisource':{
'ar': u'تصنيف:صفحات حذف سريع',
'id': u'Kategori:Usulan penghapusan',
'ja': u'Category:即時削除',
'no': u'Kategori:Sider som er foreslått raskt slettet',
'pt': u'Categoria:!Páginas para eliminação rápida',
'ro': u'Categorie:Propuneri pentru ştergere',
'zh': u'Category:快速删除候选',
},
'wikiversity':{
'beta': u'Category:Candidates for speedy deletion',
'cs': u'Kategorie:Stránky ke smazání',
'de': u'Kategorie:Wikiversity:Löschen',
'el': u'Κατηγορία:Σελίδες για γρήγορη διαγραφή',
'en': u'Category:Candidates for speedy deletion',
'es': u'Categoría:Wikiversidad:Borrar (definitivo)',
'it': u'Categoria:Da cancellare subito',
'ja': u'Category:Candidates for speedy deletion',
'pt': u'Categoria:!Páginas para eliminação rápida',
},
'wikiquote':{
'ar': u'تصنيف:صفحات للحذف السريع',
'cs': u'Kategorie:Údržba:Stránky ke smazání',
'en': u'Category:Candidates for speedy deletion',
'fi': u'Luokka:Roskaa',
'ja': u'Category:即時削除',
'ru': u'Категория:Викицитатник:К быстрому удалению',
'simple': u'Category:Quick deletion requests',
'zh': u'Category:快速删除候选',
},
'wiktionary':{
'ar': u'تصنيف:صفحات حذف سريع',
'en': u'Category:Candidates for speedy deletion',
'fi': u'Luokka:Roskaa',
'fr': u'Catégorie:Pages à supprimer rapidement',
'ja': u'Category:即時削除',
'simple': u'Category:Quick deletion requests',
'tt': u'Törkem:Candidates for speedy deletion',
'zh': u'Category:快速删除候选',
},
'wikibooks':{
'ar': u'تصنيف:صفحات حذف سريع',
'ca': u'Categoria:Elements a eliminar',
'en': u'Category:Candidates for speedy deletion',
'es': u'Categoría:Wikilibros:Borrar',
'it': u'Categoria:Da cancellare subito',
'ja': u'Category:即時削除',
'pl': u'Kategoria:Ekspresowe kasowanko',
'zh': u'Category:快速删除候选',
},
'meta':{'meta': u'Category:Deleteme',},
'commons':{'commons': u'Category:Candidates for speedy deletion',},
'incubator':{'incubator': u'Category:Maintenance:Delete',},
'mediawiki':{'mediawiki': u'Category:Candidates for deletion',},
}
# If the site has several templates for speedy deletion, it might be
# possible to find out the reason for deletion by the template used.
# _default will be used if no such semantic template was used.
deletion_messages = {
'wikipedia':{
'ar': {
'_default': u'حذف مرشح للحذف السريع حسب [[وProject:حذف سريع|معايير الحذف السريع]]',
},
'cs': {
'_default': u'Bylo označeno k [[Wikipedie:Rychlé smazání|rychlému smazání]]',
},
'de': {
'_default': u'Lösche Artikel mit [[Wikipedia:Schnelllöschantrag|Schnelllöschantrag]]',
},
'en': {
'_default': u'Deleting candidate for speedy deletion per [[WP:CSD|CSD]]',
'db-author': u'Deleting page per [[WP:CSD|CSD]] G7: Author requests deletion and is its only editor.',
'db-nonsense': u'Deleting page per [[WP:CSD|CSD]] G1: Page is patent nonsense or gibberish.',
'db-test': u'Deleting page per [[WP:CSD|CSD]] G2: Test page.',
'db-nocontext': u'Deleting page per [[WP:CSD|CSD]] A1: Short article that provides little or no context.',
'db-empty': u'Deleting page per [[WP:CSD|CSD]] A1: Empty article.',
'db-attack': u'Deleting page per [[WP:CSD|CSD]] G10: Page that exists solely to attack its subject.',
'db-catempty': u'Deleting page per [[WP:CSD|CSD]] C1: Empty category.',
'db-band': u'Deleting page per [[WP:CSD|CSD]] A7: Article about a non-notable band.',
'db-banned': u'Deleting page per [[WP:CSD|CSD]] G5: Page created by a banned user.',
'db-bio': u'Deleting page per [[WP:CSD|CSD]] A7: Article about a non-notable person.',
'db-notenglish': u'Deleting page per [[WP:CSD|CSD]] A2: Article isn\'t written in English.',
'db-copyvio': u'Deleting page per [[WP:CSD|CSD]] G12: Page is a blatant copyright violation.',
'db-repost': u'Deleting page per [[WP:CSD|CSD]] G4: Recreation of previously deleted material.',
'db-vandalism': u'Deleting page per [[WP:CSD|CSD]] G3: Blatant vandalism.',
'db-talk': u'Deleting page per [[WP:CSD|CSD]] G8: Talk page of a deleted or non-existent page.',
'db-spam': u'Deleting page per [[WP:CSD|CSD]] G11: Blatant advertising.',
'db-disparage': u'Deleting page per [[WP:CSD|CSD]] T1: Divisive or inflammatory template.',
'db-r1': u'Deleting page per [[WP:CSD|CSD]] R1: Redirect to a deleted or non-existent page.',
'db-experiment': u'Deleting page per [[WP:CSD|CSD]] G2: Page was created as an experiment.',
},
'fa': {
'_default': u'حذف مرشَّح للحذف السريع حسب [[ويكيبيديا:حذف سريع|معايير الحذف السريع]]',
},
'he': {
'_default': u'מחיקת מועמד למחיקה מהירה לפי [[ויקיפדיה:מדיניות המחיקה|מדיניות המחיקה]]',
u'גם בוויקישיתוף': u'הקובץ זמין כעת בוויקישיתוף.',
},
'ja':{
'_default': u'[[WP:CSD|即時削除の方針]]に基づい削除',
},
'pt': {
'_default': u'Apagando página por [[Wikipedia:Páginas para eliminar|eliminação rápida]]',
},
'pl': {
'_default': u'Usuwanie artykułu zgodnie z zasadami [[Wikipedia:Ekspresowe kasowanko|ekspresowego kasowania]]',
},
'it': {
'_default': u'Rimuovo pagina che rientra nei casi di [[Wikipedia:IMMEDIATA|cancellazione immediata]].',
},
'zh':{
'_default': u'[[WP:CSD]]',
'advert': 'ad',
'db-blanked': 'auth',
'db-spam': u'[[WP:CSD#G11|CSD G11]]: 廣告、宣傳頁面',
'db-rediruser': u'[[WP:CSD#O1|CSD O6]] 沒有在使用的討論頁',
'notchinese': u'[[WP:CSD#G7|CSD G7]]: 非中文條目且長時間未翻譯',
'db-vandalism': 'vand',
u'翻译': 'oprj',
u'翻譯': 'oprj',
'notchinese': 'oprj',
'notmandarin': 'oprj',
'no source': u'[[WP:CSD#I3|CSD I3]]: 沒有來源連結,無法確認來源與版權資訊',
'no license': u'[[WP:CSD#I3|CSD I3]]: 沒有版權模板,無法確認版權資訊',
'unknown': u'[[WP:CSD#I3|CSD I3]]: 沒有版權模板,無法確認版權資訊',
'temppage': u'[[WP:CSD]]: 臨時頁面',
'nowcommons':'commons',
'roughtranslation':'mactra',
},
},
'wikinews':{
'en':{
'_default': u'[[WN:CSD]]',
},
'zh':{
'_default': u'[[WN:CSD]]',
},
},
}
# Default reason for deleting a talk page.
talk_deletion_msg={
'wikipedia':{
'ar': u'صفحة نقاش يتيمة',
'cs': u'Osiřelá diskusní stránka',
'de': u'Verwaiste Diskussionsseite',
'en': u'Orphaned talk page',
'fa': u'بحث یتیم',
'fr': u'Page de discussion orpheline',
'he': u'דף שיחה של ערך שנמחק',
'it': u'Rimuovo pagina di discussione di una pagina già cancellata',
'pl': u'Osierocona strona dyskusji',
'pt': u'Página de discussão órfã',
'zh': u'[[WP:CSD#O1|CSD O1 O2 O6]] 沒有在使用的討論頁',
},
'wikinews':{
'en': u'Orphaned talk page',
'zh': u'[[WN:CSD#O1|CSD O1 O2 O6]] 沒有在使用的討論頁',
}
}
# A list of often-used reasons for deletion. Shortcuts are keys, and
# reasons are values. If the user enters a shortcut, the associated reason
# will be used.
delete_reasons = {
'wikipedia': {
'de': {
'asdf': u'Tastaturtest',
'egal': u'Eindeutig irrelevant',
'ka': u'Kein Artikel',
'mist': u'Unsinn',
'move': u'Redirectlöschung, um Platz für Verschiebung zu schaffen',
'nde': u'Nicht in deutscher Sprache verfasst',
'pfui': u'Beleidigung',
'redir': u'Unnötiger Redirect',
'spam': u'Spam',
'web': u'Nur ein Weblink',
'wg': u'Wiedergänger (wurde bereits zuvor gelöscht)',
},
'it': {
'test': u'Si tratta di un test',
'vandalismo': u'Caso di vandalismo',
'copyviol': 'Violazione di copyright',
'redirect': 'Redirect rotto o inutile',
'spam': 'Spam',
'promo': 'Pagina promozionale',
},
'ja':{
'cont': u'[[WP:CSD]] 全般1 意味不明な内容のページ',
'test': u'[[WP:CSD]] 全般2 テスト投稿',
'vand': u'[[WP:CSD]] 全般3 荒らしand/orいたずら',
'ad': u'[[WP:CSD]] 全般4 宣伝',
'rep': u'[[WP:CSD]] 全般5 削除されたページの改善なき再作成',
'cp': u'[[WP:CSD]] 全般6 コピペ移動or分割',
'sh': u'[[WP:CSD]] 記事1 短すぎ',
'nd': u'[[WP:CSD]] 記事1 定義なし',
'auth': u'[[WP:CSD]] 記事3 投稿者依頼or初版立項者による白紙化',
'nr': u'[[WP:CSD]] リダイレクト1 無意味なリダイレクト',
'nc': u'[[WP:CSD]] リダイレクト2 [[WP:NC]]違反',
'ren': u'[[WP:CSD]] リダイレクト3 改名提案を経た曖昧回避括弧付きの移動の残骸',
'commons': u'[[WP:CSD]] マルチメディア7 コモンズの画像ページ',
'tmp': u'[[WP:CSD]] テンプレート1 初版投稿者依頼',
'uau': u'[[WP:CSD]] 利用者ページ1 本人希望',
'nuu': u'[[WP:CSD]] 利用者ページ2 利用者登録されていない利用者ページ',
'ipu': u'[[WP:CSD]] 利用者ページ3 IPユーザの利用者ページ',
},
'zh':{
'empty': u'[[WP:CSD#G1]]: 沒有實際內容或歷史記錄的文章。',
'test': u'[[WP:CSD#G2]]: 測試頁',
'vand': u'[[WP:CSD#G3]]: 純粹破壞',
'rep': u'[[WP:CSD#G5]]: 經討論被刪除後又重新創建的內容',
'repa': u'[[WP:CSD#G5]]: 重複的文章',
'oprj': u'[[WP:CSD#G7]]: 內容來自其他中文計劃',
'move': u'[[WP:CSD#G8]]: 依[[Wikipedia:移動請求|移動請求]]暫時刪除以進行移動或合併頁面之工作',
'auth': u'[[WP:CSD#G10]]: 原作者請求',
'ad': u'[[WP:CSD#G11]]: 明顯的以廣告宣傳為目而建立的頁面',
'adc': u'[[WP:CSD#G11]]: 只有條目名稱中的人物或團體之聯絡資訊',
'bio': u'[[WP:CSD#G12]]: 未列明來源及語調負面的生者傳記',
'mactra': u'[[WP:CSD#G13]]: 明顯的機器翻譯',
'notrans': u'[[WP:CSD#G14]]: 未翻譯的頁面',
'isol': u'[[WP:CSD#G15]]: 孤立頁面',
'isol-f': u'[[WP:CSD#G15]]: 孤立頁面-沒有對應檔案的檔案頁面',
'isol-sub': u'[[WP:CSD#G15]]: 孤立頁面-沒有對應母頁面的子頁面',
'tempcp': u'[[WP:CSD#G16]]: 臨時頁面依然侵權',
'cont': u'[[WP:CSD#A1]]: 非常短,而且沒有定義或內容。',
'nocont': u'[[WP:CSD#A2]]: 內容只包括外部連接、參見、圖書參考、類別標籤、模板標籤、跨語言連接的條目',
'nc': u'[[WP:CSD#A3]]: 跨計劃內容',
'cn': u'[[WP:CSD#R2]]: 跨空間重定向',
'wr': u'[[WP:CSD#R3]]: 錯誤重定向',
'slr': u'[[WP:CSD#R5]]: 指向本身的重定向或循環的重定向',
'repi': u'[[WP:CSD#F1]]: 重複的檔案',
'lssd': u'[[WP:CSD#F3]]: 沒有版權或來源資訊,無法確認圖片是否符合方針要求',
'nls': u'[[WP:CSD#F3]]: 沒有版權模板,無法確認版權資訊',
'svg': u'[[WP:CSD#F5]]: 被高解析度與SVG檔案取代的圖片',
'ui': u'[[WP:CSD#F6]]: 圖片未使用且不自由',
'commons': u'[[WP:CSD#F7]]: 此圖片已存在於[[:commons:|維基共享資源]]',
'urs': u'[[WP:CSD#O1]]: 用戶請求刪除自己的用戶頁子頁面',
'anou': u'[[WP:CSD#O3]]: 匿名用戶的用戶討論頁,其中的內容不再有用',
'uc': u'[[WP:CSD#O4]]: 空類別',
'tmp': u'[[WP:CSD]]: 臨時頁面',
},
},
}
def __init__(self):
"""
Arguments:
none yet
"""
self.mySite = pywikibot.getSite()
self.csdCat = catlib.Category(self.mySite,
pywikibot.translate(self.mySite,
self.csd_cat))
self.savedProgress = None
self.preloadingGen = None
def guessReasonForDeletion(self, page):
reason = None
# TODO: The following check loads the page 2 times. Find a better way to
# do it.
if page.isTalkPage() and (page.toggleTalkPage().isRedirectPage() or
not page.toggleTalkPage().exists()):
# This is probably a talk page that is orphaned because we
# just deleted the associated article.
reason = pywikibot.translate(self.mySite, self.talk_deletion_msg)
else:
# Try to guess reason by the template used
templateNames = page.templatesWithParams()
reasons = pywikibot.translate(self.mySite, self.deletion_messages)
for templateName in templateNames:
if templateName[0].lower() in reasons:
if type(reasons[templateName[0].lower()]) is not unicode:
#Make alias to delete_reasons
reason = pywikibot.translate(self.mySite,
self.delete_reasons)[reasons[templateName[0].lower()]]
else:
reason = reasons[templateName[0].lower()]
break
if not reason:
# Unsuccessful in guessing the reason. Use a default message.
reason = reasons['_default']
return reason
def getReasonForDeletion(self, page):
suggestedReason = self.guessReasonForDeletion(page)
pywikibot.output(
u'The suggested reason is: \03{lightred}%s\03{default}'
% suggestedReason)
# We don't use pywikibot.translate() here because for some languages the
# entry is intentionally left out.
if self.mySite.family.name in self.delete_reasons:
if page.site().lang in self.delete_reasons[self.mySite.family.name]:
localReasons = pywikibot.translate(page.site().lang,
self.delete_reasons)
pywikibot.output(u'')
localReasoneKey = localReasons.keys()
localReasoneKey.sort()
for key in localReasoneKey:
pywikibot.output((key + ':').ljust(8) + localReasons[key])
pywikibot.output(u'')
reason = pywikibot.input(
u'Please enter the reason for deletion, choose a default reason, or press enter for the suggested message:')
if reason.strip() in localReasons:
reason = localReasons[reason]
else:
reason = pywikibot.input(
u'Please enter the reason for deletion, or press enter for the suggested message:')
else:
reason = pywikibot.input(
u'Please enter the reason for deletion, or press enter for the suggested message:')
if not reason:
reason = suggestedReason
return reason
def run(self):
"""
Starts the robot's action.
"""
keepGoing = True
startFromBeginning = True
while keepGoing:
if startFromBeginning:
self.savedProgress = None
self.refreshGenerator()
count = 0
for page in self.preloadingGen:
try:
pageText = page.get(get_redirect = True).split("\n")
count += 1
except pywikibot.NoPage:
pywikibot.output(
u'Page %s does not exist or has already been deleted, skipping.'
% page.title(asLink=True))
continue
# Show the title of the page we're working on.
# Highlight the title in purple.
pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% page.title())
pywikibot.output(u'- - - - - - - - - ')
if len(pageText) > 75:
pywikibot.output(
'The page detail is too many lines, only output first 50 lines:')
pywikibot.output(u'- ' * 9)
pywikibot.output(u'\n'.join(pageText[:50]))
else:
pywikibot.output(u'\n'.join(pageText))
pywikibot.output(u'- - - - - - - - - ')
choice = pywikibot.inputChoice(u'Input action?',
['delete', 'skip', 'update',
'quit'],
['d', 'S', 'u', 'q'], 'S')
if choice == 'q':
keepGoing = False
break
elif choice == 'u':
pywikibot.output(u'Updating from CSD category.')
self.savedProgress = page.title()
startFromBeginning = False
break
elif choice == 'd':
reason = self.getReasonForDeletion(page)
pywikibot.output(
u'The chosen reason is: \03{lightred}%s\03{default}'
% reason)
page.delete(reason, prompt = False)
else:
pywikibot.output(u'Skipping page %s' % page.title())
startFromBeginning = True
if count == 0:
if startFromBeginning:
pywikibot.output(
u'There are no pages to delete.\nWaiting for 30 seconds or press Ctrl+C to quit...')
try:
time.sleep(30)
except KeyboardInterrupt:
keepGoing = False
else:
startFromBeginning = True
pywikibot.output(u'Quitting program.')
def refreshGenerator(self):
generator = pagegenerators.CategorizedPageGenerator(
self.csdCat, start=self.savedProgress)
# wrap another generator around it so that we won't produce orphaned
# talk pages.
generator2 = pagegenerators.PageWithTalkPageGenerator(generator)
self.preloadingGen = pagegenerators.PreloadingGenerator(generator2,
pageNumber=20)
def main():
# read command line parameters
for arg in pywikibot.handleArgs():
pass #No args yet
bot = SpeedyRobot()
bot.run()
if __name__ == "__main__":
try:
main()
finally:
pywikibot.stopme()
| epl-1.0 |
pschwartz/ansible | v1/ansible/runner/action_plugins/script.py | 106 | 5700 | # (c) 2012, 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/>.
import os
import re
import shlex
import ansible.constants as C
from ansible.utils import template
from ansible import utils
from ansible import errors
from ansible.runner.return_data import ReturnData
class ActionModule(object):
TRANSFERS_FILES = True
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
''' handler for file transfer operations '''
if self.runner.noop_on_check(inject):
# in check mode, always skip this module
return ReturnData(conn=conn, comm_ok=True,
result=dict(skipped=True, msg='check mode not supported for this module'))
# extract ansible reserved parameters
# From library/command keep in sync
creates = None
removes = None
r = re.compile(r'(^|\s)(creates|removes)=(?P<quote>[\'"])?(.*?)(?(quote)(?<!\\)(?P=quote))((?<!\\)(?=\s)|$)')
for m in r.finditer(module_args):
v = m.group(4).replace("\\", "")
if m.group(2) == "creates":
creates = v
elif m.group(2) == "removes":
removes = v
module_args = r.sub("", module_args)
if creates:
# do not run the command if the line contains creates=filename
# and the filename already exists. This allows idempotence
# of command executions.
module_args_tmp = "path=%s" % creates
module_return = self.runner._execute_module(conn, tmp, 'stat', module_args_tmp, inject=inject,
complex_args=complex_args, persist_files=True)
stat = module_return.result.get('stat', None)
if stat and stat.get('exists', False):
return ReturnData(
conn=conn,
comm_ok=True,
result=dict(
changed=False,
msg=("skipped, since %s exists" % creates)
)
)
if removes:
# do not run the command if the line contains removes=filename
# and the filename does not exist. This allows idempotence
# of command executions.
module_args_tmp = "path=%s" % removes
module_return = self.runner._execute_module(conn, tmp, 'stat', module_args_tmp, inject=inject,
complex_args=complex_args, persist_files=True)
stat = module_return.result.get('stat', None)
if stat and not stat.get('exists', False):
return ReturnData(
conn=conn,
comm_ok=True,
result=dict(
changed=False,
msg=("skipped, since %s does not exist" % removes)
)
)
# Decode the result of shlex.split() to UTF8 to get around a bug in that's been fixed in Python 2.7 but not Python 2.6.
# See: http://bugs.python.org/issue6988
tokens = shlex.split(module_args.encode('utf8'))
tokens = [s.decode('utf8') for s in tokens]
# extract source script
source = tokens[0]
# FIXME: error handling
args = " ".join(tokens[1:])
source = template.template(self.runner.basedir, source, inject)
if '_original_file' in inject:
source = utils.path_dwim_relative(inject['_original_file'], 'files', source, self.runner.basedir)
else:
source = utils.path_dwim(self.runner.basedir, source)
# transfer the file to a remote tmp location
source = source.replace('\x00', '') # why does this happen here?
args = args.replace('\x00', '') # why does this happen here?
tmp_src = conn.shell.join_path(tmp, os.path.basename(source))
tmp_src = tmp_src.replace('\x00', '')
conn.put_file(source, tmp_src)
sudoable = True
# set file permissions, more permissive when the copy is done as a different user
if self.runner.become and self.runner.become_user != 'root':
chmod_mode = 'a+rx'
sudoable = False
else:
chmod_mode = '+rx'
self.runner._remote_chmod(conn, chmod_mode, tmp_src, tmp, sudoable=sudoable, become=self.runner.become)
# add preparation steps to one ssh roundtrip executing the script
env_string = self.runner._compute_environment_string(conn, inject)
module_args = ' '.join([env_string, tmp_src, args])
handler = utils.plugins.action_loader.get('raw', self.runner)
result = handler.run(conn, tmp, 'raw', module_args, inject)
# clean up after
if "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES:
self.runner._remove_tmp_path(conn, tmp)
result.result['changed'] = True
return result
| gpl-3.0 |
smartfile/django-secureform | django_secureform/forms/__init__.py | 1 | 14177 | import django
import time
import string
from Crypto.Random import random
from Crypto.Cipher import Blowfish
from django import forms
from django.conf import settings
from django.core.cache import cache
from django.forms import widgets
from django.forms.forms import pretty_name
from django.forms.forms import NON_FIELD_ERRORS
from django.forms.forms import BoundField
from django.forms.forms import DeclarativeFieldsMetaclass
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
if django.VERSION < (1, 7):
from django.forms.util import ErrorDict
else:
from django.forms.utils import ErrorDict
try:
# Django <= 1.6 backwards compatibility
from django.utils import simplejson as json
except ImportError:
# Django >= 1.7
import json
# Chars that are safe to use in field names.
SAFE_CHARS = string.ascii_letters + string.digits
JQUERY_TAG = '<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>'
SCRIPT_TAG = '''<script type="text/javascript">
function %(function)s(n)
{$('p'+','+'li,'+'tr'+',div.control-group')
.has('input[id="id_' + n + '"]')
.remove();}%(obfuscated)s
</script>'''
# Allow the user to specify an encryption key separate from the Django
# SECRET_KEY if they wish.
DEFAULT_CRYPT_KEY = getattr(settings, 'SECUREFORM_CRYPT_KEY', getattr(settings, 'SECRET_KEY', None))
# The user can override the secure field name.
DEFAULT_FIELD_NAME = getattr(settings, 'SECUREFORM_FIELD_NAME', 'secure')
# Give the user twenty minutes to fill out the form.
DEFAULT_FORM_TTL = getattr(settings, 'SECUREFORM_TTL', 1200)
# Inject random fields that are hidden from the user (and should be blank).
DEFAULT_HONEYPOTS = getattr(settings, 'SECUREFORM_HONEYPOTS', 2)
# Include jQuery, used to hide honeypots (probably could do the job without it).
DEFAULT_INCLUDE_JQUERY = getattr(settings, 'SECUREFORM_INCLUDE_JQUERY', True)
def random_name(choices=SAFE_CHARS, length=16):
return ''.join(random.sample(choices, length))
def testing():
"""
Detects if we are running under Django unit tests. If so, security is
disabled.
"""
return getattr(settings, 'TESTING', False)
class SecureFormException(Exception):
'Base exception for security faults.'
class StaleFormException(SecureFormException):
'Raised if a form\'s timestamp is too old.'
class ReplayedFormException(SecureFormException):
'Raised if a form\'s nonce value has been seen before.'
class HoneypotFormException(SecureFormException):
'Raised if a honeypot field receives a value.'
class InvalidFormException(SecureFormException):
'Raised if a fields do not map properly.'
class HoneypotField(forms.CharField):
'Just a CharField that we can easily identify with isinstance().'
def __init__(self, *args, **kwargs):
kwargs.update({
'required': False,
'max_length': 16,
})
super(HoneypotField, self).__init__(*args, **kwargs)
class InitialValueField(forms.CharField):
'''A field that always assumes the initial value. Used for the "secure" field
so that we can always control it's value.'''
def bound_data(self, data, initial):
return initial
class SecureBoundField(BoundField):
'''The "secure" flavor of the BoundField. Handles translations between
secure names and rightful names.'''
def _errors(self):
'''Translates errors from field's secure name to the regular name (which is
how errors are stored in the form.)'''
name = self.form._secure_field_map.get(self.name)
return self.form.errors.get(name, self.form.error_class())
errors = property(_errors)
def _data(self):
'''Get data using the secure field name. Ensures bound forms are not reset to
blank values.'''
name = self.form._secure_field_map.get(self.name)
return self.field.widget.value_from_datadict(self.form.data, self.form.files, name)
data = property(_data)
def value(self):
"""
Returns the value for this BoundField, using the initial value if
the form is not bound or the data otherwise. Takes care of secure name
conversion.
"""
name = self.form._secure_field_map.get(self.name)
initial = self.form.initial.get(name, self.field.initial)
if not self.form.is_bound:
data = initial
if callable(data):
data = data()
else:
data = self.field.bound_data(
self.data, initial
)
return self.field.prepare_value(data)
class SecureFormOptions(object):
'Contains options for the SecureForm instance.'
def __init__(self, options=None):
self.secure_field_name = getattr(options, 'secure_field_name', DEFAULT_FIELD_NAME)
self.form_ttl = getattr(options, 'form_ttl', DEFAULT_FORM_TTL)
self.honeypots = getattr(options, 'honeypots', DEFAULT_HONEYPOTS)
self.include_jquery = getattr(options, 'include_jquery', DEFAULT_INCLUDE_JQUERY)
class SecureFormMetaclass(DeclarativeFieldsMetaclass):
'Metaclass to collect the options from the special Meta class.'
def __new__(cls, name, bases, attrs):
new_class = super(SecureFormMetaclass, cls).__new__(cls, name, bases, attrs)
new_class._meta = SecureFormOptions(getattr(new_class, 'Meta', None))
return new_class
class SecureFormBase(forms.Form):
"""This form is meant to defeat spam bots. It does this using a couple of techniques.
1. First of all, it will randomize the form field names.
2. It will add a hidden field which contains an encrypted map of random field names
to actual field names. It will also contain a timestamp and nonce value to defeat
replay attacks.
3. It will create two canary or honeypot fields that are expected to be left blank.
4. It will include a snippet of javascript that hides the two honeypot fields using CSS.
This should be effective to block spammers of multiple varieties.
1. Spambots that simply replay the form submission will be foiled by replay protection.
2. Spambots that fetch then post the form back will be foiled by the honeypot fields
unless they have a full javascript engine.
3. Humans on the other hand will still be able to submit the form, whether they are
legitimate or not. However, this activity will be cost prohibitive for spammers.
"""
def __init__(self, *args, **kwargs):
super(SecureFormBase, self).__init__(*args, **kwargs)
# Use defaults, unless the caller overrode them.
crypt_key = kwargs.pop('crypt_key', DEFAULT_CRYPT_KEY)
self.crypt = Blowfish.new(crypt_key)
self.fields[self._meta.secure_field_name] = InitialValueField(required=False, widget=widgets.HiddenInput)
self.__secured = False
self._secure_field_map = {}
def __iter__(self):
'''Iterates through the form fields, after ensuring that the security data,
including all additional fields are in place.'''
if not self.__secured:
# Only secure on the first iteration.
self.__secured = True
self.secure_data()
for name in self.fields:
yield self[name]
def __getitem__(self, name):
'Returns a SecureBoundField with the given name.'
if not testing():
try:
return SecureBoundField(self, self.fields[name], name)
except KeyError:
raise KeyError('Key %r not found in Form' % name)
return super(SecureFormBase, self).__getitem__(name)
def _script(self):
'''Generates the JavaScript necessary for hiding the honeypots or an empty string
if no honeypots are requested.'''
if not self._meta.honeypots:
return ''
honeypots = [n for (n, f) in self.fields.items() if isinstance(f, HoneypotField)]
func = random_name(choices=string.letters)
name = random_name(choices=string.letters, length=2)
obs = []
for honeypot in honeypots:
orig = [c for c in honeypot]
shuf = random.sample(orig, len(orig))
pmap = map(shuf.index, orig)
obs.extend([
'var %s = [\'%s\'];' % (name, '\', \''.join(shuf)),
'%s(%s);' % (func, '+'.join(['%s[%s]' % (name, p) for p in pmap])),
])
scripts = [
SCRIPT_TAG % dict(function=func, obfuscated='\n'.join(obs))
]
if self._meta.include_jquery:
scripts.insert(0, JQUERY_TAG)
return mark_safe('\n'.join(scripts))
script = property(_script)
def decode_data(self):
'''The workhorse for validating inbound POST or GET data. It will verify the TTL and
nonce. If those are valid, then the fields are converted back to their rightful names
and while the honeypots are checked to ensure they are empty.'''
if not self.is_bound:
return
if testing():
return
cleaned_data = {}
secure = self.data[self._meta.secure_field_name]
secure = self.crypt.decrypt(secure.decode('hex')).rstrip()
secure = json.loads(secure)
timestamp = secure['t']
if timestamp < time.time() - self._meta.form_ttl:
# Form data is too old, reject the form.
raise StaleFormException(_('The form data is more than %s seconds old.') %
self._meta.form_ttl)
nonce = secure['n']
if cache.get(nonce) is not None:
# Our nonce is in our cache, it has been seen, possible replay!
raise ReplayedFormException(_('This form has already been submitted.'))
# We only need to keep the nonce around for as long as the TTL (timeout). After
# that, the timestamp check will refuse the form. That is the whole idea behind
# the TTL/timeout, we can't guarantee the cache's availability long-term.
cache.set(nonce, nonce, self._meta.form_ttl)
self._secure_field_map = secure['f']
for sname, name in self._secure_field_map.items():
if name == self._meta.secure_field_name:
cleaned_data[name] = self.data[name]
continue
if name is None:
# This field is a honeypot.
if self.data.get(sname):
# Having a value in the honeypot field is bad news!
raise HoneypotFormException(_('Unexpected value in form field.'))
continue
try:
cleaned_data[name] = self.data[sname]
except KeyError:
# The field is missing from the data, that is OK, regular validation
# will catch this if the field is required.
pass
self.data = cleaned_data
def _clean_secure(self):
'''Uses decode_data() to convert fields back to their rightful names. Turns exceptions
into validation errors.'''
try:
self.decode_data()
except SecureFormException, e:
self._errors[NON_FIELD_ERRORS] = self.error_class([str(e)])
except Exception, e:
self._errors[NON_FIELD_ERRORS] = self.error_class([_('Form verification failed. Please try again.')])
def full_clean(self):
'Does secureform validation, then regular validation.'
self._errors = ErrorDict()
self._clean_secure()
if not self._errors:
super(SecureFormBase, self).full_clean()
def secure_data(self):
'Prepares the secure data before the form is rendered.'
if testing():
return
# Empty out the previous map, we will generate a new one.
self._secure_field_map = {}
labels = []
for name in self.fields.keys():
if name == self._meta.secure_field_name:
continue
sname = random_name()
field = self.fields.pop(name)
self._secure_field_map[sname] = name
self.fields[sname] = field
# Preserve the field name unless there is an explicit label:
if not field.label:
# Pretty-up the name, just like BoundField.
field.label = pretty_name(name)
# We keep a list of labels to use for our honeypots (if requested).
if self._meta.honeypots:
labels.append(field.label)
# Add in some honeypots (if asked to).
for i in range(1, self._meta.honeypots):
sname = random_name()
self._secure_field_map[sname] = None
# Don't always put the honeypot fields at the end of the form.
i = random.randint(0, len(self.fields) - 1)
# Give the honeypot a label cloned from a legit field.
if django.VERSION < (1, 7):
self.fields.insert(i, sname, HoneypotField(label=random.choice(labels)))
else:
import collections
fields = collections.OrderedDict()
for index, (key, value) in enumerate(self.fields.items()):
if index == i:
fields.update({sname: HoneypotField(label=random.choice(labels))})
fields.update({key: value})
self.fields = fields
secure = {
# We preserve the time stamp, this lets us enforce the TTL.
't': time.time(),
# The nonce is just a random value that we can remember to ensure no replays.
'n': random_name(),
# And finally, the map of secure field names to rightful field names.
'f': self._secure_field_map,
}
secure = json.dumps(secure)
# Pad to length divisible by 8.
secure += ' ' * (8 - (len(secure) % 8))
secure = self.crypt.encrypt(secure)
self.fields[self._meta.secure_field_name].initial = secure.encode('hex')
class SecureForm(SecureFormBase):
__metaclass__ = SecureFormMetaclass
| mit |
avmarchenko/exatomic | exatomic/core/error.py | 3 | 1693 | # -*- coding: utf-8 -*-
# Copyright (c) 2015-2018, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
"""
Exceptions
###############
"""
from exa.core.error import ExaException
class AtomicException(ExaException):
"""
The exatomic exception.
"""
pass
class StringFormulaError(AtomicException):
"""
The string representation of a :class:`~exatomic.formula.SimpleFormula` has
syntax described in :class:`~exatomic.formula.SimpleFormula`.
"""
_msg = 'Incorrect formula syntax for {} (syntax example H(2)O(1)).'
def __init__(self, formula):
msg = self._msg.format(formula)
super().__init__(msg)
class ClassificationError(AtomicException):
"""
Raised when a classifier for :func:`~exatomic.molecule.Molecule.add_classification`
used incorrectly.
"""
def __init__(self):
super().__init__(msg='Classifier must be a tuple of the form ("identifier", "label", exact).')
class PeriodicUniverseError(AtomicException):
"""
Raised when the code is asked to perform a periodic simulation specific
operation on a free boundary condition :class:`~exatomic.container.Universe`.
"""
def __init__(self):
super().__init__(msg='Not a periodic boundary condition Universe?')
class FreeBoundaryUniverseError(AtomicException):
"""
"""
def __init__(self):
super().__init__(msg='Not a free boundary condition Universe?')
class BasisSetNotFoundError(AtomicException):
"""
"""
def __init__(self):
super().__init__(msg='Not basis set table present in Universe?')
| apache-2.0 |
kinnou02/navitia | source/jormungandr/jormungandr/interfaces/v1/test/resource_uri_tests.py | 3 | 4581 | # encoding: utf-8
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive locomotion way of traveling!
#
# LICENCE: 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/>.
#
# Stay tuned using
# twitter @navitia
# channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, unicode_literals, division
from jormungandr.interfaces.v1.ResourceUri import complete_links
class MockResource(object):
def __init__(self):
self.region = 'test'
def mock_stop_schedules():
return {
"stop_schedules": [
{
"date_times": [
{
"date_time": "20160102T090052",
"links": [
{
"category": "comment",
"value": "Terminus (Quimper)",
"internal": "True",
"rel": "notes",
"type": "notes",
"id": "note:b5b328cb593ae7b1d73228345fe634fc",
},
{
"internal": "True",
"except_type": 1,
"rel": "exceptions",
"date": "20120619",
"type": "exceptions",
"id": "exception:120120619",
},
],
},
{
"date_time": "20160102T091352",
"links": [
{
"category": "comment",
"value": "Terminus (Quimper)",
"internal": "True",
"rel": "notes",
"type": "notes",
"id": "note:b5b328cb593ae7b1d73228345fe634fc",
},
{
"internal": "True",
"except_type": 0,
"rel": "exceptions",
"date": "20120619",
"type": "exceptions",
"id": "exception:120120620",
},
],
},
]
}
]
}
def test_complete_links():
links = complete_links(MockResource())
response = links(mock_stop_schedules)()
assert "notes" in response
assert "exceptions" in response
assert len(response["exceptions"]) == 2
assert len(response["notes"]) == 1
for item in response["notes"][0].keys():
assert item in ["category", "type", "id", "value", "comment_type"]
for exception in response["exceptions"]:
for item in exception.keys():
assert item in ["date", "type", "id"]
assert len(response["stop_schedules"]) == 1
stop_schedules = response["stop_schedules"]
assert len(stop_schedules[0]["date_times"]) == 2
assert len(stop_schedules[0]["date_times"][0]["links"]) == 2
assert len(stop_schedules[0]["date_times"][1]["links"]) == 2
for dt in stop_schedules[0]["date_times"]:
for link in dt["links"]:
items = link.keys()
for key in items:
assert key in ["category", "internal", "rel", "type", "id"]
| agpl-3.0 |
40223209/2015cdbg5_0420 | static/Brython3.1.1-20150328-091302/Lib/fractions.py | 722 | 23203 | # Originally contributed by Sjoerd Mullender.
# Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
"""Fraction, infinite-precision, real numbers."""
from decimal import Decimal
import math
import numbers
import operator
import re
import sys
__all__ = ['Fraction', 'gcd']
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
# Constants related to the hash implementation; hash(x) is based
# on the reduction of x modulo the prime _PyHASH_MODULUS.
_PyHASH_MODULUS = sys.hash_info.modulus
# Value to be used for rationals that reduce to infinity modulo
# _PyHASH_MODULUS.
_PyHASH_INF = sys.hash_info.inf
_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
(?:/(?P<denom>\d+))? # an optional denominator
| # or
(?:\.(?P<decimal>\d*))? # an optional fractional part
(?:E(?P<exp>[-+]?\d+))? # and optional exponent
)
\s*\Z # and optional whitespace to finish
""", re.VERBOSE | re.IGNORECASE)
class Fraction(numbers.Rational):
"""This class implements rational numbers.
In the two-argument form of the constructor, Fraction(8, 6) will
produce a rational number equivalent to 4/3. Both arguments must
be Rational. 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:
- numeric strings similar to those accepted by the
float constructor (for example, '-2.3' or '1e10')
- strings of the form '123/456'
- float and Decimal instances
- other Rational instances (including integers)
"""
__slots__ = ('_numerator', '_denominator')
# We're immutable, so use __new__ not __init__
def __new__(cls, numerator=0, denominator=None):
"""Constructs a Rational.
Takes a string like '3/2' or '1.5', another Rational instance, a
numerator/denominator pair, or a float.
Examples
--------
>>> Fraction(10, -8)
Fraction(-5, 4)
>>> Fraction(Fraction(1, 7), 5)
Fraction(1, 35)
>>> Fraction(Fraction(1, 7), Fraction(2, 3))
Fraction(3, 14)
>>> Fraction('314')
Fraction(314, 1)
>>> Fraction('-35/4')
Fraction(-35, 4)
>>> Fraction('3.1415') # conversion from numeric string
Fraction(6283, 2000)
>>> Fraction('-47e-2') # string may include a decimal exponent
Fraction(-47, 100)
>>> Fraction(1.47) # direct construction from float (exact conversion)
Fraction(6620291452234629, 4503599627370496)
>>> Fraction(2.25)
Fraction(9, 4)
>>> Fraction(Decimal('1.47'))
Fraction(147, 100)
"""
self = super(Fraction, cls).__new__(cls)
if denominator is None:
if isinstance(numerator, numbers.Rational):
self._numerator = numerator.numerator
self._denominator = numerator.denominator
return self
elif isinstance(numerator, float):
# Exact conversion from float
value = Fraction.from_float(numerator)
self._numerator = value._numerator
self._denominator = value._denominator
return self
elif isinstance(numerator, Decimal):
value = Fraction.from_decimal(numerator)
self._numerator = value._numerator
self._denominator = value._denominator
return self
elif isinstance(numerator, str):
# Handle construction from strings.
m = _RATIONAL_FORMAT.match(numerator)
if m is None:
raise ValueError('Invalid literal for Fraction: %r' %
numerator)
numerator = int(m.group('num') or '0')
denom = m.group('denom')
if denom:
denominator = int(denom)
else:
denominator = 1
decimal = m.group('decimal')
if decimal:
scale = 10**len(decimal)
numerator = numerator * scale + int(decimal)
denominator *= scale
exp = m.group('exp')
if exp:
exp = int(exp)
if exp >= 0:
numerator *= 10**exp
else:
denominator *= 10**-exp
if m.group('sign') == '-':
numerator = -numerator
else:
raise TypeError("argument should be a string "
"or a Rational instance")
elif (isinstance(numerator, numbers.Rational) and
isinstance(denominator, numbers.Rational)):
numerator, denominator = (
numerator.numerator * denominator.denominator,
denominator.numerator * numerator.denominator
)
else:
raise TypeError("both arguments should be "
"Rational instances")
if denominator == 0:
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
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):
raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
if math.isinf(f):
raise OverflowError("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 dec.is_infinite():
raise OverflowError(
"Cannot convert %s to %s." % (dec, cls.__name__))
if dec.is_nan():
raise ValueError("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(4321, 8765).limit_denominator(10000)
Fraction(4321, 8765)
"""
# 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, 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, numbers.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, 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, numbers.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)
def __floordiv__(a, b):
"""a // b"""
return math.floor(a / b)
def __rfloordiv__(b, a):
"""a // b"""
return math.floor(a / b)
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, numbers.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, numbers.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 __floor__(a):
"""Will be math.floor(a) in 3.0."""
return a.numerator // a.denominator
def __ceil__(a):
"""Will be math.ceil(a) in 3.0."""
# The negations cleverly convince floordiv to return the ceiling.
return -(-a.numerator // a.denominator)
def __round__(self, ndigits=None):
"""Will be round(self, ndigits) in 3.0.
Rounds half toward even.
"""
if ndigits is None:
floor, remainder = divmod(self.numerator, self.denominator)
if remainder * 2 < self.denominator:
return floor
elif remainder * 2 > self.denominator:
return floor + 1
# Deal with the half case:
elif floor % 2 == 0:
return floor
else:
return floor + 1
shift = 10**abs(ndigits)
# See _operator_fallbacks.forward to check that the results of
# these operations will always be Fraction and therefore have
# round().
if ndigits > 0:
return Fraction(round(self * shift), shift)
else:
return Fraction(round(self / shift) * shift)
def __hash__(self):
"""hash(self)"""
# XXX since this method is expensive, consider caching the result
# In order to make sure that the hash of a Fraction agrees
# with the hash of a numerically equal integer, float or
# Decimal instance, we follow the rules for numeric hashes
# outlined in the documentation. (See library docs, 'Built-in
# Types').
# dinv is the inverse of self._denominator modulo the prime
# _PyHASH_MODULUS, or 0 if self._denominator is divisible by
# _PyHASH_MODULUS.
dinv = pow(self._denominator, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
if not dinv:
hash_ = _PyHASH_INF
else:
hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS
result = hash_ if self >= 0 else -hash_
return -2 if result == -1 else result
def __eq__(a, b):
"""a == b"""
if isinstance(b, numbers.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):
if math.isnan(b) or math.isinf(b):
# comparisons with an infinity or nan should behave in
# the same way for any finite a, so treat a as zero.
return 0.0 == b
else:
return a == a.from_float(b)
else:
# Since a doesn't know how to compare with b, let's give b
# a chance to compare itself with a.
return NotImplemented
def _richcmp(self, other, op):
"""Helper for comparison operators, for internal use only.
Implement comparison between a Rational instance `self`, and
either another Rational instance or a float `other`. If
`other` is not a Rational instance or a float, return
NotImplemented. `op` should be one of the six standard
comparison operators.
"""
# convert other to a Rational instance where reasonable.
if isinstance(other, numbers.Rational):
return op(self._numerator * other.denominator,
self._denominator * other.numerator)
if isinstance(other, float):
if math.isnan(other) or math.isinf(other):
return op(0.0, other)
else:
return op(self, self.from_float(other))
else:
return NotImplemented
def __lt__(a, b):
"""a < b"""
return a._richcmp(b, operator.lt)
def __gt__(a, b):
"""a > b"""
return a._richcmp(b, operator.gt)
def __le__(a, b):
"""a <= b"""
return a._richcmp(b, operator.le)
def __ge__(a, b):
"""a >= b"""
return a._richcmp(b, operator.ge)
def __bool__(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)
| gpl-3.0 |
huncrys/mtasa-blue | vendor/freetype/builds/meson/generate_reference_docs.py | 12 | 1932 | #!/usr/bin/env python
"""Generate FreeType reference documentation."""
from __future__ import print_function
import argparse
import glob
import os
import subprocess
import sys
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--input-dir",
required=True,
help="Top-level FreeType source directory.",
)
parser.add_argument(
"--version", required=True, help='FreeType version (e.g. "2.x.y").'
)
parser.add_argument(
"--output-dir", required=True, help="Output directory."
)
args = parser.parse_args()
# Get the list of input files of interest.
include_dir = os.path.join(args.input_dir, "include")
include_config_dir = os.path.join(include_dir, "config")
include_cache_dir = os.path.join(include_dir, "cache")
all_headers = (
glob.glob(os.path.join(args.input_dir, "include", "freetype", "*.h"))
+ glob.glob(
os.path.join(
args.input_dir, "include", "freetype", "config", "*.h"
)
)
+ glob.glob(
os.path.join(
args.input_dir, "include", "freetype", "cache", "*.h"
)
)
)
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
else:
assert os.path.isdir(args.output_dir), (
"Not a directory: " + args.output_dir
)
cmds = [
sys.executable,
"-m",
"docwriter",
"--prefix=ft2",
"--title=FreeType-" + args.version,
"--site=reference",
"--output=" + args.output_dir,
] + all_headers
print("Running docwriter...")
subprocess.check_call(cmds)
print("Building static site...")
subprocess.check_call(
[sys.executable, "-m", "mkdocs", "build"], cwd=args.output_dir
)
return 0
if __name__ == "__main__":
sys.exit(main())
| gpl-3.0 |
davy39/eric | ThirdParty/Pygments/pygments/filters/__init__.py | 2 | 11519 | # -*- coding: utf-8 -*-
"""
pygments.filters
~~~~~~~~~~~~~~~~
Module containing filter lookup functions and default
filters.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
import re
from pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \
string_to_tokentype
from pygments.filter import Filter
from pygments.util import get_list_opt, get_int_opt, get_bool_opt, \
get_choice_opt, ClassNotFound, OptionError
from pygments.plugin import find_plugin_filters
def find_filter_class(filtername):
"""
Lookup a filter by name. Return None if not found.
"""
if filtername in FILTERS:
return FILTERS[filtername]
for name, cls in find_plugin_filters():
if name == filtername:
return cls
return None
def get_filter_by_name(filtername, **options):
"""
Return an instantiated filter. Options are passed to the filter
initializer if wanted. Raise a ClassNotFound if not found.
"""
cls = find_filter_class(filtername)
if cls:
return cls(**options)
else:
raise ClassNotFound('filter %r not found' % filtername)
def get_all_filters():
"""
Return a generator of all filter names.
"""
for name in FILTERS:
yield name
for name, _ in find_plugin_filters():
yield name
def _replace_special(ttype, value, regex, specialttype,
replacefunc=lambda x: x):
last = 0
for match in regex.finditer(value):
start, end = match.start(), match.end()
if start != last:
yield ttype, value[last:start]
yield specialttype, replacefunc(value[start:end])
last = end
if last != len(value):
yield ttype, value[last:]
class CodeTagFilter(Filter):
"""
Highlight special code tags in comments and docstrings.
Options accepted:
`codetags` : list of strings
A list of strings that are flagged as code tags. The default is to
highlight ``XXX``, ``TODO``, ``BUG`` and ``NOTE``.
"""
def __init__(self, **options):
Filter.__init__(self, **options)
tags = get_list_opt(options, 'codetags',
['XXX', 'TODO', 'BUG', 'NOTE'])
self.tag_re = re.compile(r'\b(%s)\b' % '|'.join([
re.escape(tag) for tag in tags if tag
]))
def filter(self, lexer, stream):
regex = self.tag_re
for ttype, value in stream:
if ttype in String.Doc or \
ttype in Comment and \
ttype not in Comment.Preproc:
for sttype, svalue in _replace_special(ttype, value, regex,
Comment.Special):
yield sttype, svalue
else:
yield ttype, value
class KeywordCaseFilter(Filter):
"""
Convert keywords to lowercase or uppercase or capitalize them, which
means first letter uppercase, rest lowercase.
This can be useful e.g. if you highlight Pascal code and want to adapt the
code to your styleguide.
Options accepted:
`case` : string
The casing to convert keywords to. Must be one of ``'lower'``,
``'upper'`` or ``'capitalize'``. The default is ``'lower'``.
"""
def __init__(self, **options):
Filter.__init__(self, **options)
case = get_choice_opt(options, 'case', ['lower', 'upper', 'capitalize'], 'lower')
self.convert = getattr(str, case)
def filter(self, lexer, stream):
for ttype, value in stream:
if ttype in Keyword:
yield ttype, self.convert(value)
else:
yield ttype, value
class NameHighlightFilter(Filter):
"""
Highlight a normal Name token with a different token type.
Example::
filter = NameHighlightFilter(
names=['foo', 'bar', 'baz'],
tokentype=Name.Function,
)
This would highlight the names "foo", "bar" and "baz"
as functions. `Name.Function` is the default token type.
Options accepted:
`names` : list of strings
A list of names that should be given the different token type.
There is no default.
`tokentype` : TokenType or string
A token type or a string containing a token type name that is
used for highlighting the strings in `names`. The default is
`Name.Function`.
"""
def __init__(self, **options):
Filter.__init__(self, **options)
self.names = set(get_list_opt(options, 'names', []))
tokentype = options.get('tokentype')
if tokentype:
self.tokentype = string_to_tokentype(tokentype)
else:
self.tokentype = Name.Function
def filter(self, lexer, stream):
for ttype, value in stream:
if ttype is Name and value in self.names:
yield self.tokentype, value
else:
yield ttype, value
class ErrorToken(Exception):
pass
class RaiseOnErrorTokenFilter(Filter):
"""
Raise an exception when the lexer generates an error token.
Options accepted:
`excclass` : Exception class
The exception class to raise.
The default is `pygments.filters.ErrorToken`.
*New in Pygments 0.8.*
"""
def __init__(self, **options):
Filter.__init__(self, **options)
self.exception = options.get('excclass', ErrorToken)
try:
# issubclass() will raise TypeError if first argument is not a class
if not issubclass(self.exception, Exception):
raise TypeError
except TypeError:
raise OptionError('excclass option is not an exception class')
def filter(self, lexer, stream):
for ttype, value in stream:
if ttype is Error:
raise self.exception(value)
yield ttype, value
class VisibleWhitespaceFilter(Filter):
"""
Convert tabs, newlines and/or spaces to visible characters.
Options accepted:
`spaces` : string or bool
If this is a one-character string, spaces will be replaces by this string.
If it is another true value, spaces will be replaced by ``·`` (unicode
MIDDLE DOT). If it is a false value, spaces will not be replaced. The
default is ``False``.
`tabs` : string or bool
The same as for `spaces`, but the default replacement character is ``»``
(unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value
is ``False``. Note: this will not work if the `tabsize` option for the
lexer is nonzero, as tabs will already have been expanded then.
`tabsize` : int
If tabs are to be replaced by this filter (see the `tabs` option), this
is the total number of characters that a tab should be expanded to.
The default is ``8``.
`newlines` : string or bool
The same as for `spaces`, but the default replacement character is ``¶``
(unicode PILCROW SIGN). The default value is ``False``.
`wstokentype` : bool
If true, give whitespace the special `Whitespace` token type. This allows
styling the visible whitespace differently (e.g. greyed out), but it can
disrupt background colors. The default is ``True``.
*New in Pygments 0.8.*
"""
def __init__(self, **options):
Filter.__init__(self, **options)
for name, default in list({'spaces': '·', 'tabs': '»', 'newlines': '¶'}.items()):
opt = options.get(name, False)
if isinstance(opt, str) and len(opt) == 1:
setattr(self, name, opt)
else:
setattr(self, name, (opt and default or ''))
tabsize = get_int_opt(options, 'tabsize', 8)
if self.tabs:
self.tabs += ' '*(tabsize-1)
if self.newlines:
self.newlines += '\n'
self.wstt = get_bool_opt(options, 'wstokentype', True)
def filter(self, lexer, stream):
if self.wstt:
spaces = self.spaces or ' '
tabs = self.tabs or '\t'
newlines = self.newlines or '\n'
regex = re.compile(r'\s')
def replacefunc(wschar):
if wschar == ' ':
return spaces
elif wschar == '\t':
return tabs
elif wschar == '\n':
return newlines
return wschar
for ttype, value in stream:
for sttype, svalue in _replace_special(ttype, value, regex,
Whitespace, replacefunc):
yield sttype, svalue
else:
spaces, tabs, newlines = self.spaces, self.tabs, self.newlines
# simpler processing
for ttype, value in stream:
if spaces:
value = value.replace(' ', spaces)
if tabs:
value = value.replace('\t', tabs)
if newlines:
value = value.replace('\n', newlines)
yield ttype, value
class GobbleFilter(Filter):
"""
Gobbles source code lines (eats initial characters).
This filter drops the first ``n`` characters off every line of code. This
may be useful when the source code fed to the lexer is indented by a fixed
amount of space that isn't desired in the output.
Options accepted:
`n` : int
The number of characters to gobble.
*New in Pygments 1.2.*
"""
def __init__(self, **options):
Filter.__init__(self, **options)
self.n = get_int_opt(options, 'n', 0)
def gobble(self, value, left):
if left < len(value):
return value[left:], 0
else:
return '', left - len(value)
def filter(self, lexer, stream):
n = self.n
left = n # How many characters left to gobble.
for ttype, value in stream:
# Remove ``left`` tokens from first line, ``n`` from all others.
parts = value.split('\n')
(parts[0], left) = self.gobble(parts[0], left)
for i in range(1, len(parts)):
(parts[i], left) = self.gobble(parts[i], n)
value = '\n'.join(parts)
if value != '':
yield ttype, value
class TokenMergeFilter(Filter):
"""
Merges consecutive tokens with the same token type in the output stream of a
lexer.
*New in Pygments 1.2.*
"""
def __init__(self, **options):
Filter.__init__(self, **options)
def filter(self, lexer, stream):
current_type = None
current_value = None
for ttype, value in stream:
if ttype is current_type:
current_value += value
else:
if current_type is not None:
yield current_type, current_value
current_type = ttype
current_value = value
if current_type is not None:
yield current_type, current_value
FILTERS = {
'codetagify': CodeTagFilter,
'keywordcase': KeywordCaseFilter,
'highlight': NameHighlightFilter,
'raiseonerror': RaiseOnErrorTokenFilter,
'whitespace': VisibleWhitespaceFilter,
'gobble': GobbleFilter,
'tokenmerge': TokenMergeFilter,
}
| gpl-3.0 |
epyx-src/django-oauth2-provider | provider/oauth2/backends.py | 1 | 2067 | from ..utils import now
from .forms import ClientAuthForm
from .models import AccessToken
class BaseBackend(object):
"""
Base backend used to authenticate clients as defined in :rfc:`1` against
our database.
"""
def authenticate(self, request=None):
"""
Override this method to implement your own authentication backend.
Return a client or ``None`` in case of failure.
"""
pass
class BasicClientBackend(object):
"""
Backend that tries to authenticate a client through HTTP authorization
headers as defined in :rfc:`2.3.1`.
"""
def authenticate(self, request=None):
auth = request.META.get('HTTP_AUTHORIZATION')
if auth is None or auth == '':
return None
try:
basic, base64 = auth.split(' ')
client_id, client_secret = base64.decode('base64').split(':')
form = ClientAuthForm({
'client_id': client_id,
'client_secret': client_secret})
if form.is_valid():
return form.cleaned_data.get('client')
return None
except ValueError:
# Auth header was malformed, unpacking went wrong
return None
class RequestParamsClientBackend(object):
"""
Backend that tries to authenticate a client through request parameters
which might be in the request body or URI as defined in :rfc:`2.3.1`.
"""
def authenticate(self, request=None):
if request is None:
return None
form = ClientAuthForm(request.REQUEST)
if form.is_valid():
return form.cleaned_data.get('client')
return None
class AccessTokenBackend(object):
"""
Authenticate a user via access token and client object.
"""
def authenticate(self, access_token=None, client=None):
try:
return AccessToken.objects.get(token=access_token,
expires__gt=now(), client=client)
except AccessToken.DoesNotExist:
return None
| mit |
mdj2/django | django/contrib/webdesign/tests.py | 232 | 1092 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
from django.contrib.webdesign.lorem_ipsum import *
from django.template import loader, Context
class WebdesignTest(unittest.TestCase):
def test_words(self):
self.assertEqual(words(7), 'lorem ipsum dolor sit amet consectetur adipisicing')
def test_paragraphs(self):
self.assertEqual(paragraphs(1),
['Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'])
def test_lorem_tag(self):
t = loader.get_template_from_string("{% load webdesign %}{% lorem 3 w %}")
self.assertEqual(t.render(Context({})),
'lorem ipsum dolor')
| bsd-3-clause |
crs4/biodoop-core | bl/core/gt/mr/kinship/phase_two.py | 1 | 1784 | # BEGIN_COPYRIGHT
#
# Copyright (C) 2009-2013 CRS4.
#
# This file is part of biodoop-core.
#
# biodoop-core 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.
#
# biodoop-core 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
# biodoop-core. If not, see <http://www.gnu.org/licenses/>.
#
# END_COPYRIGHT
"""
Phase two: input data = paths of compressed, serialized KinshipVector objects.
This phase is meant to be run on phase one's output when the latter is
too large for a single process to collect. Using less mappers than
there are KinshipVector files allows to reduce the burden of
assembling the final matrix.
FIXME: phase_two is a misnomer, since it can be run any number of
times with a progressively reduced number of mappers.
"""
import zlib
import pydoop.hdfs as hdfs
import pydoop.pipes as pp
from bl.core.gt.kinship import KinshipBuilder, KinshipVectors
from common import BaseMapper, Reducer
class Mapper(BaseMapper):
def _feed_builder(self, v):
fn = v.strip()
with hdfs.open(fn, user=self.user) as f:
s = zlib.decompress(f.read())
vectors = KinshipVectors.deserialize(s) # ignores trailing newline char
if self.builder is None:
self.builder = KinshipBuilder(vectors)
else:
self.builder.vectors += vectors
def run_task():
return pp.runTask(pp.Factory(Mapper, Reducer))
| gpl-3.0 |
indico/indico | indico/modules/events/papers/lists.py | 4 | 8703 | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from operator import attrgetter
from flask import request
from sqlalchemy.orm import subqueryload, undefer
from indico.core.db import db
from indico.modules.events.contributions import Contribution
from indico.modules.events.papers.models.revisions import PaperRevision, PaperRevisionState
from indico.modules.events.papers.settings import PaperReviewingRole
from indico.modules.events.util import ListGeneratorBase
from indico.modules.users import User
from indico.util.i18n import _
from indico.web.flask.templating import get_template_module
class PaperListGeneratorBase(ListGeneratorBase):
"""Listing and filtering actions in a paper list."""
def __init__(self, event):
super().__init__(event)
self.default_list_config = {
'items': ('state',),
'filters': {'items': {}}
}
state_not_submitted = {None: _('Not yet submitted')}
track_empty = {None: _('No track')}
session_empty = {None: _('No session')}
type_empty = {None: _('No type')}
state_choices = {state.value: state.title for state in PaperRevisionState}
unassigned_choices = {role.value: role.title for role in PaperReviewingRole}
track_choices = {str(t.id): t.title for t in sorted(self.event.tracks, key=attrgetter('title'))}
session_choices = {str(s.id): s.title for s in sorted(self.event.sessions, key=attrgetter('title'))}
type_choices = {str(t.id): t.name for t in sorted(self.event.contribution_types, key=attrgetter('name'))}
if not event.cfp.content_reviewing_enabled:
del unassigned_choices[PaperReviewingRole.content_reviewer.value]
if not event.cfp.layout_reviewing_enabled:
del unassigned_choices[PaperReviewingRole.layout_reviewer.value]
self.static_items = {
'state': {'title': _('State'), 'filter_choices': state_not_submitted | state_choices},
'track': {'title': _('Track'), 'filter_choices': track_empty | track_choices},
'session': {'title': _('Session'), 'filter_choices': session_empty | session_choices},
'type': {'title': _('Type'), 'filter_choices': type_empty | type_choices},
'unassigned': {'title': _('Unassigned'), 'filter_choices': unassigned_choices},
}
self.list_config = self._get_config()
def _get_static_columns(self, ids):
"""
Retrieve information needed for the header of the static columns.
:return: a list of {'id': ..., 'caption': ...} dicts
"""
return [{'id': id_, 'caption': self.static_items[id_]['title']} for id_ in self.static_items if id_ in ids]
def _build_query(self):
return (Contribution.query.with_parent(self.event)
.order_by(Contribution.friendly_id)
.options(subqueryload('_paper_last_revision'),
subqueryload('paper_judges'),
subqueryload('paper_content_reviewers'),
subqueryload('paper_layout_reviewers'),
undefer('_paper_revision_count')))
def _filter_list_entries(self, query, filters):
if not filters.get('items'):
return query
criteria = []
if 'state' in filters['items']:
filtered_states = filters['items']['state']
state_criteria = []
for filter_state in filtered_states:
if filter_state is None:
state_criteria.append(~Contribution._paper_last_revision.has())
else:
state_criteria.append(Contribution._paper_last_revision
.has(PaperRevision.state == int(filter_state)))
if state_criteria:
criteria.append(db.or_(*state_criteria))
if 'unassigned' in filters['items']:
role_map = {
PaperReviewingRole.judge.value: Contribution.paper_judges,
PaperReviewingRole.content_reviewer.value: Contribution.paper_content_reviewers,
PaperReviewingRole.layout_reviewer.value: Contribution.paper_layout_reviewers,
}
filtered_roles = list(map(PaperReviewingRole, map(int, filters['items']['unassigned'])))
unassigned_criteria = [~role_map[role.value].any() for role in filtered_roles
if (role == PaperReviewingRole.judge or
self.event.cfp.get_reviewing_state(role.review_type))]
if unassigned_criteria:
criteria.append(db.or_(*unassigned_criteria))
filter_cols = {'track': Contribution.track_id,
'session': Contribution.session_id,
'type': Contribution.type_id}
for key, column in filter_cols.items():
ids = set(filters['items'].get(key, ()))
if not ids:
continue
column_criteria = []
if None in ids:
column_criteria.append(column.is_(None))
if ids - {None}:
column_criteria.append(column.in_(ids - {None}))
criteria.append(db.or_(*column_criteria))
return query.filter(*criteria)
def get_list_kwargs(self):
list_config = self._get_config()
contributions_query = self._build_query()
total_entries = contributions_query.count()
contributions = self._filter_list_entries(contributions_query, self.list_config['filters']).all()
selected_entry = request.args.get('selected')
selected_entry = int(selected_entry) if selected_entry else None
static_item_ids, dynamic_item_ids = self._split_item_ids(list_config['items'], 'static')
static_columns = self._get_static_columns(static_item_ids)
return {'contribs': contributions, 'total_entries': total_entries, 'selected_entry': selected_entry,
'static_columns': static_columns}
def render_list(self):
"""Render the contribution list template components.
:return: dict containing the list's entries, the fragment of
displayed entries and whether the contribution passed is displayed
in the results.
"""
contrib_list_kwargs = self.get_list_kwargs()
total_entries = contrib_list_kwargs.pop('total_entries')
selected_entry = contrib_list_kwargs.pop('selected_entry')
tpl_contrib = get_template_module('events/papers/_paper_list.html')
tpl_lists = get_template_module('events/management/_lists.html')
contribs = contrib_list_kwargs['contribs']
filter_statistics = tpl_lists.render_displayed_entries_fragment(len(contribs), total_entries)
return {'html': tpl_contrib.render_paper_assignment_list(self.event, total_entries, **contrib_list_kwargs),
'filter_statistics': filter_statistics,
'selected_entry': selected_entry}
class PaperAssignmentListGenerator(PaperListGeneratorBase):
"""Listing and filtering actions in a paper assignment list."""
endpoint = '.papers_list'
list_link_type = 'paper_asssignment_management'
def __init__(self, event):
super().__init__(event)
self.default_list_config = {
'items': ('state',),
'filters': {'items': {}}
}
def get_list_kwargs(self):
kwargs = super().get_list_kwargs()
kwargs['management'] = True
return kwargs
class PaperJudgingAreaListGeneratorDisplay(PaperListGeneratorBase):
"""
Listing and filtering actions in paper judging area list in the display view.
"""
endpoint = '.papers_list'
list_link_type = 'paper_judging_display'
def __init__(self, event, user):
super().__init__(event)
self.user = user
self.default_list_config = {
'items': ('state',),
'filters': {'items': {}}
}
self.static_items['unassigned']['filter_choices'] = {
role.value: role.title
for role in sorted(PaperReviewingRole, key=attrgetter('title'))
if role is not PaperReviewingRole.judge
}
def _build_query(self):
query = super()._build_query()
return query.filter(Contribution.paper_judges.any(User.id == self.user.id))
def get_list_kwargs(self):
kwargs = super().get_list_kwargs()
kwargs['management'] = False
return kwargs
| mit |
ajdawson/iris | lib/iris/tests/analysis/test_interpolate.py | 6 | 2732 | # (C) British Crown Copyright 2013 - 2016, Met Office
#
# This file is part of Iris.
#
# Iris 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 3 of the License, or
# (at your option) any later version.
#
# Iris 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 Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test the iris.analysis.interpolate module.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# Import iris tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests
import numpy as np
import iris.analysis._interpolate_private as interpolate
from iris.coords import DimCoord
from iris.cube import Cube
from iris.tests.test_interpolation import normalise_order
class Test_linear__circular_wrapping(tests.IrisTest):
def _create_cube(self, longitudes):
# Return a Cube with circular longitude with the given values.
data = np.arange(12).reshape((3, 4)) * 0.1
cube = Cube(data)
lon = DimCoord(longitudes, standard_name='longitude',
units='degrees', circular=True)
cube.add_dim_coord(lon, 1)
return cube
def test_symmetric(self):
# Check we can interpolate from a Cube defined over [-180, 180).
cube = self._create_cube([-180, -90, 0, 90])
samples = [('longitude', np.arange(-360, 720, 45))]
result = interpolate.linear(cube, samples, extrapolation_mode='nan')
normalise_order(result)
self.assertCMLApproxData(result, ('analysis', 'interpolation',
'linear', 'circular_wrapping',
'symmetric'))
def test_positive(self):
# Check we can interpolate from a Cube defined over [0, 360).
cube = self._create_cube([0, 90, 180, 270])
samples = [('longitude', np.arange(-360, 720, 45))]
result = interpolate.linear(cube, samples, extrapolation_mode='nan')
normalise_order(result)
self.assertCMLApproxData(result, ('analysis', 'interpolation',
'linear', 'circular_wrapping',
'positive'))
if __name__ == "__main__":
tests.main()
| gpl-3.0 |
PriceChild/ansible | lib/ansible/modules/notification/rocketchat.py | 49 | 8618 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016, Deepak Kothandan <deepak.kothandan@outlook.com>
# (c) 2015, Stefan Berggren <nsg@nsg.cc>
# (c) 2014, Ramon de la Fuente <ramon@delafuente.nl>
#
# 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/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
module: rocketchat
short_description: Send notifications to Rocket Chat
description:
- The C(rocketchat) module sends notifications to Rocket Chat via the Incoming WebHook integration
version_added: "2.2"
author: "Ramon de la Fuente (@ramondelafuente)"
options:
domain:
description:
- The domain for your environment without protocol. (i.e.
C(example.com) or C(chat.example.com))
required: true
token:
description:
- Rocket Chat Incoming Webhook integration token. This provides
authentication to Rocket Chat's Incoming webhook for posting
messages.
required: true
protocol:
description:
- Specify the protocol used to send notification messages before the webhook url. (i.e. http or https)
required: false
default: https
choices:
- 'http'
- 'https'
msg:
description:
- Message to be sent.
required: false
default: None
channel:
description:
- Channel to send the message to. If absent, the message goes to the channel selected for the I(token)
specifed during the creation of webhook.
required: false
default: None
username:
description:
- This is the sender of the message.
required: false
default: "Ansible"
icon_url:
description:
- URL for the message sender's icon.
required: false
default: "https://www.ansible.com/favicon.ico"
icon_emoji:
description:
- Emoji for the message sender. The representation for the available emojis can be
got from Rocket Chat. (for example :thumbsup:) (if I(icon_emoji) is set, I(icon_url) will not be used)
required: false
default: None
link_names:
description:
- Automatically create links for channels and usernames in I(msg).
required: false
default: 1
choices:
- 1
- 0
validate_certs:
description:
- If C(no), SSL certificates will not be validated. This should only be used
on personally controlled sites using self-signed certificates.
required: false
default: 'yes'
choices:
- 'yes'
- 'no'
color:
description:
- Allow text to use default colors - use the default of 'normal' to not send a custom color bar at the start of the message
required: false
default: 'normal'
choices:
- 'normal'
- 'good'
- 'warning'
- 'danger'
attachments:
description:
- Define a list of attachments.
required: false
default: None
"""
EXAMPLES = """
- name: Send notification message via Rocket Chat
rocketchat:
token: thetoken/generatedby/rocketchat
domain: chat.example.com
msg: '{{ inventory_hostname }} completed'
delegate_to: localhost
- name: Send notification message via Rocket Chat all options
rocketchat:
domain: chat.example.com
token: thetoken/generatedby/rocketchat
msg: '{{ inventory_hostname }} completed'
channel: #ansible
username: 'Ansible on {{ inventory_hostname }}'
icon_url: http://www.example.com/some-image-file.png
link_names: 0
delegate_to: localhost
- name: insert a color bar in front of the message for visibility purposes and use the default webhook icon and name configured in rocketchat
rocketchat:
token: thetoken/generatedby/rocketchat
domain: chat.example.com
msg: '{{ inventory_hostname }} is alive!'
color: good
username: ''
icon_url: ''
delegate_to: localhost
- name: Use the attachments API
rocketchat:
token: thetoken/generatedby/rocketchat
domain: chat.example.com
attachments:
- text: Display my system load on host A and B
color: #ff00dd
title: System load
fields:
- title: System A
value: 'load average: 0,74, 0,66, 0,63'
short: True
- title: System B
value: 'load average: 5,16, 4,64, 2,43'
short: True
delegate_to: localhost
"""
RETURN = """
changed:
description: A flag indicating if any change was made or not.
returned: success
type: boolean
sample: false
"""
ROCKETCHAT_INCOMING_WEBHOOK = '%s://%s/hooks/%s'
def build_payload_for_rocketchat(module, text, channel, username, icon_url, icon_emoji, link_names, color, attachments):
payload = {}
if color == "normal" and text is not None:
payload = dict(text=text)
elif text is not None:
payload = dict(attachments=[dict(text=text, color=color)])
if channel is not None:
if (channel[0] == '#') or (channel[0] == '@'):
payload['channel'] = channel
else:
payload['channel'] = '#' + channel
if username is not None:
payload['username'] = username
if icon_emoji is not None:
payload['icon_emoji'] = icon_emoji
else:
payload['icon_url'] = icon_url
if link_names is not None:
payload['link_names'] = link_names
if attachments is not None:
if 'attachments' not in payload:
payload['attachments'] = []
if attachments is not None:
for attachment in attachments:
if 'fallback' not in attachment:
attachment['fallback'] = attachment['text']
payload['attachments'].append(attachment)
payload="payload=" + module.jsonify(payload)
return payload
def do_notify_rocketchat(module, domain, token, protocol, payload):
if token.count('/') < 1:
module.fail_json(msg="Invalid Token specified, provide a valid token")
rocketchat_incoming_webhook = ROCKETCHAT_INCOMING_WEBHOOK % (protocol, domain, token)
response, info = fetch_url(module, rocketchat_incoming_webhook, data=payload)
if info['status'] != 200:
module.fail_json(msg="failed to send message, return status=%s" % str(info['status']))
def main():
module = AnsibleModule(
argument_spec = dict(
domain = dict(type='str', required=True, default=None),
token = dict(type='str', required=True, no_log=True),
protocol = dict(type='str', default='https', choices=['http', 'https']),
msg = dict(type='str', required=False, default=None),
channel = dict(type='str', default=None),
username = dict(type='str', default='Ansible'),
icon_url = dict(type='str', default='https://www.ansible.com/favicon.ico'),
icon_emoji = dict(type='str', default=None),
link_names = dict(type='int', default=1, choices=[0,1]),
validate_certs = dict(default='yes', type='bool'),
color = dict(type='str', default='normal', choices=['normal', 'good', 'warning', 'danger']),
attachments = dict(type='list', required=False, default=None)
)
)
domain = module.params['domain']
token = module.params['token']
protocol = module.params['protocol']
text = module.params['msg']
channel = module.params['channel']
username = module.params['username']
icon_url = module.params['icon_url']
icon_emoji = module.params['icon_emoji']
link_names = module.params['link_names']
color = module.params['color']
attachments = module.params['attachments']
payload = build_payload_for_rocketchat(module, text, channel, username, icon_url, icon_emoji, link_names, color, attachments)
do_notify_rocketchat(module, domain, token, protocol, payload)
module.exit_json(msg="OK")
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
if __name__ == '__main__':
main()
| gpl-3.0 |
rjsproxy/wagtail | wagtail/wagtailusers/forms.py | 11 | 10300 | from django import forms
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Group, Permission
from django.forms.models import inlineformset_factory
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.widgets import AdminPageChooser
from wagtail.wagtailusers.models import UserProfile
from wagtail.wagtailcore.models import Page, UserPagePermissionsProxy, GroupPagePermission
User = get_user_model()
# The standard fields each user model is expected to have, as a minimum.
standard_fields = set(['email', 'first_name', 'last_name', 'is_superuser', 'groups'])
class UsernameForm(forms.ModelForm):
"""
Intelligently sets up the username field if it is infact a username. If the
User model has been swapped out, and the username field is an email or
something else, dont touch it.
"""
def __init__(self, *args, **kwargs):
super(UsernameForm, self).__init__(*args, **kwargs)
if User.USERNAME_FIELD == 'username':
field = self.fields['username']
field.regex = r"^[\w.@+-]+$"
field.help_text = _("Required. 30 characters or fewer. Letters, "
"digits and @/./+/-/_ only.")
field.error_messages = field.error_messages.copy()
field.error_messages.update({
'invalid': _("This value may contain only letters, numbers "
"and @/./+/-/_ characters.")})
@property
def username_field(self):
return self[User.USERNAME_FIELD]
def separate_username_field(self):
return User.USERNAME_FIELD not in standard_fields
class UserCreationForm(UsernameForm):
required_css_class = "required"
error_messages = {
'duplicate_username': _("A user with that username already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
is_superuser = forms.BooleanField(
label=_("Administrator"),
required=False,
help_text=_("If ticked, this user has the ability to manage user accounts.")
)
password1 = forms.CharField(
label=_("Password"),
required=False,
widget=forms.PasswordInput,
help_text=_("Leave blank if not changing."))
password2 = forms.CharField(
label=_("Password confirmation"), required=False,
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
email = forms.EmailField(required=True, label=_("Email"))
first_name = forms.CharField(required=True, label=_("First Name"))
last_name = forms.CharField(required=True, label=_("Last Name"))
class Meta:
model = User
fields = set([User.USERNAME_FIELD]) | standard_fields
widgets = {
'groups': forms.CheckboxSelectMultiple
}
def clean_username(self):
username_field = User.USERNAME_FIELD
username = self.cleaned_data[username_field]
try:
User._default_manager.get(**{username_field: username})
except User.DoesNotExist:
return username
raise forms.ValidationError(
self.error_messages['duplicate_username'],
code='duplicate_username',
)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
# users can access django-admin iff they are a superuser
user.is_staff = user.is_superuser
if commit:
user.save()
self.save_m2m()
return user
# Largely the same as django.contrib.auth.forms.UserCreationForm, but with enough subtle changes
# (to make password non-required) that it isn't worth inheriting...
class UserEditForm(UsernameForm):
required_css_class = "required"
error_messages = {
'duplicate_username': _("A user with that username already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
email = forms.EmailField(required=True, label=_("Email"))
first_name = forms.CharField(required=True, label=_("First Name"))
last_name = forms.CharField(required=True, label=_("Last Name"))
password1 = forms.CharField(
label=_("Password"),
required=False,
widget=forms.PasswordInput,
help_text=_("Leave blank if not changing."))
password2 = forms.CharField(
label=_("Password confirmation"), required=False,
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
is_superuser = forms.BooleanField(
label=_("Administrator"),
required=False,
help_text=_("Administrators have the ability to manage user accounts.")
)
class Meta:
model = User
fields = set([User.USERNAME_FIELD, "is_active"]) | standard_fields
widgets = {
'groups': forms.CheckboxSelectMultiple
}
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
username_field = User.USERNAME_FIELD
try:
User._default_manager.exclude(id=self.instance.id).get(**{
username_field: username})
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
def save(self, commit=True):
user = super(UserEditForm, self).save(commit=False)
# users can access django-admin iff they are a superuser
user.is_staff = user.is_superuser
if self.cleaned_data["password1"]:
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
self.save_m2m()
return user
class GroupForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(GroupForm, self).__init__(*args, **kwargs)
self.registered_permissions = Permission.objects.none()
for fn in hooks.get_hooks('register_permissions'):
self.registered_permissions = self.registered_permissions | fn()
self.fields['permissions'].queryset = self.registered_permissions
required_css_class = "required"
error_messages = {
'duplicate_name': _("A group with that name already exists."),
}
is_superuser = forms.BooleanField(
label=_("Administrator"),
required=False,
help_text=_("Administrators have the ability to manage user accounts.")
)
class Meta:
model = Group
fields = ("name", "permissions", )
def clean_name(self):
# Since Group.name is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
name = self.cleaned_data["name"]
try:
Group._default_manager.exclude(id=self.instance.id).get(name=name)
except Group.DoesNotExist:
return name
raise forms.ValidationError(self.error_messages['duplicate_name'])
def save(self):
# We go back to the object to read (in order to reapply) the
# permissions which were set on this group, but which are not
# accessible in the wagtail admin interface, as otherwise these would
# be clobbered by this form.
try:
untouchable_permissions = self.instance.permissions.exclude(pk__in=self.registered_permissions)
bool(untouchable_permissions) # force this to be evaluated, as it's about to change
except ValueError:
# this form is not bound; we're probably creating a new group
untouchable_permissions = []
group = super(GroupForm, self).save()
group.permissions.add(*untouchable_permissions)
return group
class GroupPagePermissionForm(forms.ModelForm):
page = forms.ModelChoiceField(queryset=Page.objects.all(),
widget=AdminPageChooser(show_edit_link=False))
class Meta:
model = GroupPagePermission
fields = ('page', 'permission_type')
class BaseGroupPagePermissionFormSet(forms.models.BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super(BaseGroupPagePermissionFormSet, self).__init__(*args, **kwargs)
self.form = GroupPagePermissionForm
for form in self.forms:
form.fields['DELETE'].widget = forms.HiddenInput()
@property
def empty_form(self):
empty_form = super(BaseGroupPagePermissionFormSet, self).empty_form
empty_form.fields['DELETE'].widget = forms.HiddenInput()
return empty_form
GroupPagePermissionFormSet = inlineformset_factory(
Group,
GroupPagePermission,
formset=BaseGroupPagePermissionFormSet,
extra=0,
fields=('page', 'permission_type'),
)
class NotificationPreferencesForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(NotificationPreferencesForm, self).__init__(*args, **kwargs)
user_perms = UserPagePermissionsProxy(self.instance.user)
if not user_perms.can_publish_pages():
del self.fields['submitted_notifications']
if not user_perms.can_edit_pages():
del self.fields['approved_notifications']
del self.fields['rejected_notifications']
class Meta:
model = UserProfile
fields = ("submitted_notifications", "approved_notifications", "rejected_notifications")
| bsd-3-clause |
vathpela/anaconda | tests/nosetests/pyanaconda_tests/pwpolicy_test.py | 4 | 1952 | #
# Brian C. Lane <bcl@redhat.com>
#
# Copyright 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2. This program is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties 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. Any Red Hat
# trademarks that are incorporated in the source code or documentation are not
# subject to the GNU General Public License and may only be used or replicated
# with the express permission of Red Hat, Inc.
#
import unittest
from pyanaconda import kickstart
class PwPolicyTestCase(unittest.TestCase):
ks = """
%anaconda
pwpolicy root --strict --minlen=8 --minquality=50 --nochanges --emptyok
pwpolicy user --strict --minlen=8 --minquality=50 --nochanges --emptyok
pwpolicy luks --strict --minlen=8 --minquality=50 --nochanges --emptyok
%end
"""
def setUp(self):
self.handler = kickstart.AnacondaKSHandler()
self.ksparser = kickstart.AnacondaKSParser(self.handler)
def pwpolicy_test(self):
self.ksparser.readKickstartFromString(self.ks)
self.assertIsInstance(self.handler, kickstart.AnacondaKSHandler)
self.assertIsInstance(self.handler.anaconda, kickstart.AnacondaSectionHandler)
eq_template = "pwpolicy %s --minlen=8 --minquality=50 --strict --nochanges --emptyok\n"
for name in ["root", "user", "luks"]:
self.assertEqual(str(self.handler.anaconda.pwpolicy.get_policy(name)), eq_template % name) # pylint: disable=no-member
| gpl-2.0 |
Orav/kbengine | kbe/res/scripts/common/Lib/test/test_sysconfig.py | 2 | 17303 | import unittest
import sys
import os
import subprocess
import shutil
from copy import copy
from test.support import (run_unittest, TESTFN, unlink, check_warnings,
captured_stdout, skip_unless_symlink)
import sysconfig
from sysconfig import (get_paths, get_platform, get_config_vars,
get_path, get_path_names, _INSTALL_SCHEMES,
_get_default_scheme, _expand_vars,
get_scheme_names, get_config_var, _main)
import _osx_support
class TestSysConfig(unittest.TestCase):
def setUp(self):
super(TestSysConfig, self).setUp()
self.sys_path = sys.path[:]
# patching os.uname
if hasattr(os, 'uname'):
self.uname = os.uname
self._uname = os.uname()
else:
self.uname = None
self._set_uname(('',)*5)
os.uname = self._get_uname
# saving the environment
self.name = os.name
self.platform = sys.platform
self.version = sys.version
self.sep = os.sep
self.join = os.path.join
self.isabs = os.path.isabs
self.splitdrive = os.path.splitdrive
self._config_vars = sysconfig._CONFIG_VARS, copy(sysconfig._CONFIG_VARS)
self._added_envvars = []
self._changed_envvars = []
for var in ('MACOSX_DEPLOYMENT_TARGET', 'PATH'):
if var in os.environ:
self._changed_envvars.append((var, os.environ[var]))
else:
self._added_envvars.append(var)
def tearDown(self):
sys.path[:] = self.sys_path
self._cleanup_testfn()
if self.uname is not None:
os.uname = self.uname
else:
del os.uname
os.name = self.name
sys.platform = self.platform
sys.version = self.version
os.sep = self.sep
os.path.join = self.join
os.path.isabs = self.isabs
os.path.splitdrive = self.splitdrive
sysconfig._CONFIG_VARS = self._config_vars[0]
sysconfig._CONFIG_VARS.clear()
sysconfig._CONFIG_VARS.update(self._config_vars[1])
for var, value in self._changed_envvars:
os.environ[var] = value
for var in self._added_envvars:
os.environ.pop(var, None)
super(TestSysConfig, self).tearDown()
def _set_uname(self, uname):
self._uname = os.uname_result(uname)
def _get_uname(self):
return self._uname
def _cleanup_testfn(self):
path = TESTFN
if os.path.isfile(path):
os.remove(path)
elif os.path.isdir(path):
shutil.rmtree(path)
def test_get_path_names(self):
self.assertEqual(get_path_names(), sysconfig._SCHEME_KEYS)
def test_get_paths(self):
scheme = get_paths()
default_scheme = _get_default_scheme()
wanted = _expand_vars(default_scheme, None)
wanted = sorted(wanted.items())
scheme = sorted(scheme.items())
self.assertEqual(scheme, wanted)
def test_get_path(self):
# XXX make real tests here
for scheme in _INSTALL_SCHEMES:
for name in _INSTALL_SCHEMES[scheme]:
res = get_path(name, scheme)
def test_get_config_vars(self):
cvars = get_config_vars()
self.assertIsInstance(cvars, dict)
self.assertTrue(cvars)
def test_get_platform(self):
# windows XP, 32bits
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Intel)]')
sys.platform = 'win32'
self.assertEqual(get_platform(), 'win32')
# windows XP, amd64
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Amd64)]')
sys.platform = 'win32'
self.assertEqual(get_platform(), 'win-amd64')
# windows XP, itanium
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Itanium)]')
sys.platform = 'win32'
self.assertEqual(get_platform(), 'win-ia64')
# macbook
os.name = 'posix'
sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) '
'\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]')
sys.platform = 'darwin'
self._set_uname(('Darwin', 'macziade', '8.11.1',
('Darwin Kernel Version 8.11.1: '
'Wed Oct 10 18:23:28 PDT 2007; '
'root:xnu-792.25.20~1/RELEASE_I386'), 'PowerPC'))
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
'-fwrapv -O3 -Wall -Wstrict-prototypes')
maxint = sys.maxsize
try:
sys.maxsize = 2147483647
self.assertEqual(get_platform(), 'macosx-10.3-ppc')
sys.maxsize = 9223372036854775807
self.assertEqual(get_platform(), 'macosx-10.3-ppc64')
finally:
sys.maxsize = maxint
self._set_uname(('Darwin', 'macziade', '8.11.1',
('Darwin Kernel Version 8.11.1: '
'Wed Oct 10 18:23:28 PDT 2007; '
'root:xnu-792.25.20~1/RELEASE_I386'), 'i386'))
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
'-fwrapv -O3 -Wall -Wstrict-prototypes')
maxint = sys.maxsize
try:
sys.maxsize = 2147483647
self.assertEqual(get_platform(), 'macosx-10.3-i386')
sys.maxsize = 9223372036854775807
self.assertEqual(get_platform(), 'macosx-10.3-x86_64')
finally:
sys.maxsize = maxint
# macbook with fat binaries (fat, universal or fat64)
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.4'
get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-fat')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-intel')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-fat3')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-universal')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-fat64')
for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3' % arch)
self.assertEqual(get_platform(), 'macosx-10.4-%s' % arch)
# linux debian sarge
os.name = 'posix'
sys.version = ('2.3.5 (#1, Jul 4 2007, 17:28:59) '
'\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]')
sys.platform = 'linux2'
self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
'#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
self.assertEqual(get_platform(), 'linux-i686')
# XXX more platforms to tests here
def test_get_config_h_filename(self):
config_h = sysconfig.get_config_h_filename()
self.assertTrue(os.path.isfile(config_h), config_h)
def test_get_scheme_names(self):
wanted = ('nt', 'nt_user', 'osx_framework_user',
'posix_home', 'posix_prefix', 'posix_user')
self.assertEqual(get_scheme_names(), wanted)
@skip_unless_symlink
def test_symlink(self):
# On Windows, the EXE needs to know where pythonXY.dll is at so we have
# to add the directory to the path.
if sys.platform == "win32":
os.environ["PATH"] = "{};{}".format(
os.path.dirname(sys.executable), os.environ["PATH"])
# Issue 7880
def get(python):
cmd = [python, '-c',
'import sysconfig; print(sysconfig.get_platform())']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=os.environ)
return p.communicate()
real = os.path.realpath(sys.executable)
link = os.path.abspath(TESTFN)
os.symlink(real, link)
try:
self.assertEqual(get(real), get(link))
finally:
unlink(link)
def test_user_similar(self):
# Issue #8759: make sure the posix scheme for the users
# is similar to the global posix_prefix one
base = get_config_var('base')
user = get_config_var('userbase')
# the global scheme mirrors the distinction between prefix and
# exec-prefix but not the user scheme, so we have to adapt the paths
# before comparing (issue #9100)
adapt = sys.base_prefix != sys.base_exec_prefix
for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
global_path = get_path(name, 'posix_prefix')
if adapt:
global_path = global_path.replace(sys.exec_prefix, sys.base_prefix)
base = base.replace(sys.exec_prefix, sys.base_prefix)
elif sys.base_prefix != sys.prefix:
# virtual environment? Likewise, we have to adapt the paths
# before comparing
global_path = global_path.replace(sys.base_prefix, sys.prefix)
base = base.replace(sys.base_prefix, sys.prefix)
user_path = get_path(name, 'posix_user')
self.assertEqual(user_path, global_path.replace(base, user, 1))
def test_main(self):
# just making sure _main() runs and returns things in the stdout
with captured_stdout() as output:
_main()
self.assertTrue(len(output.getvalue().split('\n')) > 0)
@unittest.skipIf(sys.platform == "win32", "Does not apply to Windows")
def test_ldshared_value(self):
ldflags = sysconfig.get_config_var('LDFLAGS')
ldshared = sysconfig.get_config_var('LDSHARED')
self.assertIn(ldflags, ldshared)
@unittest.skipUnless(sys.platform == "darwin", "test only relevant on MacOSX")
def test_platform_in_subprocess(self):
my_platform = sysconfig.get_platform()
# Test without MACOSX_DEPLOYMENT_TARGET in the environment
env = os.environ.copy()
if 'MACOSX_DEPLOYMENT_TARGET' in env:
del env['MACOSX_DEPLOYMENT_TARGET']
p = subprocess.Popen([
sys.executable, '-c',
'import sysconfig; print(sysconfig.get_platform())',
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=env)
test_platform = p.communicate()[0].strip()
test_platform = test_platform.decode('utf-8')
status = p.wait()
self.assertEqual(status, 0)
self.assertEqual(my_platform, test_platform)
# Test with MACOSX_DEPLOYMENT_TARGET in the environment, and
# using a value that is unlikely to be the default one.
env = os.environ.copy()
env['MACOSX_DEPLOYMENT_TARGET'] = '10.1'
p = subprocess.Popen([
sys.executable, '-c',
'import sysconfig; print(sysconfig.get_platform())',
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=env)
test_platform = p.communicate()[0].strip()
test_platform = test_platform.decode('utf-8')
status = p.wait()
self.assertEqual(status, 0)
self.assertEqual(my_platform, test_platform)
def test_srcdir(self):
# See Issues #15322, #15364.
srcdir = sysconfig.get_config_var('srcdir')
self.assertTrue(os.path.isabs(srcdir), srcdir)
self.assertTrue(os.path.isdir(srcdir), srcdir)
if sysconfig._PYTHON_BUILD:
# The python executable has not been installed so srcdir
# should be a full source checkout.
Python_h = os.path.join(srcdir, 'Include', 'Python.h')
self.assertTrue(os.path.exists(Python_h), Python_h)
self.assertTrue(sysconfig._is_python_source_dir(srcdir))
elif os.name == 'posix':
makefile_dir = os.path.dirname(sysconfig.get_makefile_filename())
# Issue #19340: srcdir has been realpath'ed already
makefile_dir = os.path.realpath(makefile_dir)
self.assertEqual(makefile_dir, srcdir)
def test_srcdir_independent_of_cwd(self):
# srcdir should be independent of the current working directory
# See Issues #15322, #15364.
srcdir = sysconfig.get_config_var('srcdir')
cwd = os.getcwd()
try:
os.chdir('..')
srcdir2 = sysconfig.get_config_var('srcdir')
finally:
os.chdir(cwd)
self.assertEqual(srcdir, srcdir2)
@unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
'EXT_SUFFIX required for this test')
def test_SO_deprecation(self):
self.assertWarns(DeprecationWarning,
sysconfig.get_config_var, 'SO')
@unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
'EXT_SUFFIX required for this test')
def test_SO_value(self):
with check_warnings(('', DeprecationWarning)):
self.assertEqual(sysconfig.get_config_var('SO'),
sysconfig.get_config_var('EXT_SUFFIX'))
@unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
'EXT_SUFFIX required for this test')
def test_SO_in_vars(self):
vars = sysconfig.get_config_vars()
self.assertIsNotNone(vars['SO'])
self.assertEqual(vars['SO'], vars['EXT_SUFFIX'])
class MakefileTests(unittest.TestCase):
@unittest.skipIf(sys.platform.startswith('win'),
'Test is not Windows compatible')
def test_get_makefile_filename(self):
makefile = sysconfig.get_makefile_filename()
self.assertTrue(os.path.isfile(makefile), makefile)
def test_parse_makefile(self):
self.addCleanup(unlink, TESTFN)
with open(TESTFN, "w") as makefile:
print("var1=a$(VAR2)", file=makefile)
print("VAR2=b$(var3)", file=makefile)
print("var3=42", file=makefile)
print("var4=$/invalid", file=makefile)
print("var5=dollar$$5", file=makefile)
vars = sysconfig._parse_makefile(TESTFN)
self.assertEqual(vars, {
'var1': 'ab42',
'VAR2': 'b42',
'var3': 42,
'var4': '$/invalid',
'var5': 'dollar$5',
})
def test_main():
run_unittest(TestSysConfig, MakefileTests)
if __name__ == "__main__":
test_main()
| lgpl-3.0 |
enenche/more-recipes-project | server/node_modules/nodemon/travis_after_all.py | 229 | 4462 | import os
import sys
import json
import time
import logging
try:
from functools import reduce
except ImportError:
pass
try:
import urllib.request as urllib2
except ImportError:
import urllib2
log = logging.getLogger("travis.leader")
log.addHandler(logging.StreamHandler())
log.setLevel(logging.INFO)
TRAVIS_JOB_NUMBER = 'TRAVIS_JOB_NUMBER'
TRAVIS_BUILD_ID = 'TRAVIS_BUILD_ID'
POLLING_INTERVAL = 'LEADER_POLLING_INTERVAL'
GITHUB_TOKEN = 'GITHUB_TOKEN'
# Travis API entry point, there are at least https://api.travis-ci.com and https://api.travis-ci.org
travis_entry = sys.argv[1] if len(sys.argv) > 1 else 'https://api.travis-ci.org'
build_id = os.getenv(TRAVIS_BUILD_ID)
polling_interval = int(os.getenv(POLLING_INTERVAL, '5'))
gh_token = os.getenv(GITHUB_TOKEN)
# assume, first job is the leader
def is_leader(job_number):
return job_number.endswith('.1')
job_number = os.getenv(TRAVIS_JOB_NUMBER)
if not job_number:
# seems even for builds with only one job, this won't get here
log.fatal("Don't use defining leader for build without matrix")
exit(1)
elif is_leader(job_number):
log.info("This is a leader")
else:
# since python is subprocess, env variables are exported back via file
with open(".to_export_back", "w") as export_var:
export_var.write("BUILD_MINION=YES")
log.info("This is a minion")
exit(0)
class MatrixElement(object):
def __init__(self, json_raw):
self.is_finished = json_raw['finished_at'] is not None
self.is_succeeded = json_raw['result'] == 0
self.number = json_raw['number']
self.is_leader = is_leader(self.number)
def matrix_snapshot(travis_token):
"""
:return: Matrix List
"""
headers = {'content-type': 'application/json', 'Authorization': 'token {}'.format(travis_token)}
req = urllib2.Request("{0}/builds/{1}".format(travis_entry, build_id), headers=headers)
response = urllib2.urlopen(req).read()
raw_json = json.loads(response.decode('utf-8'))
matrix_without_leader = [MatrixElement(job) for job in raw_json["matrix"] if not is_leader(job['number'])]
return matrix_without_leader
def wait_others_to_finish(travis_token):
def others_finished():
"""
Dumps others to finish
Leader cannot finish, it is working now
:return: tuple(True or False, List of not finished jobs)
"""
snapshot = matrix_snapshot(travis_token)
finished = [job.is_finished for job in snapshot if not job.is_leader]
return reduce(lambda a, b: a and b, finished), [job.number for job in snapshot if
not job.is_leader and not job.is_finished]
while True:
finished, waiting_list = others_finished()
if finished:
break
log.info("Leader waits for minions {0}...".format(waiting_list)) # just in case do not get "silence timeout"
time.sleep(polling_interval)
def get_token():
assert gh_token, 'GITHUB_TOKEN is not set'
data = {"github_token": gh_token}
headers = {'content-type': 'application/json', 'User-Agent': 'Travis/1.0'}
req = urllib2.Request("{0}/auth/github".format(travis_entry), json.dumps(data).encode('utf-8'), headers)
response = urllib2.urlopen(req).read()
travis_token = json.loads(response.decode('utf-8')).get('access_token')
return travis_token
try:
token = get_token()
wait_others_to_finish(token)
final_snapshot = matrix_snapshot(token)
log.info("Final Results: {0}".format([(e.number, e.is_succeeded) for e in final_snapshot]))
BUILD_AGGREGATE_STATUS = 'BUILD_AGGREGATE_STATUS'
others_snapshot = [el for el in final_snapshot if not el.is_leader]
if reduce(lambda a, b: a and b, [e.is_succeeded for e in others_snapshot]):
os.environ[BUILD_AGGREGATE_STATUS] = "others_succeeded"
elif reduce(lambda a, b: a and b, [not e.is_succeeded for e in others_snapshot]):
log.error("Others Failed")
os.environ[BUILD_AGGREGATE_STATUS] = "others_failed"
else:
log.warn("Others Unknown")
os.environ[BUILD_AGGREGATE_STATUS] = "unknown"
# since python is subprocess, env variables are exported back via file
with open(".to_export_back", "w") as export_var:
export_var.write("BUILD_LEADER=YES {0}={1}".format(BUILD_AGGREGATE_STATUS, os.environ[BUILD_AGGREGATE_STATUS]))
except Exception as e:
log.fatal(e)
| mit |
yigepodan/robotframework-selenium2library | demo/rundemo.py | 53 | 2488 | #! /usr/bin/env python
"""Runner Script for Robot Framework SeleniumLibrary Demo
Tests are run by giving a path to the tests to be executed as an argument to
this script. Possible Robot Framework options are given before the path.
Examples:
rundemo.py login_tests # Run all tests in a directory
rundemo.py login_tests/valid_login.text # Run tests in a specific file
rundemo.py --variable BROWSER:IE login_tests # Override variable
rundemo.py -v BROWSER:IE -v DELAY:0.25 login_tests
By default tests are executed with Firefox browser, but this can be changed
by overriding the `BROWSER` variable as illustrated above. Similarly it is
possible to slow down the test execution by overriding the `DELAY` variable
with a non-zero value.
When tests are run, the demo application is started and stopped automatically.
It is also possible to start and stop the application separately
by using `demoapp` options. This allows running tests with the
normal `pybot` start-up script, as well as investigating the demo application.
Running the demo requires that Robot Framework, Selenium2Library, Python, and
Java to be installed.
"""
import os
import sys
from tempfile import TemporaryFile
from subprocess import Popen, call, STDOUT
try:
import Selenium2Library
except ImportError, e:
print 'Importing Selenium2Library module failed (%s).' % e
print 'Please make sure you have Selenium2Library properly installed.'
print 'See INSTALL.rst for troubleshooting information.'
sys.exit(1)
ROOT = os.path.dirname(os.path.abspath(__file__))
DEMOAPP = os.path.join(ROOT, 'demoapp', 'server.py')
def run_tests(args):
start_demo_application()
call(['pybot'] + args, shell=(os.sep == '\\'))
stop_demo_application()
def start_demo_application():
Popen(['python', DEMOAPP, 'start'], stdout=TemporaryFile(), stderr=STDOUT)
def stop_demo_application():
call(['python', DEMOAPP, 'stop'], stdout=TemporaryFile(), stderr=STDOUT)
def print_help():
print __doc__
def print_usage():
print 'Usage: rundemo.py [options] datasource'
print ' or: rundemo.py demoapp start|stop'
print ' or: rundemo.py help'
if __name__ == '__main__':
action = {'demoapp-start': start_demo_application,
'demoapp-stop': stop_demo_application,
'help': print_help,
'': print_usage}.get('-'.join(sys.argv[1:]))
if action:
action()
else:
run_tests(sys.argv[1:])
| apache-2.0 |
dfunckt/django | tests/model_fields/test_uuid.py | 11 | 6590 | import json
import uuid
from django.core import exceptions, serializers
from django.db import IntegrityError, models
from django.test import (
SimpleTestCase, TestCase, TransactionTestCase, skipUnlessDBFeature,
)
from .models import (
NullableUUIDModel, PrimaryKeyUUIDModel, RelatedToUUIDModel, UUIDGrandchild,
UUIDModel,
)
class TestSaveLoad(TestCase):
def test_uuid_instance(self):
instance = UUIDModel.objects.create(field=uuid.uuid4())
loaded = UUIDModel.objects.get()
self.assertEqual(loaded.field, instance.field)
def test_str_instance_no_hyphens(self):
UUIDModel.objects.create(field='550e8400e29b41d4a716446655440000')
loaded = UUIDModel.objects.get()
self.assertEqual(loaded.field, uuid.UUID('550e8400e29b41d4a716446655440000'))
def test_str_instance_hyphens(self):
UUIDModel.objects.create(field='550e8400-e29b-41d4-a716-446655440000')
loaded = UUIDModel.objects.get()
self.assertEqual(loaded.field, uuid.UUID('550e8400e29b41d4a716446655440000'))
def test_str_instance_bad_hyphens(self):
UUIDModel.objects.create(field='550e84-00-e29b-41d4-a716-4-466-55440000')
loaded = UUIDModel.objects.get()
self.assertEqual(loaded.field, uuid.UUID('550e8400e29b41d4a716446655440000'))
def test_null_handling(self):
NullableUUIDModel.objects.create(field=None)
loaded = NullableUUIDModel.objects.get()
self.assertIsNone(loaded.field)
def test_pk_validated(self):
with self.assertRaisesMessage(exceptions.ValidationError, 'is not a valid UUID'):
PrimaryKeyUUIDModel.objects.get(pk={})
with self.assertRaisesMessage(exceptions.ValidationError, 'is not a valid UUID'):
PrimaryKeyUUIDModel.objects.get(pk=[])
def test_wrong_value(self):
with self.assertRaisesMessage(exceptions.ValidationError, 'is not a valid UUID'):
UUIDModel.objects.get(field='not-a-uuid')
with self.assertRaisesMessage(exceptions.ValidationError, 'is not a valid UUID'):
UUIDModel.objects.create(field='not-a-uuid')
class TestMigrations(SimpleTestCase):
def test_deconstruct(self):
field = models.UUIDField()
name, path, args, kwargs = field.deconstruct()
self.assertEqual(kwargs, {})
class TestQuerying(TestCase):
def setUp(self):
self.objs = [
NullableUUIDModel.objects.create(field=uuid.uuid4()),
NullableUUIDModel.objects.create(field='550e8400e29b41d4a716446655440000'),
NullableUUIDModel.objects.create(field=None),
]
def test_exact(self):
self.assertSequenceEqual(
NullableUUIDModel.objects.filter(field__exact='550e8400e29b41d4a716446655440000'),
[self.objs[1]]
)
def test_isnull(self):
self.assertSequenceEqual(
NullableUUIDModel.objects.filter(field__isnull=True),
[self.objs[2]]
)
class TestSerialization(SimpleTestCase):
test_data = (
'[{"fields": {"field": "550e8400-e29b-41d4-a716-446655440000"}, '
'"model": "model_fields.uuidmodel", "pk": null}]'
)
def test_dumping(self):
instance = UUIDModel(field=uuid.UUID('550e8400e29b41d4a716446655440000'))
data = serializers.serialize('json', [instance])
self.assertEqual(json.loads(data), json.loads(self.test_data))
def test_loading(self):
instance = list(serializers.deserialize('json', self.test_data))[0].object
self.assertEqual(instance.field, uuid.UUID('550e8400-e29b-41d4-a716-446655440000'))
class TestValidation(SimpleTestCase):
def test_invalid_uuid(self):
field = models.UUIDField()
with self.assertRaises(exceptions.ValidationError) as cm:
field.clean('550e8400', None)
self.assertEqual(cm.exception.code, 'invalid')
self.assertEqual(cm.exception.message % cm.exception.params, "'550e8400' is not a valid UUID.")
def test_uuid_instance_ok(self):
field = models.UUIDField()
field.clean(uuid.uuid4(), None) # no error
class TestAsPrimaryKey(TestCase):
def test_creation(self):
PrimaryKeyUUIDModel.objects.create()
loaded = PrimaryKeyUUIDModel.objects.get()
self.assertIsInstance(loaded.pk, uuid.UUID)
def test_uuid_pk_on_save(self):
saved = PrimaryKeyUUIDModel.objects.create(id=None)
loaded = PrimaryKeyUUIDModel.objects.get()
self.assertIsNotNone(loaded.id, None)
self.assertEqual(loaded.id, saved.id)
def test_uuid_pk_on_bulk_create(self):
u1 = PrimaryKeyUUIDModel()
u2 = PrimaryKeyUUIDModel(id=None)
PrimaryKeyUUIDModel.objects.bulk_create([u1, u2])
# The two objects were correctly created.
u1_found = PrimaryKeyUUIDModel.objects.filter(id=u1.id).exists()
u2_found = PrimaryKeyUUIDModel.objects.exclude(id=u1.id).exists()
self.assertTrue(u1_found)
self.assertTrue(u2_found)
self.assertEqual(PrimaryKeyUUIDModel.objects.count(), 2)
def test_underlying_field(self):
pk_model = PrimaryKeyUUIDModel.objects.create()
RelatedToUUIDModel.objects.create(uuid_fk=pk_model)
related = RelatedToUUIDModel.objects.get()
self.assertEqual(related.uuid_fk.pk, related.uuid_fk_id)
def test_update_with_related_model_instance(self):
# regression for #24611
u1 = PrimaryKeyUUIDModel.objects.create()
u2 = PrimaryKeyUUIDModel.objects.create()
r = RelatedToUUIDModel.objects.create(uuid_fk=u1)
RelatedToUUIDModel.objects.update(uuid_fk=u2)
r.refresh_from_db()
self.assertEqual(r.uuid_fk, u2)
def test_update_with_related_model_id(self):
u1 = PrimaryKeyUUIDModel.objects.create()
u2 = PrimaryKeyUUIDModel.objects.create()
r = RelatedToUUIDModel.objects.create(uuid_fk=u1)
RelatedToUUIDModel.objects.update(uuid_fk=u2.pk)
r.refresh_from_db()
self.assertEqual(r.uuid_fk, u2)
def test_two_level_foreign_keys(self):
# exercises ForeignKey.get_db_prep_value()
UUIDGrandchild().save()
class TestAsPrimaryKeyTransactionTests(TransactionTestCase):
# Need a TransactionTestCase to avoid deferring FK constraint checking.
available_apps = ['model_fields']
@skipUnlessDBFeature('supports_foreign_keys')
def test_unsaved_fk(self):
u1 = PrimaryKeyUUIDModel()
with self.assertRaises(IntegrityError):
RelatedToUUIDModel.objects.create(uuid_fk=u1)
| bsd-3-clause |
Ikergune/firos | scripts/include/ros/dependencies/__init__.py | 2 | 1127 | #!/usr/bin/env python
# MIT License
#
# Copyright (c) <2015> <Ikergune, Etxetar>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| mit |
papouso/odoo | addons/l10n_it/__openerp__.py | 267 | 1992 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010
# OpenERP Italian Community (<http://www.openerp-italia.org>)
# Servabit srl
# Agile Business Group sagl
# Domsense srl
# Albatos srl
#
# Copyright (C) 2011-2012
# Associazione OpenERP Italia (<http://www.openerp-italia.org>)
#
# 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/>.
#
##############################################################################
{
'name': 'Italy - Accounting',
'version': '0.2',
'depends': ['base_vat','account_chart','base_iban'],
'author': 'OpenERP Italian Community',
'description': """
Piano dei conti italiano di un'impresa generica.
================================================
Italian accounting chart and localization.
""",
'license': 'AGPL-3',
'category': 'Localization/Account Charts',
'website': 'http://www.openerp-italia.org/',
'data': [
'data/account.account.template.csv',
'data/account.tax.code.template.csv',
'account_chart.xml',
'data/account.tax.template.csv',
'data/account.fiscal.position.template.csv',
'l10n_chart_it_generic.xml',
],
'demo': [],
'installable': True,
'auto_install': False,
}
| agpl-3.0 |
JamesRaynor67/mptcp_with_machine_learning | src/uan/bindings/modulegen__gcc_LP64.py | 2 | 536551 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
return True
pybindgen.settings.error_handler = ErrorHandler()
import sys
def module_init():
root_module = Module('ns.uan', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## address.h (module 'network'): ns3::Address [class]
module.add_class('Address', import_from_module='ns.network')
## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration]
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class]
module.add_class('AttributeConstructionList', import_from_module='ns.core')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct]
module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList'])
## buffer.h (module 'network'): ns3::Buffer [class]
module.add_class('Buffer', import_from_module='ns.network')
## buffer.h (module 'network'): ns3::Buffer::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer'])
## packet.h (module 'network'): ns3::ByteTagIterator [class]
module.add_class('ByteTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::ByteTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList', import_from_module='ns.network')
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator'])
## callback.h (module 'core'): ns3::CallbackBase [class]
module.add_class('CallbackBase', import_from_module='ns.core')
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer [class]
module.add_class('DeviceEnergyModelContainer', import_from_module='ns.energy')
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper [class]
module.add_class('DeviceEnergyModelHelper', allow_subclassing=True, import_from_module='ns.energy')
## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper [class]
module.add_class('EnergySourceHelper', allow_subclassing=True, import_from_module='ns.energy')
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId', import_from_module='ns.core')
## hash.h (module 'core'): ns3::Hasher [class]
module.add_class('Hasher', import_from_module='ns.core')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address', import_from_module='ns.network')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class]
module.add_class('Ipv6Prefix', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
module.add_class('Mac48Address', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class]
module.add_class('NetDeviceContainer', import_from_module='ns.network')
## node-container.h (module 'network'): ns3::NodeContainer [class]
module.add_class('NodeContainer', import_from_module='ns.network')
## object-base.h (module 'core'): ns3::ObjectBase [class]
module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core')
## object.h (module 'core'): ns3::ObjectDeleter [struct]
module.add_class('ObjectDeleter', import_from_module='ns.core')
## object-factory.h (module 'core'): ns3::ObjectFactory [class]
module.add_class('ObjectFactory', import_from_module='ns.core')
## packet-metadata.h (module 'network'): ns3::PacketMetadata [class]
module.add_class('PacketMetadata', import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration]
module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class]
module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet.h (module 'network'): ns3::PacketTagIterator [class]
module.add_class('PacketTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::PacketTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList [class]
module.add_class('PacketTagList', import_from_module='ns.network')
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct]
module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration]
module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network')
## uan-mac-rc.h (module 'uan'): ns3::Reservation [class]
module.add_class('Reservation')
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simulator.h (module 'core'): ns3::Simulator [class]
module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core')
## simulator.h (module 'core'): ns3::Simulator [enumeration]
module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core')
## tag.h (module 'network'): ns3::Tag [class]
module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## tag-buffer.h (module 'network'): ns3::TagBuffer [class]
module.add_class('TagBuffer', import_from_module='ns.network')
## uan-prop-model.h (module 'uan'): ns3::Tap [class]
module.add_class('Tap')
## nstime.h (module 'core'): ns3::TimeWithUnit [class]
module.add_class('TimeWithUnit', import_from_module='ns.core')
## traced-value.h (module 'core'): ns3::TracedValue<double> [class]
module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['double'])
## type-id.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId', import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration]
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct]
module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## uan-address.h (module 'uan'): ns3::UanAddress [class]
module.add_class('UanAddress')
## uan-address.h (module 'uan'): ns3::UanAddress [class]
root_module['ns3::UanAddress'].implicitly_converts_to(root_module['ns3::Address'])
## uan-helper.h (module 'uan'): ns3::UanHelper [class]
module.add_class('UanHelper')
## uan-tx-mode.h (module 'uan'): ns3::UanModesList [class]
module.add_class('UanModesList')
## uan-transducer.h (module 'uan'): ns3::UanPacketArrival [class]
module.add_class('UanPacketArrival')
## uan-prop-model.h (module 'uan'): ns3::UanPdp [class]
module.add_class('UanPdp')
## uan-phy.h (module 'uan'): ns3::UanPhyListener [class]
module.add_class('UanPhyListener', allow_subclassing=True)
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode [class]
module.add_class('UanTxMode')
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::ModulationType [enumeration]
module.add_enum('ModulationType', ['PSK', 'QAM', 'FSK', 'OTHER'], outer_class=root_module['ns3::UanTxMode'])
## uan-tx-mode.h (module 'uan'): ns3::UanTxModeFactory [class]
module.add_class('UanTxModeFactory')
## vector.h (module 'core'): ns3::Vector2D [class]
module.add_class('Vector2D', import_from_module='ns.core')
## vector.h (module 'core'): ns3::Vector3D [class]
module.add_class('Vector3D', import_from_module='ns.core')
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration]
module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core')
## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::AcousticModemEnergyModelHelper [class]
module.add_class('AcousticModemEnergyModelHelper', parent=root_module['ns3::DeviceEnergyModelHelper'])
## chunk.h (module 'network'): ns3::Chunk [class]
module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## header.h (module 'network'): ns3::Header [class]
module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## object.h (module 'core'): ns3::Object [class]
module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
## object.h (module 'core'): ns3::Object::AggregateIterator [class]
module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class]
module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class]
module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time', import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time::Unit [enumeration]
module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time [class]
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class]
module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## trailer.h (module 'network'): ns3::Trailer [class]
module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class]
module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon [class]
module.add_class('UanHeaderCommon', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcAck [class]
module.add_class('UanHeaderRcAck', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts [class]
module.add_class('UanHeaderRcCts', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal [class]
module.add_class('UanHeaderRcCtsGlobal', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData [class]
module.add_class('UanHeaderRcData', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts [class]
module.add_class('UanHeaderRcRts', parent=root_module['ns3::Header'])
## uan-mac.h (module 'uan'): ns3::UanMac [class]
module.add_class('UanMac', parent=root_module['ns3::Object'])
## uan-mac-aloha.h (module 'uan'): ns3::UanMacAloha [class]
module.add_class('UanMacAloha', parent=root_module['ns3::UanMac'])
## uan-mac-cw.h (module 'uan'): ns3::UanMacCw [class]
module.add_class('UanMacCw', parent=[root_module['ns3::UanMac'], root_module['ns3::UanPhyListener']])
## uan-mac-rc.h (module 'uan'): ns3::UanMacRc [class]
module.add_class('UanMacRc', parent=root_module['ns3::UanMac'])
## uan-mac-rc.h (module 'uan'): ns3::UanMacRc [enumeration]
module.add_enum('', ['TYPE_DATA', 'TYPE_GWPING', 'TYPE_RTS', 'TYPE_CTS', 'TYPE_ACK'], outer_class=root_module['ns3::UanMacRc'])
## uan-mac-rc-gw.h (module 'uan'): ns3::UanMacRcGw [class]
module.add_class('UanMacRcGw', parent=root_module['ns3::UanMac'])
## uan-noise-model.h (module 'uan'): ns3::UanNoiseModel [class]
module.add_class('UanNoiseModel', parent=root_module['ns3::Object'])
## uan-noise-model-default.h (module 'uan'): ns3::UanNoiseModelDefault [class]
module.add_class('UanNoiseModelDefault', parent=root_module['ns3::UanNoiseModel'])
## uan-phy.h (module 'uan'): ns3::UanPhy [class]
module.add_class('UanPhy', parent=root_module['ns3::Object'])
## uan-phy.h (module 'uan'): ns3::UanPhy::State [enumeration]
module.add_enum('State', ['IDLE', 'CCABUSY', 'RX', 'TX', 'SLEEP', 'DISABLED'], outer_class=root_module['ns3::UanPhy'])
## uan-phy.h (module 'uan'): ns3::UanPhyCalcSinr [class]
module.add_class('UanPhyCalcSinr', parent=root_module['ns3::Object'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrDefault [class]
module.add_class('UanPhyCalcSinrDefault', parent=root_module['ns3::UanPhyCalcSinr'])
## uan-phy-dual.h (module 'uan'): ns3::UanPhyCalcSinrDual [class]
module.add_class('UanPhyCalcSinrDual', parent=root_module['ns3::UanPhyCalcSinr'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrFhFsk [class]
module.add_class('UanPhyCalcSinrFhFsk', parent=root_module['ns3::UanPhyCalcSinr'])
## uan-phy-dual.h (module 'uan'): ns3::UanPhyDual [class]
module.add_class('UanPhyDual', parent=root_module['ns3::UanPhy'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyGen [class]
module.add_class('UanPhyGen', parent=root_module['ns3::UanPhy'])
## uan-phy.h (module 'uan'): ns3::UanPhyPer [class]
module.add_class('UanPhyPer', parent=root_module['ns3::Object'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerGenDefault [class]
module.add_class('UanPhyPerGenDefault', parent=root_module['ns3::UanPhyPer'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerUmodem [class]
module.add_class('UanPhyPerUmodem', parent=root_module['ns3::UanPhyPer'])
## uan-prop-model.h (module 'uan'): ns3::UanPropModel [class]
module.add_class('UanPropModel', parent=root_module['ns3::Object'])
## uan-prop-model-ideal.h (module 'uan'): ns3::UanPropModelIdeal [class]
module.add_class('UanPropModelIdeal', parent=root_module['ns3::UanPropModel'])
## uan-prop-model-thorp.h (module 'uan'): ns3::UanPropModelThorp [class]
module.add_class('UanPropModelThorp', parent=root_module['ns3::UanPropModel'])
## uan-transducer.h (module 'uan'): ns3::UanTransducer [class]
module.add_class('UanTransducer', parent=root_module['ns3::Object'])
## uan-transducer.h (module 'uan'): ns3::UanTransducer::State [enumeration]
module.add_enum('State', ['TX', 'RX'], outer_class=root_module['ns3::UanTransducer'])
## uan-transducer-hd.h (module 'uan'): ns3::UanTransducerHd [class]
module.add_class('UanTransducerHd', parent=root_module['ns3::UanTransducer'])
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class]
module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class]
module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class]
module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class]
module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## boolean.h (module 'core'): ns3::BooleanChecker [class]
module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## boolean.h (module 'core'): ns3::BooleanValue [class]
module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## channel.h (module 'network'): ns3::Channel [class]
module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class]
module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class]
module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel [class]
module.add_class('DeviceEnergyModel', import_from_module='ns.energy', parent=root_module['ns3::Object'])
## double.h (module 'core'): ns3::DoubleValue [class]
module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class]
module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## energy-harvester.h (module 'energy'): ns3::EnergyHarvester [class]
module.add_class('EnergyHarvester', import_from_module='ns.energy', parent=root_module['ns3::Object'])
## energy-source.h (module 'energy'): ns3::EnergySource [class]
module.add_class('EnergySource', import_from_module='ns.energy', parent=root_module['ns3::Object'])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer [class]
module.add_class('EnergySourceContainer', import_from_module='ns.energy', parent=root_module['ns3::Object'])
## enum.h (module 'core'): ns3::EnumChecker [class]
module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## enum.h (module 'core'): ns3::EnumValue [class]
module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class]
module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## event-impl.h (module 'core'): ns3::EventImpl [class]
module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class]
module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class]
module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## integer.h (module 'core'): ns3::IntegerValue [class]
module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class]
module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class]
module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class]
module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class]
module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class]
module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class]
module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class]
module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class]
module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class]
module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class]
module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class]
module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## mobility-model.h (module 'mobility'): ns3::MobilityModel [class]
module.add_class('MobilityModel', import_from_module='ns.mobility', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration]
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
## net-device.h (module 'network'): ns3::NetDeviceQueue [class]
module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >'])
## net-device.h (module 'network'): ns3::NetDeviceQueueInterface [class]
module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object'])
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class]
module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class]
module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## pointer.h (module 'core'): ns3::PointerChecker [class]
module.add_class('PointerChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## pointer.h (module 'core'): ns3::PointerValue [class]
module.add_class('PointerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## net-device.h (module 'network'): ns3::QueueItem [class]
module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >'])
## net-device.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration]
module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network')
## nstime.h (module 'core'): ns3::TimeValue [class]
module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## type-id.h (module 'core'): ns3::TypeIdChecker [class]
module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## type-id.h (module 'core'): ns3::TypeIdValue [class]
module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## uan-channel.h (module 'uan'): ns3::UanChannel [class]
module.add_class('UanChannel', parent=root_module['ns3::Channel'])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker [class]
module.add_class('UanModesListChecker', parent=root_module['ns3::AttributeChecker'])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue [class]
module.add_class('UanModesListValue', parent=root_module['ns3::AttributeValue'])
## uan-net-device.h (module 'uan'): ns3::UanNetDevice [class]
module.add_class('UanNetDevice', parent=root_module['ns3::NetDevice'])
## uinteger.h (module 'core'): ns3::UintegerValue [class]
module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## vector.h (module 'core'): ns3::Vector2DChecker [class]
module.add_class('Vector2DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## vector.h (module 'core'): ns3::Vector2DValue [class]
module.add_class('Vector2DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## vector.h (module 'core'): ns3::Vector3DChecker [class]
module.add_class('Vector3DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## vector.h (module 'core'): ns3::Vector3DValue [class]
module.add_class('Vector3DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel [class]
module.add_class('AcousticModemEnergyModel', parent=root_module['ns3::DeviceEnergyModel'])
## address.h (module 'network'): ns3::AddressChecker [class]
module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## address.h (module 'network'): ns3::AddressValue [class]
module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_container('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress > >', 'std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress >', container_type=u'list')
module.add_container('std::vector< ns3::Tap >', 'ns3::Tap', container_type=u'vector')
module.add_container('std::vector< std::complex< double > >', 'std::complex< double >', container_type=u'vector')
module.add_container('std::vector< double >', 'double', container_type=u'vector')
module.add_container('std::set< unsigned char >', 'unsigned char', container_type=u'set')
module.add_container('std::list< ns3::UanPacketArrival >', 'ns3::UanPacketArrival', container_type=u'list')
module.add_container('std::list< ns3::Ptr< ns3::UanPhy > >', 'ns3::Ptr< ns3::UanPhy >', container_type=u'list')
module.add_container('std::vector< std::pair< ns3::Ptr< ns3::UanNetDevice >, ns3::Ptr< ns3::UanTransducer > > >', 'std::pair< ns3::Ptr< ns3::UanNetDevice >, ns3::Ptr< ns3::UanTransducer > >', container_type=u'vector')
module.add_container('std::list< ns3::Ptr< ns3::UanTransducer > >', 'ns3::Ptr< ns3::UanTransducer >', container_type=u'list')
typehandlers.add_type_alias(u'ns3::Vector3DValue', u'ns3::VectorValue')
typehandlers.add_type_alias(u'ns3::Vector3DValue*', u'ns3::VectorValue*')
typehandlers.add_type_alias(u'ns3::Vector3DValue&', u'ns3::VectorValue&')
module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue')
typehandlers.add_type_alias(u'ns3::Vector3D', u'ns3::Vector')
typehandlers.add_type_alias(u'ns3::Vector3D*', u'ns3::Vector*')
typehandlers.add_type_alias(u'ns3::Vector3D&', u'ns3::Vector&')
module.add_typedef(root_module['ns3::Vector3D'], 'Vector')
typehandlers.add_type_alias(u'ns3::Vector3DChecker', u'ns3::VectorChecker')
typehandlers.add_type_alias(u'ns3::Vector3DChecker*', u'ns3::VectorChecker*')
typehandlers.add_type_alias(u'ns3::Vector3DChecker&', u'ns3::VectorChecker&')
module.add_typedef(root_module['ns3::Vector3DChecker'], 'VectorChecker')
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace Hash
nested_module = module.add_cpp_namespace('Hash')
register_types_ns3_Hash(nested_module)
## Register a nested module for the namespace TracedValueCallback
nested_module = module.add_cpp_namespace('TracedValueCallback')
register_types_ns3_TracedValueCallback(nested_module)
## Register a nested module for the namespace internal
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(nested_module)
def register_types_ns3_FatalImpl(module):
root_module = module.get_root()
def register_types_ns3_Hash(module):
root_module = module.get_root()
## hash-function.h (module 'core'): ns3::Hash::Implementation [class]
module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&')
## Register a nested module for the namespace Function
nested_module = module.add_cpp_namespace('Function')
register_types_ns3_Hash_Function(nested_module)
def register_types_ns3_Hash_Function(module):
root_module = module.get_root()
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class]
module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class]
module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class]
module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class]
module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
def register_types_ns3_TracedValueCallback(module):
root_module = module.get_root()
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *', u'ns3::TracedValueCallback::Int8')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) **', u'ns3::TracedValueCallback::Int8*')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *&', u'ns3::TracedValueCallback::Int8&')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *', u'ns3::TracedValueCallback::Uint8')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) **', u'ns3::TracedValueCallback::Uint8*')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *&', u'ns3::TracedValueCallback::Uint8&')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) *', u'ns3::TracedValueCallback::Double')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) **', u'ns3::TracedValueCallback::Double*')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) *&', u'ns3::TracedValueCallback::Double&')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *', u'ns3::TracedValueCallback::Uint32')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) **', u'ns3::TracedValueCallback::Uint32*')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *&', u'ns3::TracedValueCallback::Uint32&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *', u'ns3::TracedValueCallback::Bool')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) **', u'ns3::TracedValueCallback::Bool*')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *&', u'ns3::TracedValueCallback::Bool&')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *', u'ns3::TracedValueCallback::Int16')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) **', u'ns3::TracedValueCallback::Int16*')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *&', u'ns3::TracedValueCallback::Int16&')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *', u'ns3::TracedValueCallback::Int32')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) **', u'ns3::TracedValueCallback::Int32*')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *&', u'ns3::TracedValueCallback::Int32&')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *', u'ns3::TracedValueCallback::Uint16')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) **', u'ns3::TracedValueCallback::Uint16*')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *&', u'ns3::TracedValueCallback::Uint16&')
def register_types_ns3_internal(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer'])
register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator'])
register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator'])
register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item'])
register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList'])
register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator'])
register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item'])
register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase'])
register_Ns3DeviceEnergyModelContainer_methods(root_module, root_module['ns3::DeviceEnergyModelContainer'])
register_Ns3DeviceEnergyModelHelper_methods(root_module, root_module['ns3::DeviceEnergyModelHelper'])
register_Ns3EnergySourceHelper_methods(root_module, root_module['ns3::EnergySourceHelper'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address'])
register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata'])
register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item'])
register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3Reservation_methods(root_module, root_module['ns3::Reservation'])
register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3Tap_methods(root_module, root_module['ns3::Tap'])
register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit'])
register_Ns3TracedValue__Double_methods(root_module, root_module['ns3::TracedValue< double >'])
register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId'])
register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation'])
register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation'])
register_Ns3UanAddress_methods(root_module, root_module['ns3::UanAddress'])
register_Ns3UanHelper_methods(root_module, root_module['ns3::UanHelper'])
register_Ns3UanModesList_methods(root_module, root_module['ns3::UanModesList'])
register_Ns3UanPacketArrival_methods(root_module, root_module['ns3::UanPacketArrival'])
register_Ns3UanPdp_methods(root_module, root_module['ns3::UanPdp'])
register_Ns3UanPhyListener_methods(root_module, root_module['ns3::UanPhyListener'])
register_Ns3UanTxMode_methods(root_module, root_module['ns3::UanTxMode'])
register_Ns3UanTxModeFactory_methods(root_module, root_module['ns3::UanTxModeFactory'])
register_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D'])
register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3AcousticModemEnergyModelHelper_methods(root_module, root_module['ns3::AcousticModemEnergyModelHelper'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream'])
register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable'])
register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >'])
register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable'])
register_Ns3UanHeaderCommon_methods(root_module, root_module['ns3::UanHeaderCommon'])
register_Ns3UanHeaderRcAck_methods(root_module, root_module['ns3::UanHeaderRcAck'])
register_Ns3UanHeaderRcCts_methods(root_module, root_module['ns3::UanHeaderRcCts'])
register_Ns3UanHeaderRcCtsGlobal_methods(root_module, root_module['ns3::UanHeaderRcCtsGlobal'])
register_Ns3UanHeaderRcData_methods(root_module, root_module['ns3::UanHeaderRcData'])
register_Ns3UanHeaderRcRts_methods(root_module, root_module['ns3::UanHeaderRcRts'])
register_Ns3UanMac_methods(root_module, root_module['ns3::UanMac'])
register_Ns3UanMacAloha_methods(root_module, root_module['ns3::UanMacAloha'])
register_Ns3UanMacCw_methods(root_module, root_module['ns3::UanMacCw'])
register_Ns3UanMacRc_methods(root_module, root_module['ns3::UanMacRc'])
register_Ns3UanMacRcGw_methods(root_module, root_module['ns3::UanMacRcGw'])
register_Ns3UanNoiseModel_methods(root_module, root_module['ns3::UanNoiseModel'])
register_Ns3UanNoiseModelDefault_methods(root_module, root_module['ns3::UanNoiseModelDefault'])
register_Ns3UanPhy_methods(root_module, root_module['ns3::UanPhy'])
register_Ns3UanPhyCalcSinr_methods(root_module, root_module['ns3::UanPhyCalcSinr'])
register_Ns3UanPhyCalcSinrDefault_methods(root_module, root_module['ns3::UanPhyCalcSinrDefault'])
register_Ns3UanPhyCalcSinrDual_methods(root_module, root_module['ns3::UanPhyCalcSinrDual'])
register_Ns3UanPhyCalcSinrFhFsk_methods(root_module, root_module['ns3::UanPhyCalcSinrFhFsk'])
register_Ns3UanPhyDual_methods(root_module, root_module['ns3::UanPhyDual'])
register_Ns3UanPhyGen_methods(root_module, root_module['ns3::UanPhyGen'])
register_Ns3UanPhyPer_methods(root_module, root_module['ns3::UanPhyPer'])
register_Ns3UanPhyPerGenDefault_methods(root_module, root_module['ns3::UanPhyPerGenDefault'])
register_Ns3UanPhyPerUmodem_methods(root_module, root_module['ns3::UanPhyPerUmodem'])
register_Ns3UanPropModel_methods(root_module, root_module['ns3::UanPropModel'])
register_Ns3UanPropModelIdeal_methods(root_module, root_module['ns3::UanPropModelIdeal'])
register_Ns3UanPropModelThorp_methods(root_module, root_module['ns3::UanPropModelThorp'])
register_Ns3UanTransducer_methods(root_module, root_module['ns3::UanTransducer'])
register_Ns3UanTransducerHd_methods(root_module, root_module['ns3::UanTransducerHd'])
register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable'])
register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable'])
register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable'])
register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker'])
register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable'])
register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable'])
register_Ns3DeviceEnergyModel_methods(root_module, root_module['ns3::DeviceEnergyModel'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EnergyHarvester_methods(root_module, root_module['ns3::EnergyHarvester'])
register_Ns3EnergySource_methods(root_module, root_module['ns3::EnergySource'])
register_Ns3EnergySourceContainer_methods(root_module, root_module['ns3::EnergySourceContainer'])
register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker'])
register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue'])
register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable'])
register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable'])
register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue'])
register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker'])
register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue'])
register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker'])
register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue'])
register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker'])
register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue'])
register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker'])
register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue'])
register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue'])
register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable'])
register_Ns3PointerChecker_methods(root_module, root_module['ns3::PointerChecker'])
register_Ns3PointerValue_methods(root_module, root_module['ns3::PointerValue'])
register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem'])
register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue'])
register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker'])
register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue'])
register_Ns3UanChannel_methods(root_module, root_module['ns3::UanChannel'])
register_Ns3UanModesListChecker_methods(root_module, root_module['ns3::UanModesListChecker'])
register_Ns3UanModesListValue_methods(root_module, root_module['ns3::UanModesListValue'])
register_Ns3UanNetDevice_methods(root_module, root_module['ns3::UanNetDevice'])
register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue'])
register_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker'])
register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue'])
register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker'])
register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue'])
register_Ns3AcousticModemEnergyModel_methods(root_module, root_module['ns3::AcousticModemEnergyModel'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation'])
register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a'])
register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32'])
register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64'])
register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3'])
return
def register_Ns3Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## address.h (module 'network'): ns3::Address::Address() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor]
cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor]
cls.add_constructor([param('ns3::Address const &', 'address')])
## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function]
cls.add_method('CheckCompatible',
'bool',
[param('uint8_t', 'type'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyAllFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function]
cls.add_method('CopyAllTo',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'uint32_t',
[param('uint8_t *', 'buffer')],
is_const=True)
## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'buffer')])
## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function]
cls.add_method('GetLength',
'uint8_t',
[],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function]
cls.add_method('IsInvalid',
'bool',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function]
cls.add_method('IsMatchingType',
'bool',
[param('uint8_t', 'type')],
is_const=True)
## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function]
cls.add_method('Register',
'uint8_t',
[],
is_static=True)
## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'buffer')],
is_const=True)
return
def register_Ns3AttributeConstructionList_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')])
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('Find',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True)
return
def register_Ns3AttributeConstructionListItem_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable]
cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False)
return
def register_Ns3Buffer_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor]
cls.add_constructor([param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function]
cls.add_method('Begin',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Buffer',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function]
cls.add_method('End',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3BufferIterator_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')])
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function]
cls.add_method('GetDistanceFrom',
'uint32_t',
[param('ns3::Buffer::Iterator const &', 'o')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function]
cls.add_method('IsEnd',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function]
cls.add_method('IsStart',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function]
cls.add_method('Next',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function]
cls.add_method('Next',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function]
cls.add_method('PeekU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function]
cls.add_method('Prev',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function]
cls.add_method('Prev',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function]
cls.add_method('ReadLsbtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function]
cls.add_method('ReadLsbtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function]
cls.add_method('ReadLsbtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function]
cls.add_method('ReadNtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function]
cls.add_method('ReadNtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function]
cls.add_method('ReadNtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Write',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function]
cls.add_method('WriteHtolsbU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function]
cls.add_method('WriteHtolsbU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function]
cls.add_method('WriteHtolsbU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function]
cls.add_method('WriteHtonU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function]
cls.add_method('WriteHtonU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function]
cls.add_method('WriteHtonU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data'), param('uint32_t', 'len')])
return
def register_Ns3ByteTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagIterator::Item',
[])
return
def register_Ns3ByteTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function]
cls.add_method('GetEnd',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function]
cls.add_method('GetStart',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3ByteTagList_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor]
cls.add_constructor([])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function]
cls.add_method('Add',
'ns3::TagBuffer',
[param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function]
cls.add_method('Add',
'void',
[param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function]
cls.add_method('AddAtEnd',
'void',
[param('int32_t', 'appendOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function]
cls.add_method('AddAtStart',
'void',
[param('int32_t', 'prependOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function]
cls.add_method('Adjust',
'void',
[param('int32_t', 'adjustment')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function]
cls.add_method('Begin',
'ns3::ByteTagList::Iterator',
[param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')],
is_const=True)
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3ByteTagListIterator_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')])
## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function]
cls.add_method('GetOffsetStart',
'uint32_t',
[],
is_const=True)
## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagList::Iterator::Item',
[])
return
def register_Ns3ByteTagListIteratorItem_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor]
cls.add_constructor([param('ns3::TagBuffer', 'buf')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable]
cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable]
cls.add_instance_attribute('end', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable]
cls.add_instance_attribute('size', 'uint32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable]
cls.add_instance_attribute('start', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3CallbackBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function]
cls.add_method('GetImpl',
'ns3::Ptr< ns3::CallbackImplBase >',
[],
is_const=True)
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')],
visibility='protected')
return
def register_Ns3DeviceEnergyModelContainer_methods(root_module, cls):
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'arg0')])
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer() [constructor]
cls.add_constructor([])
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::Ptr<ns3::DeviceEnergyModel> model) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')])
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(std::string modelName) [constructor]
cls.add_constructor([param('std::string', 'modelName')])
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & a, ns3::DeviceEnergyModelContainer const & b) [constructor]
cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'a'), param('ns3::DeviceEnergyModelContainer const &', 'b')])
## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::DeviceEnergyModelContainer container) [member function]
cls.add_method('Add',
'void',
[param('ns3::DeviceEnergyModelContainer', 'container')])
## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::Ptr<ns3::DeviceEnergyModel> model) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')])
## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(std::string modelName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'modelName')])
## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >',
[],
is_const=True)
## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >',
[],
is_const=True)
## device-energy-model-container.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::DeviceEnergyModel >',
[param('uint32_t', 'i')],
is_const=True)
## device-energy-model-container.h (module 'energy'): uint32_t ns3::DeviceEnergyModelContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3DeviceEnergyModelHelper_methods(root_module, cls):
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper() [constructor]
cls.add_constructor([])
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper(ns3::DeviceEnergyModelHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeviceEnergyModelHelper const &', 'arg0')])
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function]
cls.add_method('Install',
'ns3::DeviceEnergyModelContainer',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_const=True)
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::NetDeviceContainer deviceContainer, ns3::EnergySourceContainer sourceContainer) const [member function]
cls.add_method('Install',
'ns3::DeviceEnergyModelContainer',
[param('ns3::NetDeviceContainer', 'deviceContainer'), param('ns3::EnergySourceContainer', 'sourceContainer')],
is_const=True)
## energy-model-helper.h (module 'energy'): void ns3::DeviceEnergyModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')],
is_pure_virtual=True, is_virtual=True)
## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelHelper::DoInstall(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function]
cls.add_method('DoInstall',
'ns3::Ptr< ns3::DeviceEnergyModel >',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EnergySourceHelper_methods(root_module, cls):
## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper() [constructor]
cls.add_constructor([])
## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper(ns3::EnergySourceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnergySourceHelper const &', 'arg0')])
## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::EnergySourceContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::EnergySourceContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::EnergySourceContainer',
[param('std::string', 'nodeName')],
is_const=True)
## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::InstallAll() const [member function]
cls.add_method('InstallAll',
'ns3::EnergySourceContainer',
[],
is_const=True)
## energy-model-helper.h (module 'energy'): void ns3::EnergySourceHelper::Set(std::string name, ns3::AttributeValue const & v) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')],
is_pure_virtual=True, is_virtual=True)
## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergySourceHelper::DoInstall(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('DoInstall',
'ns3::Ptr< ns3::EnergySource >',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('==')
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventId const &', 'arg0')])
## event-id.h (module 'core'): ns3::EventId::EventId() [constructor]
cls.add_constructor([])
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')])
## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function]
cls.add_method('GetTs',
'uint64_t',
[],
is_const=True)
## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function]
cls.add_method('PeekEventImpl',
'ns3::EventImpl *',
[],
is_const=True)
return
def register_Ns3Hasher_methods(root_module, cls):
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hasher const &', 'arg0')])
## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor]
cls.add_constructor([])
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('std::string const', 's')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('std::string const', 's')])
## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function]
cls.add_method('clear',
'ns3::Hasher &',
[])
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor]
cls.add_constructor([param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('CombineMask',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv4Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv4Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('GetSubnetDirectedBroadcast',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsAny() const [member function]
cls.add_method('IsAny',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Address const &', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function]
cls.add_method('IsLocalMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('IsSubnetDirectedBroadcast',
'bool',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
return
def register_Ns3Ipv4Mask_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor]
cls.add_constructor([param('uint32_t', 'mask')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor]
cls.add_constructor([param('char const *', 'mask')])
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function]
cls.add_method('GetInverse',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint16_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Mask', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'mask')])
return
def register_Ns3Ipv6Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor]
cls.add_constructor([param('uint8_t *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function]
cls.add_method('CombinePrefix',
'ns3::Ipv6Address',
[param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv6Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv6Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function]
cls.add_method('GetAllHostsMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function]
cls.add_method('GetAllNodesMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function]
cls.add_method('GetAllRoutersMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function]
cls.add_method('GetIpv4MappedAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function]
cls.add_method('IsAllHostsMulticast',
'bool',
[],
deprecated=True, is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function]
cls.add_method('IsAllNodesMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function]
cls.add_method('IsAllRoutersMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function]
cls.add_method('IsAny',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function]
cls.add_method('IsDocumentation',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Address const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function]
cls.add_method('IsIpv4MappedAddress',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function]
cls.add_method('IsLinkLocal',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function]
cls.add_method('IsLinkLocalMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function]
cls.add_method('IsSolicitedMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac16Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac64Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('MakeIpv4MappedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv4Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function]
cls.add_method('MakeSolicitedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv6Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function]
cls.add_method('Set',
'void',
[param('uint8_t *', 'address')])
return
def register_Ns3Ipv6Prefix_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor]
cls.add_constructor([param('uint8_t *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor]
cls.add_constructor([param('char const *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor]
cls.add_constructor([param('uint8_t', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint8_t',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Prefix const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
return
def register_Ns3Mac48Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac48Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv4Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv6Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function]
cls.add_method('GetMulticast6Prefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function]
cls.add_method('GetMulticastPrefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function]
cls.add_method('IsGroup',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3NetDeviceContainer_methods(root_module, cls):
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor]
cls.add_constructor([])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor]
cls.add_constructor([param('std::string', 'devName')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NetDeviceContainer', 'other')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'deviceName')])
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True)
## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeContainer_methods(root_module, cls):
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor]
cls.add_constructor([])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor]
cls.add_constructor([param('std::string', 'nodeName')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NodeContainer', 'other')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'nodeName')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n')])
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n'), param('uint32_t', 'systemId')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'i')],
is_const=True)
## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function]
cls.add_method('GetGlobal',
'ns3::NodeContainer',
[],
is_static=True)
## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3ObjectBase_methods(root_module, cls):
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor]
cls.add_constructor([])
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')])
## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function]
cls.add_method('ConstructSelf',
'void',
[param('ns3::AttributeConstructionList const &', 'attributes')],
visibility='protected')
## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function]
cls.add_method('NotifyConstructionCompleted',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectDeleter_methods(root_module, cls):
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor]
cls.add_constructor([])
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')])
## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Object *', 'object')],
is_static=True)
return
def register_Ns3ObjectFactory_methods(root_module, cls):
cls.add_output_stream_operator()
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor]
cls.add_constructor([param('std::string', 'typeId')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('ns3::TypeId', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('char const *', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('std::string', 'tid')])
return
def register_Ns3PacketMetadata_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor]
cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[param('ns3::Buffer', 'buffer')],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function]
cls.add_method('CreateFragment',
'ns3::PacketMetadata',
[param('uint32_t', 'start'), param('uint32_t', 'end')],
is_const=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function]
cls.add_method('Enable',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('RemoveTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3PacketMetadataItem_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor]
cls.add_constructor([])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable]
cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable]
cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable]
cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable]
cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable]
cls.add_instance_attribute('isFragment', 'bool', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor]
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketMetadata::Item',
[])
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function]
cls.add_method('Replace',
'bool',
[param('ns3::Tag &', 'tag')])
return
def register_Ns3PacketTagListTagData_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable]
cls.add_instance_attribute('count', 'uint32_t', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable]
cls.add_instance_attribute('data', 'uint8_t [ 21 ]', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable]
cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3Reservation_methods(root_module, cls):
## uan-mac-rc.h (module 'uan'): ns3::Reservation::Reservation(ns3::Reservation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Reservation const &', 'arg0')])
## uan-mac-rc.h (module 'uan'): ns3::Reservation::Reservation() [constructor]
cls.add_constructor([])
## uan-mac-rc.h (module 'uan'): ns3::Reservation::Reservation(std::list<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress>, std::allocator<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress> > > & list, uint8_t frameNo, uint32_t maxPkts=0) [constructor]
cls.add_constructor([param('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress > > &', 'list'), param('uint8_t', 'frameNo'), param('uint32_t', 'maxPkts', default_value='0')])
## uan-mac-rc.h (module 'uan'): void ns3::Reservation::AddTimestamp(ns3::Time t) [member function]
cls.add_method('AddTimestamp',
'void',
[param('ns3::Time', 't')])
## uan-mac-rc.h (module 'uan'): uint8_t ns3::Reservation::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): uint32_t ns3::Reservation::GetLength() const [member function]
cls.add_method('GetLength',
'uint32_t',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): uint32_t ns3::Reservation::GetNoFrames() const [member function]
cls.add_method('GetNoFrames',
'uint32_t',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): std::list<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress>, std::allocator<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress> > > const & ns3::Reservation::GetPktList() const [member function]
cls.add_method('GetPktList',
'std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress > > const &',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): uint8_t ns3::Reservation::GetRetryNo() const [member function]
cls.add_method('GetRetryNo',
'uint8_t',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): ns3::Time ns3::Reservation::GetTimestamp(uint8_t n) const [member function]
cls.add_method('GetTimestamp',
'ns3::Time',
[param('uint8_t', 'n')],
is_const=True)
## uan-mac-rc.h (module 'uan'): void ns3::Reservation::IncrementRetry() [member function]
cls.add_method('IncrementRetry',
'void',
[])
## uan-mac-rc.h (module 'uan'): bool ns3::Reservation::IsTransmitted() const [member function]
cls.add_method('IsTransmitted',
'bool',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): void ns3::Reservation::SetFrameNo(uint8_t fn) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'fn')])
## uan-mac-rc.h (module 'uan'): void ns3::Reservation::SetTransmitted(bool t=true) [member function]
cls.add_method('SetTransmitted',
'void',
[param('bool', 't', default_value='true')])
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function]
cls.add_method('SetImplementation',
'void',
[param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'delay')],
is_static=True)
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_Ns3Tap_methods(root_module, cls):
## uan-prop-model.h (module 'uan'): ns3::Tap::Tap(ns3::Tap const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tap const &', 'arg0')])
## uan-prop-model.h (module 'uan'): ns3::Tap::Tap() [constructor]
cls.add_constructor([])
## uan-prop-model.h (module 'uan'): ns3::Tap::Tap(ns3::Time delay, std::complex<double> amp) [constructor]
cls.add_constructor([param('ns3::Time', 'delay'), param('std::complex< double >', 'amp')])
## uan-prop-model.h (module 'uan'): std::complex<double> ns3::Tap::GetAmp() const [member function]
cls.add_method('GetAmp',
'std::complex< double >',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): ns3::Time ns3::Tap::GetDelay() const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[],
is_const=True)
return
def register_Ns3TimeWithUnit_methods(root_module, cls):
cls.add_output_stream_operator()
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor]
cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')])
return
def register_Ns3TracedValue__Double_methods(root_module, cls):
## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue() [constructor]
cls.add_constructor([])
## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue(ns3::TracedValue<double> const & o) [copy constructor]
cls.add_constructor([param('ns3::TracedValue< double > const &', 'o')])
## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue(double const & v) [constructor]
cls.add_constructor([param('double const &', 'v')])
## traced-value.h (module 'core'): void ns3::TracedValue<double>::Connect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function]
cls.add_method('Connect',
'void',
[param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')])
## traced-value.h (module 'core'): void ns3::TracedValue<double>::ConnectWithoutContext(ns3::CallbackBase const & cb) [member function]
cls.add_method('ConnectWithoutContext',
'void',
[param('ns3::CallbackBase const &', 'cb')])
## traced-value.h (module 'core'): void ns3::TracedValue<double>::Disconnect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function]
cls.add_method('Disconnect',
'void',
[param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')])
## traced-value.h (module 'core'): void ns3::TracedValue<double>::DisconnectWithoutContext(ns3::CallbackBase const & cb) [member function]
cls.add_method('DisconnectWithoutContext',
'void',
[param('ns3::CallbackBase const &', 'cb')])
## traced-value.h (module 'core'): double ns3::TracedValue<double>::Get() const [member function]
cls.add_method('Get',
'double',
[],
is_const=True)
## traced-value.h (module 'core'): void ns3::TracedValue<double>::Set(double const & v) [member function]
cls.add_method('Set',
'void',
[param('double const &', 'v')])
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')],
deprecated=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function]
cls.add_method('GetHash',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function]
cls.add_method('GetParent',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint32_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint32_t',
[],
is_static=True)
## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function]
cls.add_method('GetSize',
'std::size_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function]
cls.add_method('GetUid',
'uint16_t',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function]
cls.add_method('HasConstructor',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function]
cls.add_method('HasParent',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function]
cls.add_method('HideFromDocumentation',
'ns3::TypeId',
[])
## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function]
cls.add_method('IsChildOf',
'bool',
[param('ns3::TypeId', 'other')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function]
cls.add_method('LookupAttributeByName',
'bool',
[param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function]
cls.add_method('LookupByHash',
'ns3::TypeId',
[param('uint32_t', 'hash')],
is_static=True)
## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function]
cls.add_method('LookupByHashFailSafe',
'bool',
[param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')],
is_static=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function]
cls.add_method('MustHideFromDocumentation',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function]
cls.add_method('SetGroupName',
'ns3::TypeId',
[param('std::string', 'groupName')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[param('ns3::TypeId', 'tid')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function]
cls.add_method('SetSize',
'ns3::TypeId',
[param('std::size_t', 'size')])
## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'tid')])
return
def register_Ns3TypeIdAttributeInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable]
cls.add_instance_attribute('flags', 'uint32_t', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable]
cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable]
cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
return
def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable]
cls.add_instance_attribute('callback', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
return
def register_Ns3UanAddress_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## uan-address.h (module 'uan'): ns3::UanAddress::UanAddress(ns3::UanAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanAddress const &', 'arg0')])
## uan-address.h (module 'uan'): ns3::UanAddress::UanAddress() [constructor]
cls.add_constructor([])
## uan-address.h (module 'uan'): ns3::UanAddress::UanAddress(uint8_t addr) [constructor]
cls.add_constructor([param('uint8_t', 'addr')])
## uan-address.h (module 'uan'): static ns3::UanAddress ns3::UanAddress::Allocate() [member function]
cls.add_method('Allocate',
'ns3::UanAddress',
[],
is_static=True)
## uan-address.h (module 'uan'): static ns3::UanAddress ns3::UanAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::UanAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## uan-address.h (module 'uan'): void ns3::UanAddress::CopyFrom(uint8_t const * pBuffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'pBuffer')])
## uan-address.h (module 'uan'): void ns3::UanAddress::CopyTo(uint8_t * pBuffer) [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'pBuffer')])
## uan-address.h (module 'uan'): uint8_t ns3::UanAddress::GetAsInt() const [member function]
cls.add_method('GetAsInt',
'uint8_t',
[],
is_const=True)
## uan-address.h (module 'uan'): static ns3::UanAddress ns3::UanAddress::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::UanAddress',
[],
is_static=True)
## uan-address.h (module 'uan'): static bool ns3::UanAddress::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3UanHelper_methods(root_module, cls):
## uan-helper.h (module 'uan'): ns3::UanHelper::UanHelper(ns3::UanHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHelper const &', 'arg0')])
## uan-helper.h (module 'uan'): ns3::UanHelper::UanHelper() [constructor]
cls.add_constructor([])
## uan-helper.h (module 'uan'): int64_t ns3::UanHelper::AssignStreams(ns3::NetDeviceContainer c, int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('ns3::NetDeviceContainer', 'c'), param('int64_t', 'stream')])
## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAscii(std::ostream & os, uint32_t nodeid, uint32_t deviceid) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::ostream &', 'os'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')],
is_static=True)
## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAscii(std::ostream & os, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::ostream &', 'os'), param('ns3::NetDeviceContainer', 'd')],
is_static=True)
## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAscii(std::ostream & os, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::ostream &', 'os'), param('ns3::NodeContainer', 'n')],
is_static=True)
## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAsciiAll(std::ostream & os) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('std::ostream &', 'os')],
is_static=True)
## uan-helper.h (module 'uan'): ns3::NetDeviceContainer ns3::UanHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## uan-helper.h (module 'uan'): ns3::NetDeviceContainer ns3::UanHelper::Install(ns3::NodeContainer c, ns3::Ptr<ns3::UanChannel> channel) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer', 'c'), param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_const=True)
## uan-helper.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::UanChannel> channel) const [member function]
cls.add_method('Install',
'ns3::Ptr< ns3::UanNetDevice >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_const=True)
## uan-helper.h (module 'uan'): void ns3::UanHelper::SetMac(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function]
cls.add_method('SetMac',
'void',
[param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')])
## uan-helper.h (module 'uan'): void ns3::UanHelper::SetPhy(std::string phyType, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function]
cls.add_method('SetPhy',
'void',
[param('std::string', 'phyType'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')])
## uan-helper.h (module 'uan'): void ns3::UanHelper::SetTransducer(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function]
cls.add_method('SetTransducer',
'void',
[param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')])
return
def register_Ns3UanModesList_methods(root_module, cls):
cls.add_output_stream_operator()
## uan-tx-mode.h (module 'uan'): ns3::UanModesList::UanModesList(ns3::UanModesList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanModesList const &', 'arg0')])
## uan-tx-mode.h (module 'uan'): ns3::UanModesList::UanModesList() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): void ns3::UanModesList::AppendMode(ns3::UanTxMode mode) [member function]
cls.add_method('AppendMode',
'void',
[param('ns3::UanTxMode', 'mode')])
## uan-tx-mode.h (module 'uan'): void ns3::UanModesList::DeleteMode(uint32_t num) [member function]
cls.add_method('DeleteMode',
'void',
[param('uint32_t', 'num')])
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanModesList::GetNModes() const [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_const=True)
return
def register_Ns3UanPacketArrival_methods(root_module, cls):
## uan-transducer.h (module 'uan'): ns3::UanPacketArrival::UanPacketArrival(ns3::UanPacketArrival const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPacketArrival const &', 'arg0')])
## uan-transducer.h (module 'uan'): ns3::UanPacketArrival::UanPacketArrival() [constructor]
cls.add_constructor([])
## uan-transducer.h (module 'uan'): ns3::UanPacketArrival::UanPacketArrival(ns3::Ptr<ns3::Packet> packet, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp, ns3::Time arrTime) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp'), param('ns3::Time', 'arrTime')])
## uan-transducer.h (module 'uan'): ns3::Time ns3::UanPacketArrival::GetArrivalTime() const [member function]
cls.add_method('GetArrivalTime',
'ns3::Time',
[],
is_const=True)
## uan-transducer.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPacketArrival::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## uan-transducer.h (module 'uan'): ns3::UanPdp ns3::UanPacketArrival::GetPdp() const [member function]
cls.add_method('GetPdp',
'ns3::UanPdp',
[],
is_const=True)
## uan-transducer.h (module 'uan'): double ns3::UanPacketArrival::GetRxPowerDb() const [member function]
cls.add_method('GetRxPowerDb',
'double',
[],
is_const=True)
## uan-transducer.h (module 'uan'): ns3::UanTxMode const & ns3::UanPacketArrival::GetTxMode() const [member function]
cls.add_method('GetTxMode',
'ns3::UanTxMode const &',
[],
is_const=True)
return
def register_Ns3UanPdp_methods(root_module, cls):
cls.add_output_stream_operator()
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(ns3::UanPdp const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPdp const &', 'arg0')])
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp() [constructor]
cls.add_constructor([])
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(std::vector<ns3::Tap, std::allocator<ns3::Tap> > taps, ns3::Time resolution) [constructor]
cls.add_constructor([param('std::vector< ns3::Tap >', 'taps'), param('ns3::Time', 'resolution')])
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(std::vector<std::complex<double>,std::allocator<std::complex<double> > > arrivals, ns3::Time resolution) [constructor]
cls.add_constructor([param('std::vector< std::complex< double > >', 'arrivals'), param('ns3::Time', 'resolution')])
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(std::vector<double,std::allocator<double> > arrivals, ns3::Time resolution) [constructor]
cls.add_constructor([param('std::vector< double >', 'arrivals'), param('ns3::Time', 'resolution')])
## uan-prop-model.h (module 'uan'): static ns3::UanPdp ns3::UanPdp::CreateImpulsePdp() [member function]
cls.add_method('CreateImpulsePdp',
'ns3::UanPdp',
[],
is_static=True)
## uan-prop-model.h (module 'uan'): __gnu_cxx::__normal_iterator<const ns3::Tap*,std::vector<ns3::Tap, std::allocator<ns3::Tap> > > ns3::UanPdp::GetBegin() const [member function]
cls.add_method('GetBegin',
'__gnu_cxx::__normal_iterator< ns3::Tap const *, std::vector< ns3::Tap > >',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): __gnu_cxx::__normal_iterator<const ns3::Tap*,std::vector<ns3::Tap, std::allocator<ns3::Tap> > > ns3::UanPdp::GetEnd() const [member function]
cls.add_method('GetEnd',
'__gnu_cxx::__normal_iterator< ns3::Tap const *, std::vector< ns3::Tap > >',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): uint32_t ns3::UanPdp::GetNTaps() const [member function]
cls.add_method('GetNTaps',
'uint32_t',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): ns3::Time ns3::UanPdp::GetResolution() const [member function]
cls.add_method('GetResolution',
'ns3::Time',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): ns3::Tap const & ns3::UanPdp::GetTap(uint32_t i) const [member function]
cls.add_method('GetTap',
'ns3::Tap const &',
[param('uint32_t', 'i')],
is_const=True)
## uan-prop-model.h (module 'uan'): void ns3::UanPdp::SetNTaps(uint32_t nTaps) [member function]
cls.add_method('SetNTaps',
'void',
[param('uint32_t', 'nTaps')])
## uan-prop-model.h (module 'uan'): void ns3::UanPdp::SetResolution(ns3::Time resolution) [member function]
cls.add_method('SetResolution',
'void',
[param('ns3::Time', 'resolution')])
## uan-prop-model.h (module 'uan'): void ns3::UanPdp::SetTap(std::complex<double> arrival, uint32_t index) [member function]
cls.add_method('SetTap',
'void',
[param('std::complex< double >', 'arrival'), param('uint32_t', 'index')])
## uan-prop-model.h (module 'uan'): std::complex<double> ns3::UanPdp::SumTapsC(ns3::Time begin, ns3::Time end) const [member function]
cls.add_method('SumTapsC',
'std::complex< double >',
[param('ns3::Time', 'begin'), param('ns3::Time', 'end')],
is_const=True)
## uan-prop-model.h (module 'uan'): std::complex<double> ns3::UanPdp::SumTapsFromMaxC(ns3::Time delay, ns3::Time duration) const [member function]
cls.add_method('SumTapsFromMaxC',
'std::complex< double >',
[param('ns3::Time', 'delay'), param('ns3::Time', 'duration')],
is_const=True)
## uan-prop-model.h (module 'uan'): double ns3::UanPdp::SumTapsFromMaxNc(ns3::Time delay, ns3::Time duration) const [member function]
cls.add_method('SumTapsFromMaxNc',
'double',
[param('ns3::Time', 'delay'), param('ns3::Time', 'duration')],
is_const=True)
## uan-prop-model.h (module 'uan'): double ns3::UanPdp::SumTapsNc(ns3::Time begin, ns3::Time end) const [member function]
cls.add_method('SumTapsNc',
'double',
[param('ns3::Time', 'begin'), param('ns3::Time', 'end')],
is_const=True)
return
def register_Ns3UanPhyListener_methods(root_module, cls):
## uan-phy.h (module 'uan'): ns3::UanPhyListener::UanPhyListener() [constructor]
cls.add_constructor([])
## uan-phy.h (module 'uan'): ns3::UanPhyListener::UanPhyListener(ns3::UanPhyListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyListener const &', 'arg0')])
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyCcaEnd() [member function]
cls.add_method('NotifyCcaEnd',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyCcaStart() [member function]
cls.add_method('NotifyCcaStart',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyRxEndError() [member function]
cls.add_method('NotifyRxEndError',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyRxEndOk() [member function]
cls.add_method('NotifyRxEndOk',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyRxStart() [member function]
cls.add_method('NotifyRxStart',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyTxStart(ns3::Time duration) [member function]
cls.add_method('NotifyTxStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3UanTxMode_methods(root_module, cls):
cls.add_output_stream_operator()
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::UanTxMode(ns3::UanTxMode const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanTxMode const &', 'arg0')])
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::UanTxMode() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetBandwidthHz() const [member function]
cls.add_method('GetBandwidthHz',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetCenterFreqHz() const [member function]
cls.add_method('GetCenterFreqHz',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetConstellationSize() const [member function]
cls.add_method('GetConstellationSize',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetDataRateBps() const [member function]
cls.add_method('GetDataRateBps',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::ModulationType ns3::UanTxMode::GetModType() const [member function]
cls.add_method('GetModType',
'ns3::UanTxMode::ModulationType',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): std::string ns3::UanTxMode::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetPhyRateSps() const [member function]
cls.add_method('GetPhyRateSps',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
return
def register_Ns3UanTxModeFactory_methods(root_module, cls):
## uan-tx-mode.h (module 'uan'): ns3::UanTxModeFactory::UanTxModeFactory(ns3::UanTxModeFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanTxModeFactory const &', 'arg0')])
## uan-tx-mode.h (module 'uan'): ns3::UanTxModeFactory::UanTxModeFactory() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): static ns3::UanTxMode ns3::UanTxModeFactory::CreateMode(ns3::UanTxMode::ModulationType type, uint32_t dataRateBps, uint32_t phyRateSps, uint32_t cfHz, uint32_t bwHz, uint32_t constSize, std::string name) [member function]
cls.add_method('CreateMode',
'ns3::UanTxMode',
[param('ns3::UanTxMode::ModulationType', 'type'), param('uint32_t', 'dataRateBps'), param('uint32_t', 'phyRateSps'), param('uint32_t', 'cfHz'), param('uint32_t', 'bwHz'), param('uint32_t', 'constSize'), param('std::string', 'name')],
is_static=True)
## uan-tx-mode.h (module 'uan'): static ns3::UanTxMode ns3::UanTxModeFactory::GetMode(std::string name) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('std::string', 'name')],
is_static=True)
## uan-tx-mode.h (module 'uan'): static ns3::UanTxMode ns3::UanTxModeFactory::GetMode(uint32_t uid) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('uint32_t', 'uid')],
is_static=True)
return
def register_Ns3Vector2D_methods(root_module, cls):
cls.add_output_stream_operator()
## vector.h (module 'core'): ns3::Vector2D::Vector2D(ns3::Vector2D const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector2D const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector2D::Vector2D(double _x, double _y) [constructor]
cls.add_constructor([param('double', '_x'), param('double', '_y')])
## vector.h (module 'core'): ns3::Vector2D::Vector2D() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector2D::x [variable]
cls.add_instance_attribute('x', 'double', is_const=False)
## vector.h (module 'core'): ns3::Vector2D::y [variable]
cls.add_instance_attribute('y', 'double', is_const=False)
return
def register_Ns3Vector3D_methods(root_module, cls):
cls.add_output_stream_operator()
## vector.h (module 'core'): ns3::Vector3D::Vector3D(ns3::Vector3D const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector3D const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector3D::Vector3D(double _x, double _y, double _z) [constructor]
cls.add_constructor([param('double', '_x'), param('double', '_y'), param('double', '_z')])
## vector.h (module 'core'): ns3::Vector3D::Vector3D() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector3D::x [variable]
cls.add_instance_attribute('x', 'double', is_const=False)
## vector.h (module 'core'): ns3::Vector3D::y [variable]
cls.add_instance_attribute('y', 'double', is_const=False)
## vector.h (module 'core'): ns3::Vector3D::z [variable]
cls.add_instance_attribute('z', 'double', is_const=False)
return
def register_Ns3Empty_methods(root_module, cls):
## empty.h (module 'core'): ns3::empty::empty() [constructor]
cls.add_constructor([])
## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor]
cls.add_constructor([param('ns3::empty const &', 'arg0')])
return
def register_Ns3Int64x64_t_methods(root_module, cls):
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor]
cls.add_constructor([param('long double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor]
cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t', 'v')],
is_static=True)
## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function]
cls.add_method('MulByInvert',
'void',
[param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable]
cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True)
return
def register_Ns3AcousticModemEnergyModelHelper_methods(root_module, cls):
## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::AcousticModemEnergyModelHelper::AcousticModemEnergyModelHelper(ns3::AcousticModemEnergyModelHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AcousticModemEnergyModelHelper const &', 'arg0')])
## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::AcousticModemEnergyModelHelper::AcousticModemEnergyModelHelper() [constructor]
cls.add_constructor([])
## acoustic-modem-energy-model-helper.h (module 'uan'): void ns3::AcousticModemEnergyModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')],
is_virtual=True)
## acoustic-modem-energy-model-helper.h (module 'uan'): void ns3::AcousticModemEnergyModelHelper::SetDepletionCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetDepletionCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::AcousticModemEnergyModelHelper::DoInstall(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function]
cls.add_method('DoInstall',
'ns3::Ptr< ns3::DeviceEnergyModel >',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Chunk_methods(root_module, cls):
## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor]
cls.add_constructor([])
## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Chunk const &', 'arg0')])
## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Header_methods(root_module, cls):
cls.add_output_stream_operator()
## header.h (module 'network'): ns3::Header::Header() [constructor]
cls.add_constructor([])
## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Header const &', 'arg0')])
## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Object_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::Object() [constructor]
cls.add_constructor([])
## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function]
cls.add_method('AggregateObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'other')])
## object.h (module 'core'): void ns3::Object::Dispose() [member function]
cls.add_method('Dispose',
'void',
[])
## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function]
cls.add_method('GetAggregateIterator',
'ns3::Object::AggregateIterator',
[],
is_const=True)
## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object.h (module 'core'): void ns3::Object::Initialize() [member function]
cls.add_method('Initialize',
'void',
[])
## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor]
cls.add_constructor([param('ns3::Object const &', 'o')],
visibility='protected')
## object.h (module 'core'): void ns3::Object::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectAggregateIterator_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')])
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor]
cls.add_constructor([])
## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function]
cls.add_method('Next',
'ns3::Ptr< ns3::Object const >',
[])
return
def register_Ns3RandomVariableStream_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function]
cls.add_method('SetStream',
'void',
[param('int64_t', 'stream')])
## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function]
cls.add_method('GetStream',
'int64_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function]
cls.add_method('SetAntithetic',
'void',
[param('bool', 'isAntithetic')])
## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function]
cls.add_method('IsAntithetic',
'bool',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function]
cls.add_method('Peek',
'ns3::RngStream *',
[],
is_const=True, visibility='protected')
return
def register_Ns3SequentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function]
cls.add_method('GetIncrement',
'ns3::Ptr< ns3::RandomVariableStream >',
[],
is_const=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function]
cls.add_method('GetConsecutive',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Time_methods(root_module, cls):
cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor]
cls.add_constructor([param('ns3::Time const &', 'o')])
## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function]
cls.add_method('As',
'ns3::TimeWithUnit',
[param('ns3::Time::Unit const', 'unit')],
is_const=True)
## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function]
cls.add_method('Compare',
'int',
[param('ns3::Time const &', 'o')],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function]
cls.add_method('GetDays',
'double',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function]
cls.add_method('GetFemtoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function]
cls.add_method('GetHours',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function]
cls.add_method('GetInteger',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function]
cls.add_method('GetMicroSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function]
cls.add_method('GetMilliSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function]
cls.add_method('GetMinutes',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function]
cls.add_method('GetNanoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function]
cls.add_method('GetPicoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function]
cls.add_method('GetResolution',
'ns3::Time::Unit',
[],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function]
cls.add_method('GetSeconds',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function]
cls.add_method('GetTimeStep',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function]
cls.add_method('GetYears',
'double',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function]
cls.add_method('IsNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function]
cls.add_method('IsPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function]
cls.add_method('IsStrictlyNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function]
cls.add_method('IsStrictlyPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function]
cls.add_method('IsZero',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function]
cls.add_method('Max',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function]
cls.add_method('Min',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function]
cls.add_method('SetResolution',
'void',
[param('ns3::Time::Unit', 'resolution')],
is_static=True)
## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function]
cls.add_method('StaticInit',
'bool',
[],
is_static=True)
## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'unit')],
is_const=True)
return
def register_Ns3TraceSourceAccessor_methods(root_module, cls):
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor]
cls.add_constructor([])
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Connect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('ConnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Disconnect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('DisconnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Trailer_methods(root_module, cls):
cls.add_output_stream_operator()
## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor]
cls.add_constructor([])
## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Trailer const &', 'arg0')])
## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'end')],
is_pure_virtual=True, is_virtual=True)
## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TriangularRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3UanHeaderCommon_methods(root_module, cls):
## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon::UanHeaderCommon(ns3::UanHeaderCommon const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderCommon const &', 'arg0')])
## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon::UanHeaderCommon() [constructor]
cls.add_constructor([])
## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon::UanHeaderCommon(ns3::UanAddress const src, ns3::UanAddress const dest, uint8_t type) [constructor]
cls.add_constructor([param('ns3::UanAddress const', 'src'), param('ns3::UanAddress const', 'dest'), param('uint8_t', 'type')])
## uan-header-common.h (module 'uan'): uint32_t ns3::UanHeaderCommon::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-common.h (module 'uan'): ns3::UanAddress ns3::UanHeaderCommon::GetDest() const [member function]
cls.add_method('GetDest',
'ns3::UanAddress',
[],
is_const=True)
## uan-header-common.h (module 'uan'): ns3::TypeId ns3::UanHeaderCommon::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-common.h (module 'uan'): uint32_t ns3::UanHeaderCommon::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-common.h (module 'uan'): ns3::UanAddress ns3::UanHeaderCommon::GetSrc() const [member function]
cls.add_method('GetSrc',
'ns3::UanAddress',
[],
is_const=True)
## uan-header-common.h (module 'uan'): uint8_t ns3::UanHeaderCommon::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## uan-header-common.h (module 'uan'): static ns3::TypeId ns3::UanHeaderCommon::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::SetDest(ns3::UanAddress dest) [member function]
cls.add_method('SetDest',
'void',
[param('ns3::UanAddress', 'dest')])
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::SetSrc(ns3::UanAddress src) [member function]
cls.add_method('SetSrc',
'void',
[param('ns3::UanAddress', 'src')])
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
return
def register_Ns3UanHeaderRcAck_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcAck::UanHeaderRcAck(ns3::UanHeaderRcAck const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcAck const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcAck::UanHeaderRcAck() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::AddNackedFrame(uint8_t frame) [member function]
cls.add_method('AddNackedFrame',
'void',
[param('uint8_t', 'frame')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcAck::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcAck::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcAck::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): std::set<unsigned char, std::less<unsigned char>, std::allocator<unsigned char> > const & ns3::UanHeaderRcAck::GetNackedFrames() const [member function]
cls.add_method('GetNackedFrames',
'std::set< unsigned char > const &',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcAck::GetNoNacks() const [member function]
cls.add_method('GetNoNacks',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcAck::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcAck::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::SetFrameNo(uint8_t frameNo) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'frameNo')])
return
def register_Ns3UanHeaderRcCts_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts::UanHeaderRcCts(ns3::UanHeaderRcCts const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcCts const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts::UanHeaderRcCts() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts::UanHeaderRcCts(uint8_t frameNo, uint8_t retryNo, ns3::Time rtsTs, ns3::Time delay, ns3::UanAddress addr) [constructor]
cls.add_constructor([param('uint8_t', 'frameNo'), param('uint8_t', 'retryNo'), param('ns3::Time', 'rtsTs'), param('ns3::Time', 'delay'), param('ns3::UanAddress', 'addr')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCts::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::UanAddress ns3::UanHeaderRcCts::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::UanAddress',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCts::GetDelayToTx() const [member function]
cls.add_method('GetDelayToTx',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcCts::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcCts::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcCts::GetRetryNo() const [member function]
cls.add_method('GetRetryNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCts::GetRtsTimeStamp() const [member function]
cls.add_method('GetRtsTimeStamp',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCts::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcCts::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetDelayToTx(ns3::Time delay) [member function]
cls.add_method('SetDelayToTx',
'void',
[param('ns3::Time', 'delay')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetFrameNo(uint8_t frameNo) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'frameNo')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetRetryNo(uint8_t no) [member function]
cls.add_method('SetRetryNo',
'void',
[param('uint8_t', 'no')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetRtsTimeStamp(ns3::Time timeStamp) [member function]
cls.add_method('SetRtsTimeStamp',
'void',
[param('ns3::Time', 'timeStamp')])
return
def register_Ns3UanHeaderRcCtsGlobal_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal(ns3::UanHeaderRcCtsGlobal const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcCtsGlobal const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal(ns3::Time wt, ns3::Time ts, uint16_t rate, uint16_t retryRate) [constructor]
cls.add_constructor([param('ns3::Time', 'wt'), param('ns3::Time', 'ts'), param('uint16_t', 'rate'), param('uint16_t', 'retryRate')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCtsGlobal::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcCtsGlobal::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): uint16_t ns3::UanHeaderRcCtsGlobal::GetRateNum() const [member function]
cls.add_method('GetRateNum',
'uint16_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint16_t ns3::UanHeaderRcCtsGlobal::GetRetryRate() const [member function]
cls.add_method('GetRetryRate',
'uint16_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCtsGlobal::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCtsGlobal::GetTxTimeStamp() const [member function]
cls.add_method('GetTxTimeStamp',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcCtsGlobal::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCtsGlobal::GetWindowTime() const [member function]
cls.add_method('GetWindowTime',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetRateNum(uint16_t rate) [member function]
cls.add_method('SetRateNum',
'void',
[param('uint16_t', 'rate')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetRetryRate(uint16_t rate) [member function]
cls.add_method('SetRetryRate',
'void',
[param('uint16_t', 'rate')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetTxTimeStamp(ns3::Time timeStamp) [member function]
cls.add_method('SetTxTimeStamp',
'void',
[param('ns3::Time', 'timeStamp')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetWindowTime(ns3::Time t) [member function]
cls.add_method('SetWindowTime',
'void',
[param('ns3::Time', 't')])
return
def register_Ns3UanHeaderRcData_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData::UanHeaderRcData(ns3::UanHeaderRcData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcData const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData::UanHeaderRcData() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData::UanHeaderRcData(uint8_t frameNum, ns3::Time propDelay) [constructor]
cls.add_constructor([param('uint8_t', 'frameNum'), param('ns3::Time', 'propDelay')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcData::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcData::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcData::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcData::GetPropDelay() const [member function]
cls.add_method('GetPropDelay',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcData::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcData::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::SetFrameNo(uint8_t frameNum) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'frameNum')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::SetPropDelay(ns3::Time propDelay) [member function]
cls.add_method('SetPropDelay',
'void',
[param('ns3::Time', 'propDelay')])
return
def register_Ns3UanHeaderRcRts_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts::UanHeaderRcRts(ns3::UanHeaderRcRts const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcRts const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts::UanHeaderRcRts() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts::UanHeaderRcRts(uint8_t frameNo, uint8_t retryNo, uint8_t noFrames, uint16_t length, ns3::Time ts) [constructor]
cls.add_constructor([param('uint8_t', 'frameNo'), param('uint8_t', 'retryNo'), param('uint8_t', 'noFrames'), param('uint16_t', 'length'), param('ns3::Time', 'ts')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcRts::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcRts::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcRts::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): uint16_t ns3::UanHeaderRcRts::GetLength() const [member function]
cls.add_method('GetLength',
'uint16_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcRts::GetNoFrames() const [member function]
cls.add_method('GetNoFrames',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcRts::GetRetryNo() const [member function]
cls.add_method('GetRetryNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcRts::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcRts::GetTimeStamp() const [member function]
cls.add_method('GetTimeStamp',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcRts::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetFrameNo(uint8_t fno) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'fno')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetLength(uint16_t length) [member function]
cls.add_method('SetLength',
'void',
[param('uint16_t', 'length')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetNoFrames(uint8_t no) [member function]
cls.add_method('SetNoFrames',
'void',
[param('uint8_t', 'no')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetRetryNo(uint8_t no) [member function]
cls.add_method('SetRetryNo',
'void',
[param('uint8_t', 'no')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetTimeStamp(ns3::Time timeStamp) [member function]
cls.add_method('SetTimeStamp',
'void',
[param('ns3::Time', 'timeStamp')])
return
def register_Ns3UanMac_methods(root_module, cls):
## uan-mac.h (module 'uan'): ns3::UanMac::UanMac() [constructor]
cls.add_constructor([])
## uan-mac.h (module 'uan'): ns3::UanMac::UanMac(ns3::UanMac const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMac const &', 'arg0')])
## uan-mac.h (module 'uan'): int64_t ns3::UanMac::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): void ns3::UanMac::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): void ns3::UanMac::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): bool ns3::UanMac::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): ns3::Address ns3::UanMac::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): ns3::Address ns3::UanMac::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-mac.h (module 'uan'): static ns3::TypeId ns3::UanMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac.h (module 'uan'): void ns3::UanMac::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): void ns3::UanMac::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3UanMacAloha_methods(root_module, cls):
## uan-mac-aloha.h (module 'uan'): ns3::UanMacAloha::UanMacAloha(ns3::UanMacAloha const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMacAloha const &', 'arg0')])
## uan-mac-aloha.h (module 'uan'): ns3::UanMacAloha::UanMacAloha() [constructor]
cls.add_constructor([])
## uan-mac-aloha.h (module 'uan'): int64_t ns3::UanMacAloha::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): bool ns3::UanMacAloha::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): ns3::Address ns3::UanMacAloha::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): ns3::Address ns3::UanMacAloha::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-mac-aloha.h (module 'uan'): static ns3::TypeId ns3::UanMacAloha::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanMacCw_methods(root_module, cls):
## uan-mac-cw.h (module 'uan'): ns3::UanMacCw::UanMacCw(ns3::UanMacCw const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMacCw const &', 'arg0')])
## uan-mac-cw.h (module 'uan'): ns3::UanMacCw::UanMacCw() [constructor]
cls.add_constructor([])
## uan-mac-cw.h (module 'uan'): int64_t ns3::UanMacCw::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): bool ns3::UanMacCw::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): ns3::Address ns3::UanMacCw::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): ns3::Address ns3::UanMacCw::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-mac-cw.h (module 'uan'): uint32_t ns3::UanMacCw::GetCw() [member function]
cls.add_method('GetCw',
'uint32_t',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): ns3::Time ns3::UanMacCw::GetSlotTime() [member function]
cls.add_method('GetSlotTime',
'ns3::Time',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): static ns3::TypeId ns3::UanMacCw::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyCcaEnd() [member function]
cls.add_method('NotifyCcaEnd',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyCcaStart() [member function]
cls.add_method('NotifyCcaStart',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyRxEndError() [member function]
cls.add_method('NotifyRxEndError',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyRxEndOk() [member function]
cls.add_method('NotifyRxEndOk',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyRxStart() [member function]
cls.add_method('NotifyRxStart',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyTxStart(ns3::Time duration) [member function]
cls.add_method('NotifyTxStart',
'void',
[param('ns3::Time', 'duration')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetCw(uint32_t cw) [member function]
cls.add_method('SetCw',
'void',
[param('uint32_t', 'cw')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetSlotTime(ns3::Time duration) [member function]
cls.add_method('SetSlotTime',
'void',
[param('ns3::Time', 'duration')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanMacRc_methods(root_module, cls):
## uan-mac-rc.h (module 'uan'): ns3::UanMacRc::UanMacRc(ns3::UanMacRc const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMacRc const &', 'arg0')])
## uan-mac-rc.h (module 'uan'): ns3::UanMacRc::UanMacRc() [constructor]
cls.add_constructor([])
## uan-mac-rc.h (module 'uan'): int64_t ns3::UanMacRc::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): bool ns3::UanMacRc::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): ns3::Address ns3::UanMacRc::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): ns3::Address ns3::UanMacRc::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-mac-rc.h (module 'uan'): static ns3::TypeId ns3::UanMacRc::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanMacRcGw_methods(root_module, cls):
## uan-mac-rc-gw.h (module 'uan'): ns3::UanMacRcGw::UanMacRcGw(ns3::UanMacRcGw const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMacRcGw const &', 'arg0')])
## uan-mac-rc-gw.h (module 'uan'): ns3::UanMacRcGw::UanMacRcGw() [constructor]
cls.add_constructor([])
## uan-mac-rc-gw.h (module 'uan'): int64_t ns3::UanMacRcGw::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): bool ns3::UanMacRcGw::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): ns3::Address ns3::UanMacRcGw::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): ns3::Address ns3::UanMacRcGw::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): static ns3::TypeId ns3::UanMacRcGw::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanNoiseModel_methods(root_module, cls):
## uan-noise-model.h (module 'uan'): ns3::UanNoiseModel::UanNoiseModel() [constructor]
cls.add_constructor([])
## uan-noise-model.h (module 'uan'): ns3::UanNoiseModel::UanNoiseModel(ns3::UanNoiseModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanNoiseModel const &', 'arg0')])
## uan-noise-model.h (module 'uan'): void ns3::UanNoiseModel::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-noise-model.h (module 'uan'): void ns3::UanNoiseModel::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## uan-noise-model.h (module 'uan'): double ns3::UanNoiseModel::GetNoiseDbHz(double fKhz) const [member function]
cls.add_method('GetNoiseDbHz',
'double',
[param('double', 'fKhz')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-noise-model.h (module 'uan'): static ns3::TypeId ns3::UanNoiseModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanNoiseModelDefault_methods(root_module, cls):
## uan-noise-model-default.h (module 'uan'): ns3::UanNoiseModelDefault::UanNoiseModelDefault(ns3::UanNoiseModelDefault const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanNoiseModelDefault const &', 'arg0')])
## uan-noise-model-default.h (module 'uan'): ns3::UanNoiseModelDefault::UanNoiseModelDefault() [constructor]
cls.add_constructor([])
## uan-noise-model-default.h (module 'uan'): double ns3::UanNoiseModelDefault::GetNoiseDbHz(double fKhz) const [member function]
cls.add_method('GetNoiseDbHz',
'double',
[param('double', 'fKhz')],
is_const=True, is_virtual=True)
## uan-noise-model-default.h (module 'uan'): static ns3::TypeId ns3::UanNoiseModelDefault::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhy_methods(root_module, cls):
## uan-phy.h (module 'uan'): ns3::UanPhy::UanPhy() [constructor]
cls.add_constructor([])
## uan-phy.h (module 'uan'): ns3::UanPhy::UanPhy(ns3::UanPhy const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhy const &', 'arg0')])
## uan-phy.h (module 'uan'): int64_t ns3::UanPhy::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::EnergyDepletionHandler() [member function]
cls.add_method('EnergyDepletionHandler',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::EnergyRechargeHandler() [member function]
cls.add_method('EnergyRechargeHandler',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhy::GetCcaThresholdDb() [member function]
cls.add_method('GetCcaThresholdDb',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanPhy::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanPhy::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::UanNetDevice >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::UanTxMode ns3::UanPhy::GetMode(uint32_t n) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('uint32_t', 'n')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): uint32_t ns3::UanPhy::GetNModes() [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhy::GetPacketRx() const [member function]
cls.add_method('GetPacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhy::GetRxGainDb() [member function]
cls.add_method('GetRxGainDb',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhy::GetRxThresholdDb() [member function]
cls.add_method('GetRxThresholdDb',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanPhy::GetTransducer() [member function]
cls.add_method('GetTransducer',
'ns3::Ptr< ns3::UanTransducer >',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhy::GetTxPowerDb() [member function]
cls.add_method('GetTxPowerDb',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): static ns3::TypeId ns3::UanPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateSleep() [member function]
cls.add_method('IsStateSleep',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyIntChange() [member function]
cls.add_method('NotifyIntChange',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyRxBegin(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('NotifyRxBegin',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyRxDrop(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('NotifyRxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyRxEnd(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('NotifyRxEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyTransStartTx(ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('NotifyTransStartTx',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyTxBegin(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('NotifyTxBegin',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyTxDrop(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('NotifyTxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyTxEnd(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('NotifyTxEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## uan-phy.h (module 'uan'): void ns3::UanPhy::RegisterListener(ns3::UanPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::UanPhyListener *', 'listener')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SendPacket(ns3::Ptr<ns3::Packet> pkt, uint32_t modeNum) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('uint32_t', 'modeNum')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetCcaThresholdDb(double thresh) [member function]
cls.add_method('SetCcaThresholdDb',
'void',
[param('double', 'thresh')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetDevice(ns3::Ptr<ns3::UanNetDevice> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::UanNetDevice >', 'device')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetEnergyModelCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetEnergyModelCallback',
'void',
[param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::UanMac >', 'mac')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetReceiveErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetReceiveOkCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetRxGainDb(double gain) [member function]
cls.add_method('SetRxGainDb',
'void',
[param('double', 'gain')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetRxThresholdDb(double thresh) [member function]
cls.add_method('SetRxThresholdDb',
'void',
[param('double', 'thresh')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetSleepMode(bool sleep) [member function]
cls.add_method('SetSleepMode',
'void',
[param('bool', 'sleep')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('SetTransducer',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'trans')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetTxPowerDb(double txpwr) [member function]
cls.add_method('SetTxPowerDb',
'void',
[param('double', 'txpwr')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::StartRxPacket(ns3::Ptr<ns3::Packet> pkt, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('StartRxPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3UanPhyCalcSinr_methods(root_module, cls):
## uan-phy.h (module 'uan'): ns3::UanPhyCalcSinr::UanPhyCalcSinr() [constructor]
cls.add_constructor([])
## uan-phy.h (module 'uan'): ns3::UanPhyCalcSinr::UanPhyCalcSinr(ns3::UanPhyCalcSinr const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyCalcSinr const &', 'arg0')])
## uan-phy.h (module 'uan'): double ns3::UanPhyCalcSinr::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function]
cls.add_method('CalcSinrDb',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyCalcSinr::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhyCalcSinr::DbToKp(double db) const [member function]
cls.add_method('DbToKp',
'double',
[param('double', 'db')],
is_const=True)
## uan-phy.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinr::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-phy.h (module 'uan'): double ns3::UanPhyCalcSinr::KpToDb(double kp) const [member function]
cls.add_method('KpToDb',
'double',
[param('double', 'kp')],
is_const=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyCalcSinr::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanPhyCalcSinrDefault_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrDefault::UanPhyCalcSinrDefault(ns3::UanPhyCalcSinrDefault const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyCalcSinrDefault const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrDefault::UanPhyCalcSinrDefault() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyCalcSinrDefault::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function]
cls.add_method('CalcSinrDb',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')],
is_const=True, is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinrDefault::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhyCalcSinrDual_methods(root_module, cls):
## uan-phy-dual.h (module 'uan'): ns3::UanPhyCalcSinrDual::UanPhyCalcSinrDual(ns3::UanPhyCalcSinrDual const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyCalcSinrDual const &', 'arg0')])
## uan-phy-dual.h (module 'uan'): ns3::UanPhyCalcSinrDual::UanPhyCalcSinrDual() [constructor]
cls.add_constructor([])
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyCalcSinrDual::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function]
cls.add_method('CalcSinrDb',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')],
is_const=True, is_virtual=True)
## uan-phy-dual.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinrDual::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhyCalcSinrFhFsk_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrFhFsk::UanPhyCalcSinrFhFsk(ns3::UanPhyCalcSinrFhFsk const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyCalcSinrFhFsk const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrFhFsk::UanPhyCalcSinrFhFsk() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyCalcSinrFhFsk::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function]
cls.add_method('CalcSinrDb',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')],
is_const=True, is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinrFhFsk::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhyDual_methods(root_module, cls):
## uan-phy-dual.h (module 'uan'): ns3::UanPhyDual::UanPhyDual(ns3::UanPhyDual const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyDual const &', 'arg0')])
## uan-phy-dual.h (module 'uan'): ns3::UanPhyDual::UanPhyDual() [constructor]
cls.add_constructor([])
## uan-phy-dual.h (module 'uan'): int64_t ns3::UanPhyDual::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::EnergyDepletionHandler() [member function]
cls.add_method('EnergyDepletionHandler',
'void',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::EnergyRechargeHandler() [member function]
cls.add_method('EnergyRechargeHandler',
'void',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetCcaThresholdDb() [member function]
cls.add_method('GetCcaThresholdDb',
'double',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetCcaThresholdPhy1() const [member function]
cls.add_method('GetCcaThresholdPhy1',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetCcaThresholdPhy2() const [member function]
cls.add_method('GetCcaThresholdPhy2',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanPhyDual::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_const=True, is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanPhyDual::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::UanNetDevice >',
[],
is_const=True, is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::UanTxMode ns3::UanPhyDual::GetMode(uint32_t n) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('uint32_t', 'n')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::UanModesList ns3::UanPhyDual::GetModesPhy1() const [member function]
cls.add_method('GetModesPhy1',
'ns3::UanModesList',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::UanModesList ns3::UanPhyDual::GetModesPhy2() const [member function]
cls.add_method('GetModesPhy2',
'ns3::UanModesList',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): uint32_t ns3::UanPhyDual::GetNModes() [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyDual::GetPacketRx() const [member function]
cls.add_method('GetPacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True, is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyPer> ns3::UanPhyDual::GetPerModelPhy1() const [member function]
cls.add_method('GetPerModelPhy1',
'ns3::Ptr< ns3::UanPhyPer >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyPer> ns3::UanPhyDual::GetPerModelPhy2() const [member function]
cls.add_method('GetPerModelPhy2',
'ns3::Ptr< ns3::UanPhyPer >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyDual::GetPhy1PacketRx() const [member function]
cls.add_method('GetPhy1PacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyDual::GetPhy2PacketRx() const [member function]
cls.add_method('GetPhy2PacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxGainDb() [member function]
cls.add_method('GetRxGainDb',
'double',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxGainDbPhy1() const [member function]
cls.add_method('GetRxGainDbPhy1',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxGainDbPhy2() const [member function]
cls.add_method('GetRxGainDbPhy2',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxThresholdDb() [member function]
cls.add_method('GetRxThresholdDb',
'double',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyCalcSinr> ns3::UanPhyDual::GetSinrModelPhy1() const [member function]
cls.add_method('GetSinrModelPhy1',
'ns3::Ptr< ns3::UanPhyCalcSinr >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyCalcSinr> ns3::UanPhyDual::GetSinrModelPhy2() const [member function]
cls.add_method('GetSinrModelPhy2',
'ns3::Ptr< ns3::UanPhyCalcSinr >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanPhyDual::GetTransducer() [member function]
cls.add_method('GetTransducer',
'ns3::Ptr< ns3::UanTransducer >',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetTxPowerDb() [member function]
cls.add_method('GetTxPowerDb',
'double',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetTxPowerDbPhy1() const [member function]
cls.add_method('GetTxPowerDbPhy1',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetTxPowerDbPhy2() const [member function]
cls.add_method('GetTxPowerDbPhy2',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): static ns3::TypeId ns3::UanPhyDual::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy1Idle() [member function]
cls.add_method('IsPhy1Idle',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy1Rx() [member function]
cls.add_method('IsPhy1Rx',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy1Tx() [member function]
cls.add_method('IsPhy1Tx',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy2Idle() [member function]
cls.add_method('IsPhy2Idle',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy2Rx() [member function]
cls.add_method('IsPhy2Rx',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy2Tx() [member function]
cls.add_method('IsPhy2Tx',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateSleep() [member function]
cls.add_method('IsStateSleep',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::NotifyIntChange() [member function]
cls.add_method('NotifyIntChange',
'void',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::NotifyTransStartTx(ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('NotifyTransStartTx',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::RegisterListener(ns3::UanPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::UanPhyListener *', 'listener')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SendPacket(ns3::Ptr<ns3::Packet> pkt, uint32_t modeNum) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('uint32_t', 'modeNum')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetCcaThresholdDb(double thresh) [member function]
cls.add_method('SetCcaThresholdDb',
'void',
[param('double', 'thresh')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetCcaThresholdPhy1(double thresh) [member function]
cls.add_method('SetCcaThresholdPhy1',
'void',
[param('double', 'thresh')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetCcaThresholdPhy2(double thresh) [member function]
cls.add_method('SetCcaThresholdPhy2',
'void',
[param('double', 'thresh')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetDevice(ns3::Ptr<ns3::UanNetDevice> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::UanNetDevice >', 'device')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetEnergyModelCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetEnergyModelCallback',
'void',
[param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::UanMac >', 'mac')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetModesPhy1(ns3::UanModesList modes) [member function]
cls.add_method('SetModesPhy1',
'void',
[param('ns3::UanModesList', 'modes')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetModesPhy2(ns3::UanModesList modes) [member function]
cls.add_method('SetModesPhy2',
'void',
[param('ns3::UanModesList', 'modes')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetPerModelPhy1(ns3::Ptr<ns3::UanPhyPer> per) [member function]
cls.add_method('SetPerModelPhy1',
'void',
[param('ns3::Ptr< ns3::UanPhyPer >', 'per')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetPerModelPhy2(ns3::Ptr<ns3::UanPhyPer> per) [member function]
cls.add_method('SetPerModelPhy2',
'void',
[param('ns3::Ptr< ns3::UanPhyPer >', 'per')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetReceiveErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetReceiveOkCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxGainDb(double gain) [member function]
cls.add_method('SetRxGainDb',
'void',
[param('double', 'gain')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxGainDbPhy1(double gain) [member function]
cls.add_method('SetRxGainDbPhy1',
'void',
[param('double', 'gain')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxGainDbPhy2(double gain) [member function]
cls.add_method('SetRxGainDbPhy2',
'void',
[param('double', 'gain')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxThresholdDb(double thresh) [member function]
cls.add_method('SetRxThresholdDb',
'void',
[param('double', 'thresh')],
deprecated=True, is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetSinrModelPhy1(ns3::Ptr<ns3::UanPhyCalcSinr> calcSinr) [member function]
cls.add_method('SetSinrModelPhy1',
'void',
[param('ns3::Ptr< ns3::UanPhyCalcSinr >', 'calcSinr')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetSinrModelPhy2(ns3::Ptr<ns3::UanPhyCalcSinr> calcSinr) [member function]
cls.add_method('SetSinrModelPhy2',
'void',
[param('ns3::Ptr< ns3::UanPhyCalcSinr >', 'calcSinr')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetSleepMode(bool sleep) [member function]
cls.add_method('SetSleepMode',
'void',
[param('bool', 'sleep')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('SetTransducer',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'trans')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTxPowerDb(double txpwr) [member function]
cls.add_method('SetTxPowerDb',
'void',
[param('double', 'txpwr')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTxPowerDbPhy1(double txpwr) [member function]
cls.add_method('SetTxPowerDbPhy1',
'void',
[param('double', 'txpwr')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTxPowerDbPhy2(double txpwr) [member function]
cls.add_method('SetTxPowerDbPhy2',
'void',
[param('double', 'txpwr')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::StartRxPacket(ns3::Ptr<ns3::Packet> pkt, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('StartRxPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanPhyGen_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyGen::UanPhyGen(ns3::UanPhyGen const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyGen const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyGen::UanPhyGen() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): int64_t ns3::UanPhyGen::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::EnergyDepletionHandler() [member function]
cls.add_method('EnergyDepletionHandler',
'void',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::EnergyRechargeHandler() [member function]
cls.add_method('EnergyRechargeHandler',
'void',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetCcaThresholdDb() [member function]
cls.add_method('GetCcaThresholdDb',
'double',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanPhyGen::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_const=True, is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::UanModesList ns3::UanPhyGen::GetDefaultModes() [member function]
cls.add_method('GetDefaultModes',
'ns3::UanModesList',
[],
is_static=True)
## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanPhyGen::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::UanNetDevice >',
[],
is_const=True, is_virtual=True)
## uan-phy-gen.h (module 'uan'): ns3::UanTxMode ns3::UanPhyGen::GetMode(uint32_t n) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('uint32_t', 'n')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): uint32_t ns3::UanPhyGen::GetNModes() [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyGen::GetPacketRx() const [member function]
cls.add_method('GetPacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True, is_virtual=True)
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetRxGainDb() [member function]
cls.add_method('GetRxGainDb',
'double',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetRxThresholdDb() [member function]
cls.add_method('GetRxThresholdDb',
'double',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanPhyGen::GetTransducer() [member function]
cls.add_method('GetTransducer',
'ns3::Ptr< ns3::UanTransducer >',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetTxPowerDb() [member function]
cls.add_method('GetTxPowerDb',
'double',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyGen::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateSleep() [member function]
cls.add_method('IsStateSleep',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::NotifyIntChange() [member function]
cls.add_method('NotifyIntChange',
'void',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::NotifyTransStartTx(ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('NotifyTransStartTx',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::RegisterListener(ns3::UanPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::UanPhyListener *', 'listener')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SendPacket(ns3::Ptr<ns3::Packet> pkt, uint32_t modeNum) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('uint32_t', 'modeNum')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetCcaThresholdDb(double thresh) [member function]
cls.add_method('SetCcaThresholdDb',
'void',
[param('double', 'thresh')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetDevice(ns3::Ptr<ns3::UanNetDevice> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::UanNetDevice >', 'device')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetEnergyModelCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetEnergyModelCallback',
'void',
[param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::UanMac >', 'mac')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetReceiveErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetReceiveOkCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetRxGainDb(double gain) [member function]
cls.add_method('SetRxGainDb',
'void',
[param('double', 'gain')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetRxThresholdDb(double thresh) [member function]
cls.add_method('SetRxThresholdDb',
'void',
[param('double', 'thresh')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetSleepMode(bool sleep) [member function]
cls.add_method('SetSleepMode',
'void',
[param('bool', 'sleep')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('SetTransducer',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'trans')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetTxPowerDb(double txpwr) [member function]
cls.add_method('SetTxPowerDb',
'void',
[param('double', 'txpwr')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::StartRxPacket(ns3::Ptr<ns3::Packet> pkt, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('StartRxPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanPhyPer_methods(root_module, cls):
## uan-phy.h (module 'uan'): ns3::UanPhyPer::UanPhyPer() [constructor]
cls.add_constructor([])
## uan-phy.h (module 'uan'): ns3::UanPhyPer::UanPhyPer(ns3::UanPhyPer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyPer const &', 'arg0')])
## uan-phy.h (module 'uan'): double ns3::UanPhyPer::CalcPer(ns3::Ptr<ns3::Packet> pkt, double sinrDb, ns3::UanTxMode mode) [member function]
cls.add_method('CalcPer',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyPer::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-phy.h (module 'uan'): static ns3::TypeId ns3::UanPhyPer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyPer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanPhyPerGenDefault_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerGenDefault::UanPhyPerGenDefault(ns3::UanPhyPerGenDefault const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyPerGenDefault const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerGenDefault::UanPhyPerGenDefault() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyPerGenDefault::CalcPer(ns3::Ptr<ns3::Packet> pkt, double sinrDb, ns3::UanTxMode mode) [member function]
cls.add_method('CalcPer',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyPerGenDefault::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhyPerUmodem_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerUmodem::UanPhyPerUmodem(ns3::UanPhyPerUmodem const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyPerUmodem const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerUmodem::UanPhyPerUmodem() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyPerUmodem::CalcPer(ns3::Ptr<ns3::Packet> pkt, double sinrDb, ns3::UanTxMode mode) [member function]
cls.add_method('CalcPer',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyPerUmodem::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPropModel_methods(root_module, cls):
## uan-prop-model.h (module 'uan'): ns3::UanPropModel::UanPropModel() [constructor]
cls.add_constructor([])
## uan-prop-model.h (module 'uan'): ns3::UanPropModel::UanPropModel(ns3::UanPropModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPropModel const &', 'arg0')])
## uan-prop-model.h (module 'uan'): void ns3::UanPropModel::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-prop-model.h (module 'uan'): void ns3::UanPropModel::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## uan-prop-model.h (module 'uan'): ns3::Time ns3::UanPropModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_pure_virtual=True, is_virtual=True)
## uan-prop-model.h (module 'uan'): double ns3::UanPropModel::GetPathLossDb(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode txMode) [member function]
cls.add_method('GetPathLossDb',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
## uan-prop-model.h (module 'uan'): ns3::UanPdp ns3::UanPropModel::GetPdp(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPdp',
'ns3::UanPdp',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_pure_virtual=True, is_virtual=True)
## uan-prop-model.h (module 'uan'): static ns3::TypeId ns3::UanPropModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPropModelIdeal_methods(root_module, cls):
## uan-prop-model-ideal.h (module 'uan'): ns3::UanPropModelIdeal::UanPropModelIdeal(ns3::UanPropModelIdeal const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPropModelIdeal const &', 'arg0')])
## uan-prop-model-ideal.h (module 'uan'): ns3::UanPropModelIdeal::UanPropModelIdeal() [constructor]
cls.add_constructor([])
## uan-prop-model-ideal.h (module 'uan'): ns3::Time ns3::UanPropModelIdeal::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-ideal.h (module 'uan'): double ns3::UanPropModelIdeal::GetPathLossDb(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPathLossDb',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-ideal.h (module 'uan'): ns3::UanPdp ns3::UanPropModelIdeal::GetPdp(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPdp',
'ns3::UanPdp',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-ideal.h (module 'uan'): static ns3::TypeId ns3::UanPropModelIdeal::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPropModelThorp_methods(root_module, cls):
## uan-prop-model-thorp.h (module 'uan'): ns3::UanPropModelThorp::UanPropModelThorp(ns3::UanPropModelThorp const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPropModelThorp const &', 'arg0')])
## uan-prop-model-thorp.h (module 'uan'): ns3::UanPropModelThorp::UanPropModelThorp() [constructor]
cls.add_constructor([])
## uan-prop-model-thorp.h (module 'uan'): ns3::Time ns3::UanPropModelThorp::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-thorp.h (module 'uan'): double ns3::UanPropModelThorp::GetPathLossDb(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPathLossDb',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-thorp.h (module 'uan'): ns3::UanPdp ns3::UanPropModelThorp::GetPdp(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPdp',
'ns3::UanPdp',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-thorp.h (module 'uan'): static ns3::TypeId ns3::UanPropModelThorp::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanTransducer_methods(root_module, cls):
## uan-transducer.h (module 'uan'): ns3::UanTransducer::UanTransducer() [constructor]
cls.add_constructor([])
## uan-transducer.h (module 'uan'): ns3::UanTransducer::UanTransducer(ns3::UanTransducer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanTransducer const &', 'arg0')])
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::AddPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AddPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_pure_virtual=True, is_virtual=True)
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-transducer.h (module 'uan'): std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & ns3::UanTransducer::GetArrivalList() const [member function]
cls.add_method('GetArrivalList',
'std::list< ns3::UanPacketArrival > const &',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanTransducer::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): std::list<ns3::Ptr<ns3::UanPhy>, std::allocator<ns3::Ptr<ns3::UanPhy> > > const & ns3::UanTransducer::GetPhyList() const [member function]
cls.add_method('GetPhyList',
'std::list< ns3::Ptr< ns3::UanPhy > > const &',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): ns3::UanTransducer::State ns3::UanTransducer::GetState() const [member function]
cls.add_method('GetState',
'ns3::UanTransducer::State',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): static ns3::TypeId ns3::UanTransducer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-transducer.h (module 'uan'): bool ns3::UanTransducer::IsRx() const [member function]
cls.add_method('IsRx',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): bool ns3::UanTransducer::IsTx() const [member function]
cls.add_method('IsTx',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::Receive(ns3::Ptr<ns3::Packet> packet, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_pure_virtual=True, is_virtual=True)
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::SetChannel(ns3::Ptr<ns3::UanChannel> chan) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'chan')],
is_pure_virtual=True, is_virtual=True)
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::Transmit(ns3::Ptr<ns3::UanPhy> src, ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('Transmit',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3UanTransducerHd_methods(root_module, cls):
## uan-transducer-hd.h (module 'uan'): ns3::UanTransducerHd::UanTransducerHd(ns3::UanTransducerHd const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanTransducerHd const &', 'arg0')])
## uan-transducer-hd.h (module 'uan'): ns3::UanTransducerHd::UanTransducerHd() [constructor]
cls.add_constructor([])
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::AddPhy(ns3::Ptr<ns3::UanPhy> arg0) [member function]
cls.add_method('AddPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'arg0')],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & ns3::UanTransducerHd::GetArrivalList() const [member function]
cls.add_method('GetArrivalList',
'std::list< ns3::UanPacketArrival > const &',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanTransducerHd::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): std::list<ns3::Ptr<ns3::UanPhy>, std::allocator<ns3::Ptr<ns3::UanPhy> > > const & ns3::UanTransducerHd::GetPhyList() const [member function]
cls.add_method('GetPhyList',
'std::list< ns3::Ptr< ns3::UanPhy > > const &',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): ns3::UanTransducer::State ns3::UanTransducerHd::GetState() const [member function]
cls.add_method('GetState',
'ns3::UanTransducer::State',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): static ns3::TypeId ns3::UanTransducerHd::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-transducer-hd.h (module 'uan'): bool ns3::UanTransducerHd::IsRx() const [member function]
cls.add_method('IsRx',
'bool',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): bool ns3::UanTransducerHd::IsTx() const [member function]
cls.add_method('IsTx',
'bool',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::Receive(ns3::Ptr<ns3::Packet> packet, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::SetChannel(ns3::Ptr<ns3::UanChannel> chan) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'chan')],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::Transmit(ns3::Ptr<ns3::UanPhy> src, ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('Transmit',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UniformRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3WeibullRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function]
cls.add_method('GetScale',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'scale'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ZetaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ZipfRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'n'), param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'n'), param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3BooleanChecker_methods(root_module, cls):
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')])
return
def register_Ns3BooleanValue_methods(root_module, cls):
cls.add_output_stream_operator()
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor]
cls.add_constructor([param('bool', 'value')])
## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function]
cls.add_method('Get',
'bool',
[],
is_const=True)
## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function]
cls.add_method('Set',
'void',
[param('bool', 'value')])
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_Ns3Channel_methods(root_module, cls):
## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Channel const &', 'arg0')])
## channel.h (module 'network'): ns3::Channel::Channel() [constructor]
cls.add_constructor([])
## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3ConstantRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function]
cls.add_method('GetConstant',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'constant')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'constant')])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DeterministicRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function]
cls.add_method('SetValueArray',
'void',
[param('double *', 'values'), param('uint64_t', 'length')])
## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DeviceEnergyModel_methods(root_module, cls):
## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel::DeviceEnergyModel(ns3::DeviceEnergyModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeviceEnergyModel const &', 'arg0')])
## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel::DeviceEnergyModel() [constructor]
cls.add_constructor([])
## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::ChangeState(int newState) [member function]
cls.add_method('ChangeState',
'void',
[param('int', 'newState')],
is_pure_virtual=True, is_virtual=True)
## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::GetCurrentA() const [member function]
cls.add_method('GetCurrentA',
'double',
[],
is_const=True)
## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::GetTotalEnergyConsumption() const [member function]
cls.add_method('GetTotalEnergyConsumption',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## device-energy-model.h (module 'energy'): static ns3::TypeId ns3::DeviceEnergyModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::HandleEnergyDepletion() [member function]
cls.add_method('HandleEnergyDepletion',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::HandleEnergyRecharged() [member function]
cls.add_method('HandleEnergyRecharged',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function]
cls.add_method('SetEnergySource',
'void',
[param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_pure_virtual=True, is_virtual=True)
## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::DoGetCurrentA() const [member function]
cls.add_method('DoGetCurrentA',
'double',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3DoubleValue_methods(root_module, cls):
## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor]
cls.add_constructor([])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor]
cls.add_constructor([param('double const &', 'value')])
## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## double.h (module 'core'): bool ns3::DoubleValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function]
cls.add_method('Get',
'double',
[],
is_const=True)
## double.h (module 'core'): std::string ns3::DoubleValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function]
cls.add_method('Set',
'void',
[param('double const &', 'value')])
return
def register_Ns3EmpiricalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function]
cls.add_method('CDF',
'void',
[param('double', 'v'), param('double', 'c')])
## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double c1, double c2, double v1, double v2, double r) [member function]
cls.add_method('Interpolate',
'double',
[param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')],
visibility='private', is_virtual=True)
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function]
cls.add_method('Validate',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, visibility='private', is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
visibility='private', is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EnergyHarvester_methods(root_module, cls):
## energy-harvester.h (module 'energy'): ns3::EnergyHarvester::EnergyHarvester(ns3::EnergyHarvester const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnergyHarvester const &', 'arg0')])
## energy-harvester.h (module 'energy'): ns3::EnergyHarvester::EnergyHarvester() [constructor]
cls.add_constructor([])
## energy-harvester.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergyHarvester::GetEnergySource() const [member function]
cls.add_method('GetEnergySource',
'ns3::Ptr< ns3::EnergySource >',
[],
is_const=True)
## energy-harvester.h (module 'energy'): ns3::Ptr<ns3::Node> ns3::EnergyHarvester::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True)
## energy-harvester.h (module 'energy'): double ns3::EnergyHarvester::GetPower() const [member function]
cls.add_method('GetPower',
'double',
[],
is_const=True)
## energy-harvester.h (module 'energy'): static ns3::TypeId ns3::EnergyHarvester::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## energy-harvester.h (module 'energy'): void ns3::EnergyHarvester::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function]
cls.add_method('SetEnergySource',
'void',
[param('ns3::Ptr< ns3::EnergySource >', 'source')])
## energy-harvester.h (module 'energy'): void ns3::EnergyHarvester::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## energy-harvester.h (module 'energy'): void ns3::EnergyHarvester::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## energy-harvester.h (module 'energy'): double ns3::EnergyHarvester::DoGetPower() const [member function]
cls.add_method('DoGetPower',
'double',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EnergySource_methods(root_module, cls):
## energy-source.h (module 'energy'): ns3::EnergySource::EnergySource(ns3::EnergySource const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnergySource const &', 'arg0')])
## energy-source.h (module 'energy'): ns3::EnergySource::EnergySource() [constructor]
cls.add_constructor([])
## energy-source.h (module 'energy'): void ns3::EnergySource::AppendDeviceEnergyModel(ns3::Ptr<ns3::DeviceEnergyModel> deviceEnergyModelPtr) [member function]
cls.add_method('AppendDeviceEnergyModel',
'void',
[param('ns3::Ptr< ns3::DeviceEnergyModel >', 'deviceEnergyModelPtr')])
## energy-source.h (module 'energy'): void ns3::EnergySource::ConnectEnergyHarvester(ns3::Ptr<ns3::EnergyHarvester> energyHarvesterPtr) [member function]
cls.add_method('ConnectEnergyHarvester',
'void',
[param('ns3::Ptr< ns3::EnergyHarvester >', 'energyHarvesterPtr')])
## energy-source.h (module 'energy'): void ns3::EnergySource::DisposeDeviceModels() [member function]
cls.add_method('DisposeDeviceModels',
'void',
[])
## energy-source.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::EnergySource::FindDeviceEnergyModels(ns3::TypeId tid) [member function]
cls.add_method('FindDeviceEnergyModels',
'ns3::DeviceEnergyModelContainer',
[param('ns3::TypeId', 'tid')])
## energy-source.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::EnergySource::FindDeviceEnergyModels(std::string name) [member function]
cls.add_method('FindDeviceEnergyModels',
'ns3::DeviceEnergyModelContainer',
[param('std::string', 'name')])
## energy-source.h (module 'energy'): double ns3::EnergySource::GetEnergyFraction() [member function]
cls.add_method('GetEnergyFraction',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## energy-source.h (module 'energy'): double ns3::EnergySource::GetInitialEnergy() const [member function]
cls.add_method('GetInitialEnergy',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## energy-source.h (module 'energy'): ns3::Ptr<ns3::Node> ns3::EnergySource::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True)
## energy-source.h (module 'energy'): double ns3::EnergySource::GetRemainingEnergy() [member function]
cls.add_method('GetRemainingEnergy',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## energy-source.h (module 'energy'): double ns3::EnergySource::GetSupplyVoltage() const [member function]
cls.add_method('GetSupplyVoltage',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## energy-source.h (module 'energy'): static ns3::TypeId ns3::EnergySource::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## energy-source.h (module 'energy'): void ns3::EnergySource::InitializeDeviceModels() [member function]
cls.add_method('InitializeDeviceModels',
'void',
[])
## energy-source.h (module 'energy'): void ns3::EnergySource::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## energy-source.h (module 'energy'): void ns3::EnergySource::UpdateEnergySource() [member function]
cls.add_method('UpdateEnergySource',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## energy-source.h (module 'energy'): void ns3::EnergySource::BreakDeviceEnergyModelRefCycle() [member function]
cls.add_method('BreakDeviceEnergyModelRefCycle',
'void',
[],
visibility='protected')
## energy-source.h (module 'energy'): double ns3::EnergySource::CalculateTotalCurrent() [member function]
cls.add_method('CalculateTotalCurrent',
'double',
[],
visibility='protected')
## energy-source.h (module 'energy'): void ns3::EnergySource::NotifyEnergyDrained() [member function]
cls.add_method('NotifyEnergyDrained',
'void',
[],
visibility='protected')
## energy-source.h (module 'energy'): void ns3::EnergySource::NotifyEnergyRecharged() [member function]
cls.add_method('NotifyEnergyRecharged',
'void',
[],
visibility='protected')
## energy-source.h (module 'energy'): void ns3::EnergySource::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EnergySourceContainer_methods(root_module, cls):
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::EnergySourceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnergySourceContainer const &', 'arg0')])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer() [constructor]
cls.add_constructor([])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::Ptr<ns3::EnergySource> source) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EnergySource >', 'source')])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(std::string sourceName) [constructor]
cls.add_constructor([param('std::string', 'sourceName')])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::EnergySourceContainer const & a, ns3::EnergySourceContainer const & b) [constructor]
cls.add_constructor([param('ns3::EnergySourceContainer const &', 'a'), param('ns3::EnergySourceContainer const &', 'b')])
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(ns3::EnergySourceContainer container) [member function]
cls.add_method('Add',
'void',
[param('ns3::EnergySourceContainer', 'container')])
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(ns3::Ptr<ns3::EnergySource> source) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::EnergySource >', 'source')])
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(std::string sourceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'sourceName')])
## energy-source-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::EnergySource>*,std::vector<ns3::Ptr<ns3::EnergySource>, std::allocator<ns3::Ptr<ns3::EnergySource> > > > ns3::EnergySourceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::EnergySource > const, std::vector< ns3::Ptr< ns3::EnergySource > > >',
[],
is_const=True)
## energy-source-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::EnergySource>*,std::vector<ns3::Ptr<ns3::EnergySource>, std::allocator<ns3::Ptr<ns3::EnergySource> > > > ns3::EnergySourceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::EnergySource > const, std::vector< ns3::Ptr< ns3::EnergySource > > >',
[],
is_const=True)
## energy-source-container.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergySourceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::EnergySource >',
[param('uint32_t', 'i')],
is_const=True)
## energy-source-container.h (module 'energy'): uint32_t ns3::EnergySourceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## energy-source-container.h (module 'energy'): static ns3::TypeId ns3::EnergySourceContainer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EnumChecker_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): void ns3::EnumChecker::Add(int value, std::string name) [member function]
cls.add_method('Add',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int value, std::string name) [member function]
cls.add_method('AddDefault',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EnumValue_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumValue const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): ns3::EnumValue::EnumValue(int value) [constructor]
cls.add_constructor([param('int', 'value')])
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function]
cls.add_method('Get',
'int',
[],
is_const=True)
## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): void ns3::EnumValue::Set(int value) [member function]
cls.add_method('Set',
'void',
[param('int', 'value')])
return
def register_Ns3ErlangRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function]
cls.add_method('GetK',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'k'), param('double', 'lambda')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'k'), param('uint32_t', 'lambda')])
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3EventImpl_methods(root_module, cls):
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventImpl const &', 'arg0')])
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor]
cls.add_constructor([])
## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[])
## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function]
cls.add_method('IsCancelled',
'bool',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function]
cls.add_method('Notify',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3ExponentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3GammaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function]
cls.add_method('GetBeta',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha'), param('double', 'beta')])
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha'), param('uint32_t', 'beta')])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3IntegerValue_methods(root_module, cls):
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor]
cls.add_constructor([])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor]
cls.add_constructor([param('int64_t const &', 'value')])
## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## integer.h (module 'core'): bool ns3::IntegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function]
cls.add_method('Get',
'int64_t',
[],
is_const=True)
## integer.h (module 'core'): std::string ns3::IntegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('int64_t const &', 'value')])
return
def register_Ns3Ipv4AddressChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv4AddressValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Address const &', 'value')])
return
def register_Ns3Ipv4MaskChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')])
return
def register_Ns3Ipv4MaskValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Mask const &', 'value')])
return
def register_Ns3Ipv6AddressChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv6AddressValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Address const &', 'value')])
return
def register_Ns3Ipv6PrefixChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')])
return
def register_Ns3Ipv6PrefixValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Prefix',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Prefix const &', 'value')])
return
def register_Ns3LogNormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function]
cls.add_method('GetMu',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function]
cls.add_method('GetSigma',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mu'), param('double', 'sigma')])
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mu'), param('uint32_t', 'sigma')])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3Mac48AddressChecker_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')])
return
def register_Ns3Mac48AddressValue_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'value')])
## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac48Address',
[],
is_const=True)
## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac48Address const &', 'value')])
return
def register_Ns3MobilityModel_methods(root_module, cls):
## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel(ns3::MobilityModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MobilityModel const &', 'arg0')])
## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel() [constructor]
cls.add_constructor([])
## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr<const ns3::MobilityModel> position) const [member function]
cls.add_method('GetDistanceFrom',
'double',
[param('ns3::Ptr< ns3::MobilityModel const >', 'position')],
is_const=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetPosition() const [member function]
cls.add_method('GetPosition',
'ns3::Vector',
[],
is_const=True)
## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetRelativeSpeed(ns3::Ptr<const ns3::MobilityModel> other) const [member function]
cls.add_method('GetRelativeSpeed',
'double',
[param('ns3::Ptr< ns3::MobilityModel const >', 'other')],
is_const=True)
## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function]
cls.add_method('GetVelocity',
'ns3::Vector',
[],
is_const=True)
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function]
cls.add_method('SetPosition',
'void',
[param('ns3::Vector const &', 'position')])
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function]
cls.add_method('NotifyCourseChange',
'void',
[],
is_const=True, visibility='protected')
## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::DoAssignStreams(int64_t start) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'start')],
visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function]
cls.add_method('DoGetPosition',
'ns3::Vector',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function]
cls.add_method('DoGetVelocity',
'ns3::Vector',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function]
cls.add_method('DoSetPosition',
'void',
[param('ns3::Vector const &', 'position')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3NetDevice_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDevice const &', 'arg0')])
## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3NetDeviceQueue_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')])
## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): bool ns3::NetDeviceQueue::HasWakeCallbackSet() const [member function]
cls.add_method('HasWakeCallbackSet',
'bool',
[],
is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function]
cls.add_method('IsStopped',
'bool',
[],
is_const=True)
## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetWakeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function]
cls.add_method('Start',
'void',
[],
is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function]
cls.add_method('Wake',
'void',
[],
is_virtual=True)
return
def register_Ns3NetDeviceQueueInterface_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')])
## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function]
cls.add_method('GetNTxQueues',
'uint8_t',
[],
is_const=True)
## net-device.h (module 'network'): ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function]
cls.add_method('GetSelectQueueCallback',
'ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(uint8_t i) const [member function]
cls.add_method('GetTxQueue',
'ns3::Ptr< ns3::NetDeviceQueue >',
[param('uint8_t', 'i')],
is_const=True)
## net-device.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetSelectQueueCallback',
'void',
[param('ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')])
## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function]
cls.add_method('SetTxQueuesN',
'void',
[param('uint8_t', 'numTxQueues')])
## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3NixVector_methods(root_module, cls):
cls.add_output_stream_operator()
## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor]
cls.add_constructor([])
## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor]
cls.add_constructor([param('ns3::NixVector const &', 'o')])
## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function]
cls.add_method('AddNeighborIndex',
'void',
[param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function]
cls.add_method('BitCount',
'uint32_t',
[param('uint32_t', 'numberOfNeighbors')],
is_const=True)
## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint32_t const *', 'buffer'), param('uint32_t', 'size')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function]
cls.add_method('ExtractNeighborIndex',
'uint32_t',
[param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function]
cls.add_method('GetRemainingBits',
'uint32_t',
[])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3Node_methods(root_module, cls):
## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Node const &', 'arg0')])
## node.h (module 'network'): ns3::Node::Node() [constructor]
cls.add_constructor([])
## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor]
cls.add_constructor([param('uint32_t', 'systemId')])
## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('AddApplication',
'uint32_t',
[param('ns3::Ptr< ns3::Application >', 'application')])
## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddDevice',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function]
cls.add_method('ChecksumEnabled',
'bool',
[],
is_static=True)
## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function]
cls.add_method('GetApplication',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): ns3::Time ns3::Node::GetLocalTime() const [member function]
cls.add_method('GetLocalTime',
'ns3::Time',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function]
cls.add_method('GetNApplications',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('RegisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function]
cls.add_method('RegisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')])
## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('UnregisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function]
cls.add_method('UnregisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')])
## node.h (module 'network'): void ns3::Node::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## node.h (module 'network'): void ns3::Node::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3NormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable]
cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function]
cls.add_method('GetVariance',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')])
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ObjectFactoryChecker_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')])
return
def register_Ns3ObjectFactoryValue_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'value')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function]
cls.add_method('Get',
'ns3::ObjectFactory',
[],
is_const=True)
## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::ObjectFactory const &', 'value')])
return
def register_Ns3Packet_methods(root_module, cls):
cls.add_output_stream_operator()
## packet.h (module 'network'): ns3::Packet::Packet() [constructor]
cls.add_constructor([])
## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor]
cls.add_constructor([param('ns3::Packet const &', 'o')])
## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor]
cls.add_constructor([param('uint32_t', 'size')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddByteTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header')])
## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddPacketTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer')])
## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function]
cls.add_method('EnablePrinting',
'void',
[],
is_static=True)
## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function]
cls.add_method('FindFirstMatchingByteTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function]
cls.add_method('GetByteTagIterator',
'ns3::ByteTagIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function]
cls.add_method('GetNixVector',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function]
cls.add_method('GetPacketTagIterator',
'ns3::PacketTagIterator',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function]
cls.add_method('PeekHeader',
'uint32_t',
[param('ns3::Header &', 'header')],
is_const=True)
## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function]
cls.add_method('PeekPacketTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('PeekTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function]
cls.add_method('PrintByteTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function]
cls.add_method('PrintPacketTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function]
cls.add_method('RemoveAllByteTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function]
cls.add_method('RemoveAllPacketTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function]
cls.add_method('RemoveHeader',
'uint32_t',
[param('ns3::Header &', 'header')])
## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function]
cls.add_method('RemovePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('RemoveTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function]
cls.add_method('ReplacePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function]
cls.add_method('SetNixVector',
'void',
[param('ns3::Ptr< ns3::NixVector >', 'nixVector')])
## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function]
cls.add_method('ToString',
'std::string',
[],
is_const=True)
return
def register_Ns3ParetoRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3PointerChecker_methods(root_module, cls):
## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker() [constructor]
cls.add_constructor([])
## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker(ns3::PointerChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PointerChecker const &', 'arg0')])
## pointer.h (module 'core'): ns3::TypeId ns3::PointerChecker::GetPointeeTypeId() const [member function]
cls.add_method('GetPointeeTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3PointerValue_methods(root_module, cls):
## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::PointerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PointerValue const &', 'arg0')])
## pointer.h (module 'core'): ns3::PointerValue::PointerValue() [constructor]
cls.add_constructor([])
## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::Ptr<ns3::Object> object) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Object >', 'object')])
## pointer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::PointerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## pointer.h (module 'core'): bool ns3::PointerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## pointer.h (module 'core'): ns3::Ptr<ns3::Object> ns3::PointerValue::GetObject() const [member function]
cls.add_method('GetObject',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## pointer.h (module 'core'): std::string ns3::PointerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## pointer.h (module 'core'): void ns3::PointerValue::SetObject(ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('SetObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'object')])
return
def register_Ns3QueueItem_methods(root_module, cls):
cls.add_output_stream_operator()
## net-device.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')])
## net-device.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## net-device.h (module 'network'): uint32_t ns3::QueueItem::GetPacketSize() const [member function]
cls.add_method('GetPacketSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function]
cls.add_method('GetUint8Value',
'bool',
[param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')],
is_const=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
return
def register_Ns3TimeValue_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeValue const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor]
cls.add_constructor([param('ns3::Time const &', 'value')])
## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function]
cls.add_method('Get',
'ns3::Time',
[],
is_const=True)
## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Time const &', 'value')])
return
def register_Ns3TypeIdChecker_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')])
return
def register_Ns3TypeIdValue_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor]
cls.add_constructor([param('ns3::TypeId const &', 'value')])
## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function]
cls.add_method('Get',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::TypeId const &', 'value')])
return
def register_Ns3UanChannel_methods(root_module, cls):
## uan-channel.h (module 'uan'): ns3::UanChannel::UanChannel(ns3::UanChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanChannel const &', 'arg0')])
## uan-channel.h (module 'uan'): ns3::UanChannel::UanChannel() [constructor]
cls.add_constructor([])
## uan-channel.h (module 'uan'): void ns3::UanChannel::AddDevice(ns3::Ptr<ns3::UanNetDevice> dev, ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('AddDevice',
'void',
[param('ns3::Ptr< ns3::UanNetDevice >', 'dev'), param('ns3::Ptr< ns3::UanTransducer >', 'trans')])
## uan-channel.h (module 'uan'): void ns3::UanChannel::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## uan-channel.h (module 'uan'): ns3::Ptr<ns3::NetDevice> ns3::UanChannel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## uan-channel.h (module 'uan'): uint32_t ns3::UanChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-channel.h (module 'uan'): double ns3::UanChannel::GetNoiseDbHz(double fKhz) [member function]
cls.add_method('GetNoiseDbHz',
'double',
[param('double', 'fKhz')])
## uan-channel.h (module 'uan'): static ns3::TypeId ns3::UanChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-channel.h (module 'uan'): void ns3::UanChannel::SetNoiseModel(ns3::Ptr<ns3::UanNoiseModel> noise) [member function]
cls.add_method('SetNoiseModel',
'void',
[param('ns3::Ptr< ns3::UanNoiseModel >', 'noise')])
## uan-channel.h (module 'uan'): void ns3::UanChannel::SetPropagationModel(ns3::Ptr<ns3::UanPropModel> prop) [member function]
cls.add_method('SetPropagationModel',
'void',
[param('ns3::Ptr< ns3::UanPropModel >', 'prop')])
## uan-channel.h (module 'uan'): void ns3::UanChannel::TxPacket(ns3::Ptr<ns3::UanTransducer> src, ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txmode) [member function]
cls.add_method('TxPacket',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txmode')])
## uan-channel.h (module 'uan'): void ns3::UanChannel::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanModesListChecker_methods(root_module, cls):
## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker::UanModesListChecker() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker::UanModesListChecker(ns3::UanModesListChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanModesListChecker const &', 'arg0')])
return
def register_Ns3UanModesListValue_methods(root_module, cls):
## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue(ns3::UanModesListValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanModesListValue const &', 'arg0')])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue(ns3::UanModesList const & value) [constructor]
cls.add_constructor([param('ns3::UanModesList const &', 'value')])
## uan-tx-mode.h (module 'uan'): ns3::Ptr<ns3::AttributeValue> ns3::UanModesListValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## uan-tx-mode.h (module 'uan'): bool ns3::UanModesListValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## uan-tx-mode.h (module 'uan'): ns3::UanModesList ns3::UanModesListValue::Get() const [member function]
cls.add_method('Get',
'ns3::UanModesList',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): std::string ns3::UanModesListValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## uan-tx-mode.h (module 'uan'): void ns3::UanModesListValue::Set(ns3::UanModesList const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::UanModesList const &', 'value')])
return
def register_Ns3UanNetDevice_methods(root_module, cls):
## uan-net-device.h (module 'uan'): ns3::UanNetDevice::UanNetDevice(ns3::UanNetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanNetDevice const &', 'arg0')])
## uan-net-device.h (module 'uan'): ns3::UanNetDevice::UanNetDevice() [constructor]
cls.add_constructor([])
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::Channel> ns3::UanNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): uint32_t ns3::UanNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::UanMac> ns3::UanNetDevice::GetMac() const [member function]
cls.add_method('GetMac',
'ns3::Ptr< ns3::UanMac >',
[],
is_const=True)
## uan-net-device.h (module 'uan'): uint16_t ns3::UanNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::Node> ns3::UanNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::UanPhy> ns3::UanNetDevice::GetPhy() const [member function]
cls.add_method('GetPhy',
'ns3::Ptr< ns3::UanPhy >',
[],
is_const=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanNetDevice::GetTransducer() const [member function]
cls.add_method('GetTransducer',
'ns3::Ptr< ns3::UanTransducer >',
[],
is_const=True)
## uan-net-device.h (module 'uan'): static ns3::TypeId ns3::UanNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'channel')])
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::UanMac >', 'mac')])
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('SetPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')])
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetSleepMode(bool sleep) [member function]
cls.add_method('SetSleepMode',
'void',
[param('bool', 'sleep')])
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('SetTransducer',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'trans')])
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::ForwardUp(ns3::Ptr<ns3::Packet> pkt, ns3::UanAddress const & src) [member function]
cls.add_method('ForwardUp',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::UanAddress const &', 'src')],
visibility='private', is_virtual=True)
return
def register_Ns3UintegerValue_methods(root_module, cls):
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor]
cls.add_constructor([])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor]
cls.add_constructor([param('uint64_t const &', 'value')])
## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function]
cls.add_method('Get',
'uint64_t',
[],
is_const=True)
## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('uint64_t const &', 'value')])
return
def register_Ns3Vector2DChecker_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')])
return
def register_Ns3Vector2DValue_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor]
cls.add_constructor([param('ns3::Vector2D const &', 'value')])
## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector2DValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## vector.h (module 'core'): bool ns3::Vector2DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function]
cls.add_method('Get',
'ns3::Vector2D',
[],
is_const=True)
## vector.h (module 'core'): std::string ns3::Vector2DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Vector2D const &', 'value')])
return
def register_Ns3Vector3DChecker_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')])
return
def register_Ns3Vector3DValue_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor]
cls.add_constructor([param('ns3::Vector3D const &', 'value')])
## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector3DValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## vector.h (module 'core'): bool ns3::Vector3DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function]
cls.add_method('Get',
'ns3::Vector3D',
[],
is_const=True)
## vector.h (module 'core'): std::string ns3::Vector3DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Vector3D const &', 'value')])
return
def register_Ns3AcousticModemEnergyModel_methods(root_module, cls):
## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel::AcousticModemEnergyModel(ns3::AcousticModemEnergyModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AcousticModemEnergyModel const &', 'arg0')])
## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel::AcousticModemEnergyModel() [constructor]
cls.add_constructor([])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::ChangeState(int newState) [member function]
cls.add_method('ChangeState',
'void',
[param('int', 'newState')],
is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): int ns3::AcousticModemEnergyModel::GetCurrentState() const [member function]
cls.add_method('GetCurrentState',
'int',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetIdlePowerW() const [member function]
cls.add_method('GetIdlePowerW',
'double',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): ns3::Ptr<ns3::Node> ns3::AcousticModemEnergyModel::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetRxPowerW() const [member function]
cls.add_method('GetRxPowerW',
'double',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetSleepPowerW() const [member function]
cls.add_method('GetSleepPowerW',
'double',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetTotalEnergyConsumption() const [member function]
cls.add_method('GetTotalEnergyConsumption',
'double',
[],
is_const=True, is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetTxPowerW() const [member function]
cls.add_method('GetTxPowerW',
'double',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): static ns3::TypeId ns3::AcousticModemEnergyModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::HandleEnergyDepletion() [member function]
cls.add_method('HandleEnergyDepletion',
'void',
[],
is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::HandleEnergyRecharged() [member function]
cls.add_method('HandleEnergyRecharged',
'void',
[],
is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergyDepletionCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetEnergyDepletionCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergyRechargeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetEnergyRechargeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function]
cls.add_method('SetEnergySource',
'void',
[param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetIdlePowerW(double idlePowerW) [member function]
cls.add_method('SetIdlePowerW',
'void',
[param('double', 'idlePowerW')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetRxPowerW(double rxPowerW) [member function]
cls.add_method('SetRxPowerW',
'void',
[param('double', 'rxPowerW')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetSleepPowerW(double sleepPowerW) [member function]
cls.add_method('SetSleepPowerW',
'void',
[param('double', 'sleepPowerW')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetTxPowerW(double txPowerW) [member function]
cls.add_method('SetTxPowerW',
'void',
[param('double', 'txPowerW')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::DoGetCurrentA() const [member function]
cls.add_method('DoGetCurrentA',
'double',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AddressChecker_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')])
return
def register_Ns3AddressValue_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressValue const &', 'arg0')])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor]
cls.add_constructor([param('ns3::Address const &', 'value')])
## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Address',
[],
is_const=True)
## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Address const &', 'value')])
return
def register_Ns3HashImplementation_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor]
cls.add_constructor([])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_pure_virtual=True, is_virtual=True)
## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function]
cls.add_method('clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3HashFunctionFnv1a_methods(root_module, cls):
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')])
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor]
cls.add_constructor([])
## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionHash32_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor]
cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionHash64_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor]
cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionMurmur3_methods(root_module, cls):
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')])
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor]
cls.add_constructor([])
## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_functions(root_module):
module = root_module
## uan-tx-mode.h (module 'uan'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeUanModesListChecker() [free function]
module.add_function('MakeUanModesListChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module)
register_functions_ns3_Hash(module.get_submodule('Hash'), root_module)
register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module)
register_functions_ns3_internal(module.get_submodule('internal'), root_module)
return
def register_functions_ns3_FatalImpl(module, root_module):
return
def register_functions_ns3_Hash(module, root_module):
register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module)
return
def register_functions_ns3_Hash_Function(module, root_module):
return
def register_functions_ns3_TracedValueCallback(module, root_module):
return
def register_functions_ns3_internal(module, root_module):
return
def main():
out = FileCodeSink(sys.stdout)
root_module = module_init()
register_types(root_module)
register_methods(root_module)
register_functions(root_module)
root_module.generate(out)
if __name__ == '__main__':
main()
| gpl-2.0 |
technicalpickles/zulip | zerver/management/commands/realm_filters.py | 113 | 2798 | from __future__ import absolute_import
from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.models import RealmFilter, all_realm_filters, Realm
from zerver.lib.actions import do_add_realm_filter, do_remove_realm_filter
import sys
class Command(BaseCommand):
help = """Create a link filter rule for the specified domain.
NOTE: Regexes must be simple enough that they can be easily translated to JavaScript
RegExp syntax. In addition to JS-compatible syntax, the following features are available:
* Named groups will be converted to numbered groups automatically
* Inline-regex flags will be stripped, and where possible translated to RegExp-wide flags
Example: python manage.py realm_filters --realm=zulip.com --op=add '#(?P<id>[0-9]{2,8})' 'https://trac.humbughq.com/ticket/%(id)s'
Example: python manage.py realm_filters --realm=zulip.com --op=remove '#(?P<id>[0-9]{2,8})'
Example: python manage.py realm_filters --realm=zulip.com --op=show
"""
def add_arguments(self, parser):
parser.add_argument('-r', '--realm',
dest='domain',
type=str,
required=True,
help='The name of the realm to adjust filters for.')
parser.add_argument('--op',
dest='op',
type=str,
default="show",
help='What operation to do (add, show, remove).')
parser.add_argument('pattern', metavar='<pattern>', type=str, nargs='?', default=None,
help="regular expression to match")
parser.add_argument('url_format_string', metavar='<url pattern>', type=str, nargs='?',
help="format string to substitute")
def handle(self, *args, **options):
realm = Realm.objects.get(domain=options["domain"])
if options["op"] == "show":
print "%s: %s" % (realm.domain, all_realm_filters().get(realm.domain, ""))
sys.exit(0)
pattern = options['pattern']
if not pattern:
self.print_help("python manage.py", "realm_filters")
sys.exit(1)
if options["op"] == "add":
url_format_string = options['url_format_string']
if not url_format_string:
self.print_help("python manage.py", "realm_filters")
sys.exit(1)
do_add_realm_filter(realm, pattern, url_format_string)
sys.exit(0)
elif options["op"] == "remove":
do_remove_realm_filter(realm, pattern)
sys.exit(0)
else:
self.print_help("python manage.py", "realm_filters")
sys.exit(1)
| apache-2.0 |
ashhher3/invenio | modules/bibexport/lib/bibexport_method_fieldexporter_templates.py | 35 | 29935 | # -*- coding: utf-8 -*-
## $Id: webmessage_templates.py,v 1.32 2008/03/26 23:26:23 tibor Exp $
##
## handles rendering of webmessage module
##
## This file is part of Invenio.
## Copyright (C) 2009, 2010, 2011 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.
""" Templates for field exporter plugin """
__revision__ = "$Id: webmessage_templates.py,v 1.32 2008/03/26 23:26:23 tibor Exp $"
import cgi
from invenio.config import CFG_SITE_LANG, CFG_SITE_URL
from invenio.messages import gettext_set_language
from invenio.dateutils import convert_datestruct_to_datetext, convert_datetext_to_dategui, convert_datestruct_to_dategui
from invenio.bibexport_method_fieldexporter_dblayer import Job, JobResult
class Template:
"""Templates for field exporter plugin"""
_JOBS_URL = "%s/exporter/jobs" % (CFG_SITE_URL, )
_EDIT_JOB_URL = "%s/exporter/edit_job" % (CFG_SITE_URL, )
_EDIT_QUERY_URL = "%s/exporter/edit_query" % (CFG_SITE_URL, )
_JOB_RESULTS_URL = "%s/exporter/job_results" % (CFG_SITE_URL, )
_DISPLAY_JOB_RESULT_URL = "%s/exporter/display_job_result" % (CFG_SITE_URL, )
_DOWNLOAD_JOB_RESULT_URL = "%s/exporter/download_job_result" % (CFG_SITE_URL, )
_JOB_HISTORY_URL = "%s/exporter/history" % (CFG_SITE_URL, )
def tmpl_styles(self):
"""Defines the local CSS styles used in the plugin"""
styles = """
<style type="text/css">
.label{
white-space: nowrap;
padding-right: 15px;
}
.textentry{
width: 350px;
}
table.spacedcells td{
padding-right: 20px;
white-space: nowrap;
}
table.spacedcells th{
padding-right: 20px;
text-align: left;
}
</style>
<script type="text/javascript">
<!--
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
if(!document.forms[FormName])
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
// -->
</script>
"""
return styles
def tmpl_navigation_menu(self, language = CFG_SITE_LANG):
"""Returns HTML representing navigation menu for field exporter."""
_ = gettext_set_language(language)
navigation_menu = """
<table class="headermodulebox">
<tbody><tr>
<td class="headermoduleboxbody">
<a class="header" href="%(job_verview_url)s?ln=%(language)s">%(label_job_overview)s</a>
</td>
<td class="headermoduleboxbody">
<a class="header" href="%(edit_job_url)s?ln=%(language)s">%(label_new_job)s</a>
</td>
<td class="headermoduleboxbody">
<a class="header" href="%(job_history_url)s?ln=%(language)s">%(label_job_history)s</a>
</td>
</tr></tbody></table>
""" % {"edit_job_url" : self._EDIT_JOB_URL,
"job_verview_url" : self._JOBS_URL,
"job_history_url" : self._JOB_HISTORY_URL,
"language" : language,
"label_job_overview" : _("Export Job Overview"),
"label_new_job" : _("New Export Job"),
"label_job_history" : _("Export Job History")
}
return navigation_menu
def tmpl_display_jobs(self, jobs, language = CFG_SITE_LANG):
"""
Creates page for displaying of all the jobs.
@param jobs: list of the jobs that have to be displayed
@param language: language of the page
"""
_ = gettext_set_language(language)
table_rows = ""
for current_job in jobs:
# convert last run date into text proper to be shown to the user
datetext = convert_datestruct_to_datetext(current_job.get_last_run())
last_run = convert_datetext_to_dategui(datetext, language)
# obtain text corresponding to the frequency of execution
frequency = current_job.get_frequency()
frequency_text = self._get_frequency_text(frequency)
row = """<tr>
<td><input type="checkbox" name="selected_jobs" value="%(job_id)s"></input></td>
<td><a href="%(edit_job_url)s?id=%(job_id)s&ln=%(language)s">%(name)s</a></td>
<td>%(frequency)s</td>
<td>%(last_run)s</td>
</tr>""" % self._html_escape_dictionary({
"edit_job_url" : self._EDIT_JOB_URL,
"job_id" : current_job.get_id(),
"name" : current_job.get_name(),
"frequency" : frequency_text,
"language" : language,
"last_run" : last_run
})
table_rows += row
select_all_none_row = """
<tr><td colspan="4">
<small>%s</small><br><br>
</td></tr>""" \
%(self._get_select_all_none_html("jobsForm",
"selected_jobs",
language))
table_rows += select_all_none_row
buttons_row = """<tr>
<td colspan="3">
<input type="Submit" name="run_button" value="%(label_run)s" class="formbutton">
<input type="Submit" name="delete_button" value="%(label_delete)s" class="formbutton">
</td>
<td align="right">
<input type="Submit" name="new_button" value="%(label_new)s" class="formbutton">
</td>
</tr>""" % {
"label_run" : _("Run"),
"label_delete" : _("Delete"),
"label_new" : _("New")
}
table_rows += buttons_row
body = """
<form method="post" name="jobsForm">
<table class="spacedcells">
<th></th>
<th>%(label_name)s</th>
<th>%(label_frequency)s</th>
<th>%(label_last_run)s</th>
%(table_rows)s
</table>
</form>
""" % {
"table_rows" : table_rows,
"label_name" : _("Name"),
"label_frequency" : _("Run"),
"label_last_run" : _("Last run")
}
return body
def tmpl_edit_job(self, job, language = CFG_SITE_LANG):
"""
Creates page for editing of jobs.
@param job: The job that will be edited
@param language: language of the page
"""
_ = gettext_set_language(language)
job_frequency = job.get_frequency()
frequency_select_box_html = self._create_frequency_select_box("job_frequency", job_frequency, language)
output_format_select_box_html = self._create_output_format_select_box(selected_value = job.get_output_format())
body = """
<form method="post">
<input type="Hidden" name="id" value="%(job_id)s">
<table>
<tr>
<td class = "label">%(name_label)s</td>
<td colspan="2"><input type="text" name="job_name" class="textentry" value="%(job_name)s"></td>
</tr>
<tr>
<td class = "label">%(frequency_label)s</td>
<td colspan="2">%(frequency_select_box)s</td>
</tr>
<tr>
<td class = "label">%(output_format_label)s</td>
<td colspan="2">%(output_format_select_box)s</td>
</tr>
<tr>
<td class = "label">%(start_label)s</td>
<td colspan="2"><input type="text" name="last_run" class="textentry" value="%(job_last_run)s"></td>
</tr>
<tr>
<td class = "label">%(output_directory_label)s</td>
<td colspan="2"><input type="text" name="output_directory" class="textentry" value="%(output_directory)s"></td>
</tr>
<tr>
<td></td>
<td>
<input type="Submit" name="save_button" value="%(save_label)s" class="formbutton">
<input type="Submit" name="cancel_button" value="%(cancel_label)s" class="formbutton">
</td>
<td align="right">
<input type="Submit" name="edit_queries_button" value="%(edit_queries_label)s" class="formbutton">
</td>
</tr>
</table>
</form>
""" % {
"name_label" : _("Name"),
"frequency_label" : _("Frequency"),
"output_format_label" : _("Output Format"),
"start_label" : _("Start"),
"output_directory_label" : _("Output Directory"),
"save_label" : _("Save"),
"cancel_label" : _("Cancel"),
"edit_queries_label" : _("Edit Queries"),
"job_id" : self._html_escape_content(job.get_id()),
"job_name" : self._html_escape_content(job.get_name()),
"frequency_select_box" : frequency_select_box_html,
"output_format_select_box" : output_format_select_box_html,
"job_last_run" : convert_datestruct_to_datetext(job.get_last_run()),
"output_directory" : self._html_escape_content(job.get_output_directory())
}
return body
def tmpl_display_job_queries(self, job_queries, job_id, language = CFG_SITE_LANG):
"""
Creates page for displaying of queries of a given jobs.
@param job_queries: list of JobQuery objects that have to be displayed
@param job_id: identifier of the job that own the queries
@param language: language of the page
"""
_ = gettext_set_language(language)
table_rows = ""
for current_query in job_queries:
output_fields = ", ".join(current_query.get_output_fields())
row = """<tr>
<td><input type="checkbox" name="selected_queries" value="%(query_id)s"></input></td>
<td><a href="%(edit_query_url)s?id=%(query_id)s&job_id=%(job_id)s&ln=%(language)s">%(name)s</a></td>
<td><input type="text" value="%(search_criteria)s" readonly style="border: none; width: 130px"></td>
<td><input type="text" value="%(output_fields)s" readonly style="border: none; width: 130px"></td>
<td><input type="text" value="%(comment)s" readonly style="border: none; width: 130px"></td>
</tr>""" % self._html_escape_dictionary({
"edit_query_url" : self._EDIT_QUERY_URL,
"language" : language,
"query_id" : current_query.get_id(),
"search_criteria" : current_query.get_search_criteria(),
"name" : current_query.get_name(),
"comment" : current_query.get_comment(),
"output_fields" : output_fields,
"job_id" : job_id
})
table_rows += row
select_all_none_row = """
<tr><td colspan="4">
<small>%s</small><br><br>
</td></tr>""" \
% (self._get_select_all_none_html("queriesForm",
"selected_queries",
language))
table_rows += select_all_none_row
buttons_row = """<tr>
<td colspan="4">
<input type="Submit" name="run_button" value="%(label_run)s" class="formbutton">
<input type="Submit" name="delete_button" value="%(label_delete)s" class="formbutton">
</td>
<td align="right">
<input type="Submit" name="new_button" value="%(label_new)s" class="formbutton">
</td>
</tr>""" % {
"label_run" : _("Run"),
"label_delete" : _("Delete"),
"label_new" : _("New")
}
table_rows += buttons_row
body = """
<form method="post" name="queriesForm">
<input type="Hidden" name="job_id" value="%(job_id)s">
<table class="spacedcells">
<th></th>
<th>%(label_name)s</th>
<th>%(label_search_criteria)s</th>
<th>%(label_output_fields)s</th>
<th>%(label_comment)s</th>
%(table_rows)s
</table>
</form>
""" % {
"table_rows" : table_rows,
"label_name" : _("Name"),
"label_search_criteria" : _("Query"),
"label_comment" : _("Comment"),
"label_output_fields" : _("Output Fields"),
"job_id" : self._html_escape_content(job_id)
}
return body
def tmpl_edit_query(self, query, job_id, language = CFG_SITE_LANG):
"""
Creates page for editing of a query.
@param query: the query that will be edited
@param language: language of the page
@return: The HTML content of the page
"""
_ = gettext_set_language(language)
body = """
<form method="post">
<input type="Hidden" name="id" value="%(id)s">
<input type="Hidden" name="job_id" value="%(job_id)s">
<table >
<tr>
<td class = "label">%(name_label)s</td>
<td><input type="text" name="name" class="textentry" value="%(name)s"></td>
</tr>
<tr>
<td class = "label">%(query_label)s</td>
<td><input type="text" name="search_criteria" class="textentry" value="%(search_criteria)s"></td>
</tr>
<tr>
<td class = "label">%(output_fields_label)s</td>
<td><input type="text" name="output_fields" class="textentry" value="%(output_fields)s"></td>
</tr>
<tr>
<td class = "label">%(comment_label)s</td>
<td><textarea name="comment" rows="6" class="textentry">%(comment)s</textarea></td>
</tr>
<tr>
<td></td>
<td>
<input type="Submit" name="save_button" value="%(save_label)s" class="formbutton">
<input type="Submit" name="cancel_button" value="%(cancel_label)s" class="formbutton">
</td>
</tr>
</table>
</form>
""" % self._html_escape_dictionary({
"name_label" : _("Name"),
"query_label" : _("Query"),
"output_fields_label" : _("Output fields"),
"comment_label" : _("Comment"),
"save_label" : _("Save"),
"cancel_label" : _("Cancel"),
"job_id" : job_id,
"id" : query.get_id(),
"name" : query.get_name(),
"search_criteria" : query.get_search_criteria(),
"output_fields" : ", ".join(query.get_output_fields()),
"comment" : query.get_comment(),
})
return body
def tmpl_display_queries_results(self, job_result, language = CFG_SITE_LANG):
"""Creates a page displaying results from execution of multiple queries.
@param job_result: JobResult object containing the job results
that will be displayed
@param language: language of the page
@return: The HTML content of the page
"""
_ = gettext_set_language(language)
queries_results = job_result.get_query_results()
output_format = job_result.get_job().get_output_format()
job_result_id = job_result.get_id()
body = ""
if job_result_id != JobResult.ID_MISSING:
download_and_format_html = """
<a href="%(download_job_results_url)s?result_id=%(job_result_id)s&ln=%(language)s"><input type="button" value="%(label_download)s" class="formbutton"></a>
<strong>%(label_view_as)s</strong>
<a href="%(display_job_result_url)s?result_id=%(job_result_id)s&output_format=%(output_format_marcxml)s&ln=%(language)s">MARCXML</a>
<a href="%(display_job_result_url)s?result_id=%(job_result_id)s&output_format=%(output_format_marc)s&ln=%(language)s">MARC</a>
""" % self._html_escape_dictionary({
"label_download" : _("Download"),
"label_view_as" : _("View as: "),
"output_format_marcxml" : Job.OUTPUT_FORMAT_MARCXML,
"output_format_marc" : Job.OUTPUT_FORMAT_MARC,
"download_job_results_url" : self._DOWNLOAD_JOB_RESULT_URL,
"language" : language,
"display_job_result_url" : self._DISPLAY_JOB_RESULT_URL,
"job_result_id" : job_result_id
})
body += download_and_format_html
for query_result in queries_results:
query = query_result.get_query()
results = query_result.get_result(output_format)
html = """
<h2>%(name)s</h2>
<strong>%(query_label)s: </strong>%(search_criteria)s<br>
<strong>%(output_fields_label)s: </strong>%(output_fields)s<br>
<textarea rows="10" style="width: 100%%" wrap="off" readonly>%(results)s</textarea></td>
""" % self._html_escape_dictionary({
"query_label" : _("Query"),
"output_fields_label" : _("Output fields"),
"name" : query.get_name(),
"search_criteria" : query.get_search_criteria(),
"output_fields" : ",".join(query.get_output_fields()),
"results" : results
})
body += html
return body
def tmpl_display_job_history(self, job_results, language = CFG_SITE_LANG):
"""Creates a page displaying information about
the job results given as a parameter.
@param job_results: List of JobResult objects containing
information about the job results that have to be displayed
@param language: language of the page
@return: The HTML content of the page
"""
_ = gettext_set_language(language)
table_rows = ""
for current_job_result in job_results:
current_job = current_job_result.get_job()
# convert execution date into text proper to be shown to the user
execution_date_time = current_job_result.get_execution_date_time()
date = convert_datestruct_to_dategui(execution_date_time)
# obtain text corresponding to the frequency of execution
frequency = current_job.get_frequency()
frequency_text = self._get_frequency_text(frequency, language)
# set the status text
if current_job_result.STATUS_CODE_OK == current_job_result.get_status():
status = _("OK")
else:
status = _("Error")
records_found = current_job_result.get_number_of_records_found()
row = """<tr>
<td><a href="%(job_results_url)s?result_id=%(job_result_id)s&ln=%(language)s">%(job_name)s</a></td>
<td>%(job_frequency)s</td>
<td>%(execution_date)s</td>
<td><b>%(status)s</b>
<a href="%(display_job_result_url)s?result_id=%(job_result_id)s&ln=%(language)s">
<small>%(number_of_records_found)s %(label_records_found)s</small>
</a>
</td>
</tr>""" % self._html_escape_dictionary({
"job_name" : current_job.get_name(),
"job_frequency" : frequency_text,
"execution_date" : date,
"status" : status,
"number_of_records_found" : records_found,
"label_records_found" : _("records found"),
"job_results_url" : self._JOB_RESULTS_URL,
"display_job_result_url" : self._DISPLAY_JOB_RESULT_URL,
"language" : language,
"job_result_id" : current_job_result.get_id()
})
table_rows += row
body = """
<table class="spacedcells">
<th>%(label_job_name)s</th>
<th>%(label_job_frequency)s</th>
<th>%(label_execution_date)s</th>
<th>%(label_status)s</th>
%(table_rows)s
</table>
""" % {
"table_rows" : table_rows,
"label_job_name" : _("Job"),
"label_job_frequency" : _("Run"),
"label_execution_date" : _("Date"),
"label_status" : _("Status")
}
return body
def tmpl_display_job_result_information(self, job_result, language = CFG_SITE_LANG):
"""Creates a page with information about a given job result
@param job_result: JobResult object with containg the job result
@param language: language of the page
@return: The HTML content of the page
"""
_ = gettext_set_language(language)
table_rows = ""
for current_query_result in job_result.get_query_results():
current_query_name = current_query_result.get_query().get_name()
# set the status text
if current_query_result.STATUS_CODE_OK == current_query_result.get_status():
status = _("OK")
else:
status = _("Error")
records_found = current_query_result.get_number_of_records_found()
row = """<tr>
<td>%(query_name)s</td>
<td><b>%(status)s</b></td>
<td><small>%(number_of_records_found)s %(label_records_found)s</small></td>
</tr>""" % self._html_escape_dictionary({
"query_name" : current_query_name,
"status" : status,
"number_of_records_found" : records_found,
"label_records_found" : _("records found")
})
table_rows += row
number_of_all_records_found = job_result.get_number_of_records_found()
job_result_id = job_result.get_id()
final_row = """
<tr>
<td></td>
<td><b>%(label_total)s</b></td>
<td>
<a href="%(display_job_results_url)s?result_id=%(job_result_id)s&ln=%(language)s">
<b>%(number_of_all_records_found)s %(label_records_found)s</b>
</a>
</td>
</tr>""" % self._html_escape_dictionary({
"label_total" : _("Total"),
"number_of_all_records_found" : number_of_all_records_found,
"label_records_found" : _("records found"),
"display_job_results_url" : self._DISPLAY_JOB_RESULT_URL,
"language" : language,
"job_result_id" : job_result_id
})
table_rows += final_row
download_row = """
<tr>
<td></td><td></td><td>
<a href="%(download_job_results_url)s?result_id=%(job_result_id)s&ln=%(language)s">
<input type="button" value="%(label_download)s" class="formbutton">
</a>
</td>
</tr>""" % self._html_escape_dictionary({
"label_download" : _("Download"),
"download_job_results_url" : self._DOWNLOAD_JOB_RESULT_URL,
"language" : language,
"job_result_id" : job_result_id
})
table_rows += download_row
job_name = self._html_escape_content(job_result.get_job().get_name())
if(job_result.get_status() == job_result.STATUS_CODE_ERROR):
status_messasge = job_result.get_status_message()
else:
status_messasge = ""
status_messasge = self._html_escape_content(status_messasge)
body = """
<h2>%(job_name)s</h2>
<table class="spacedcells">
<th>%(label_query)s</th>
<th>%(label_status)s</th>
<th></th>
%(table_rows)s
</table>
<br>
<pre style="color: Red;">%(status_message)s</pre>
""" % {
"table_rows" : table_rows,
"label_query" : _("Query"),
"label_status" : _("Status"),
"job_name" : job_name,
"status_message" : status_messasge
}
return body
def _get_select_all_none_html(self, form_name, field_name, language = CFG_SITE_LANG):
"""Returns HTML providing Select All|None links
@param form_name: the name of the form containing the checkboxes
@param field_name: the name of the checkbox fields that will be affected
@param language: language for output
"""
_ = gettext_set_language(language)
output_html = """
%(label_select)s: <a href="javascript:SetAllCheckBoxes('%(form_name)s', '%(field_name)s', true);">%(label_all)s</a>, <a href="javascript:SetAllCheckBoxes('%(form_name)s', '%(field_name)s', false);">%(label_none)s</a>
"""% {
"label_select" : _("Select"),
"label_all" : _("All"),
"label_none" : _("None"),
"form_name" : form_name,
"field_name" : field_name
}
return output_html
def _get_frequency_text(self, frequency, language = CFG_SITE_LANG):
"""
Returns text representation of the frequency: Manually, Daily, Weekly, Monthly
@param frequency: integer containg the number of hours between every execution.
@param language: language for output
"""
_ = gettext_set_language(language)
if 0 == frequency:
frequency_text = _("Manually")
elif 24 == frequency:
frequency_text = _("Daily")
elif 168 == frequency:
frequency_text = _("Weekly")
elif 720 == frequency:
frequency_text = _("Monthly")
else:
frequency_text = "Every %s hours" % (frequency,)
return frequency_text
def _create_output_format_select_box(self, selected_value = 0):
"""
Creates a select box for output format of a job.
@param name: name of the control
@param language: language of the menu
@param selected_value: value selected in the control
@return: HTML string representing HTML select control.
"""
items = [("MARCXML", Job.OUTPUT_FORMAT_MARCXML),
("MARC", Job.OUTPUT_FORMAT_MARC)]
html_output = self._create_select_box("output_format", items, selected_value)
return html_output
def _create_frequency_select_box(self, name, selected_value = 0, language = CFG_SITE_LANG):
"""
Creates a select box for frequency of an action/task.
@param name: name of the control
@param language: language of the menu
@param selected_value: value selected in the control
@return: HTML string representing HTML select control.
"""
items = [(self._get_frequency_text(0, language), 0),
(self._get_frequency_text(24, language), 24),
(self._get_frequency_text(168, language), 168),
(self._get_frequency_text(720, language), 720)]
html_output = self._create_select_box(name, items, selected_value)
return html_output
def _create_select_box(self, name, items, selected_value = None):
""" Returns the HTML code for a select box.
@param name: the name of the control
@param items: list of (text, value) tuples where text is the text to be displayed
and value is the value corresponding to the text in the select box
e.g. [("first", 1), ("second", 2), ("third", 3)]
@param selected_value: the value that will be selected
in the select box.
"""
html_output = """<select name="%s">""" % name
for text, value in items:
if selected_value == value:
selected = 'selected="selected"'
else:
selected = ""
current_option = """<option value="%(value)s" %(selected)s>%(text)s</option>""" % self._html_escape_dictionary({
"value" : value,
"text" : text,
"selected" :selected
})
html_output += current_option
html_output += """</select>"""
return html_output
def _html_escape_dictionary(self, dictionaty_to_escape):
"""Escapes all the values in the dictionary and transform
them in strings that are safe to siplay in HTML page.
HTML special symbols are replaced with their sage equivalents.
@param dictionaty_to_escape: dictionary containing values
that have to be escaped.
@return: returns dictionary with the same keys where the
values are escaped strings"""
for key in dictionaty_to_escape:
value = "%s" % dictionaty_to_escape[key]
dictionaty_to_escape[key] = cgi.escape(value)
return dictionaty_to_escape
def _html_escape_content(self, content_to_escape):
"""Escapes the value given as parameter and
trasforms it to a string that is safe for display in HTML page.
@param content_to_escape: contains the content that have to be escaped.
@return: string containing the escaped content
"""
text_content = "%s" % content_to_escape
escaped_content = cgi.escape(text_content)
return escaped_content
| gpl-2.0 |
zhangyongfei/StudySkia | gm/rebaseline_server/compare_configs.py | 1 | 8543 | #!/usr/bin/python
"""
Copyright 2014 Google Inc.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
Compare GM results for two configs, across all builders.
"""
# System-level imports
import argparse
import logging
import time
# Must fix up PYTHONPATH before importing from within Skia
import fix_pythonpath # pylint: disable=W0611
# Imports from within Skia
from py.utils import url_utils
import gm_json
import imagediffdb
import imagepair
import imagepairset
import results
class ConfigComparisons(results.BaseComparisons):
"""Loads results from two different configurations into an ImagePairSet.
Loads actual and expected results from all builders, except for those skipped
by _ignore_builder().
"""
def __init__(self, configs, actuals_root=results.DEFAULT_ACTUALS_DIR,
generated_images_root=results.DEFAULT_GENERATED_IMAGES_ROOT,
diff_base_url=None, builder_regex_list=None):
"""
Args:
configs: (string, string) tuple; pair of configs to compare
actuals_root: root directory containing all actual-results.json files
generated_images_root: directory within which to create all pixel diffs;
if this directory does not yet exist, it will be created
diff_base_url: base URL within which the client should look for diff
images; if not specified, defaults to a "file:///" URL representation
of generated_images_root
builder_regex_list: List of regular expressions specifying which builders
we will process. If None, process all builders.
"""
time_start = int(time.time())
if builder_regex_list != None:
self.set_match_builders_pattern_list(builder_regex_list)
self._image_diff_db = imagediffdb.ImageDiffDB(generated_images_root)
self._diff_base_url = (
diff_base_url or
url_utils.create_filepath_url(generated_images_root))
self._actuals_root = actuals_root
self._load_config_pairs(configs)
self._timestamp = int(time.time())
logging.info('Results complete; took %d seconds.' %
(self._timestamp - time_start))
def _load_config_pairs(self, configs):
"""Loads the results of all tests, across all builders (based on the
files within self._actuals_root), compares them across two configs,
and stores the summary in self._results.
Args:
configs: tuple of strings; pair of configs to compare
"""
logging.info('Reading actual-results JSON files from %s...' %
self._actuals_root)
actual_builder_dicts = self._read_builder_dicts_from_root(
self._actuals_root)
configA, configB = configs
logging.info('Comparing configs %s and %s...' % (configA, configB))
all_image_pairs = imagepairset.ImagePairSet(
descriptions=configs,
diff_base_url=self._diff_base_url)
failing_image_pairs = imagepairset.ImagePairSet(
descriptions=configs,
diff_base_url=self._diff_base_url)
all_image_pairs.ensure_extra_column_values_in_summary(
column_id=results.KEY__EXTRACOLUMNS__RESULT_TYPE, values=[
results.KEY__RESULT_TYPE__FAILED,
results.KEY__RESULT_TYPE__NOCOMPARISON,
results.KEY__RESULT_TYPE__SUCCEEDED,
])
failing_image_pairs.ensure_extra_column_values_in_summary(
column_id=results.KEY__EXTRACOLUMNS__RESULT_TYPE, values=[
results.KEY__RESULT_TYPE__FAILED,
results.KEY__RESULT_TYPE__NOCOMPARISON,
])
builders = sorted(actual_builder_dicts.keys())
num_builders = len(builders)
builder_num = 0
for builder in builders:
builder_num += 1
logging.info('Generating pixel diffs for builder #%d of %d, "%s"...' %
(builder_num, num_builders, builder))
actual_results_for_this_builder = (
actual_builder_dicts[builder][gm_json.JSONKEY_ACTUALRESULTS])
for result_type in sorted(actual_results_for_this_builder.keys()):
results_of_this_type = actual_results_for_this_builder[result_type]
if not results_of_this_type:
continue
tests_found = set()
for image_name in sorted(results_of_this_type.keys()):
(test, _) = results.IMAGE_FILENAME_RE.match(image_name).groups()
tests_found.add(test)
for test in tests_found:
# Get image_relative_url (or None) for each of configA, configB
image_name_A = results.IMAGE_FILENAME_FORMATTER % (test, configA)
configA_image_relative_url = ConfigComparisons._create_relative_url(
hashtype_and_digest=results_of_this_type.get(image_name_A),
test_name=test)
image_name_B = results.IMAGE_FILENAME_FORMATTER % (test, configB)
configB_image_relative_url = ConfigComparisons._create_relative_url(
hashtype_and_digest=results_of_this_type.get(image_name_B),
test_name=test)
# If we have images for at least one of these two configs,
# add them to our list.
if configA_image_relative_url or configB_image_relative_url:
if configA_image_relative_url == configB_image_relative_url:
result_type = results.KEY__RESULT_TYPE__SUCCEEDED
elif not configA_image_relative_url:
result_type = results.KEY__RESULT_TYPE__NOCOMPARISON
elif not configB_image_relative_url:
result_type = results.KEY__RESULT_TYPE__NOCOMPARISON
else:
result_type = results.KEY__RESULT_TYPE__FAILED
extra_columns_dict = {
results.KEY__EXTRACOLUMNS__RESULT_TYPE: result_type,
results.KEY__EXTRACOLUMNS__BUILDER: builder,
results.KEY__EXTRACOLUMNS__TEST: test,
# TODO(epoger): Right now, the client UI crashes if it receives
# results that do not include a 'config' column.
# Until we fix that, keep the client happy.
results.KEY__EXTRACOLUMNS__CONFIG: 'TODO',
}
try:
image_pair = imagepair.ImagePair(
image_diff_db=self._image_diff_db,
base_url=gm_json.GM_ACTUALS_ROOT_HTTP_URL,
imageA_relative_url=configA_image_relative_url,
imageB_relative_url=configB_image_relative_url,
extra_columns=extra_columns_dict)
all_image_pairs.add_image_pair(image_pair)
if result_type != results.KEY__RESULT_TYPE__SUCCEEDED:
failing_image_pairs.add_image_pair(image_pair)
except (KeyError, TypeError):
logging.exception(
'got exception while creating ImagePair for test '
'"%s", builder "%s"' % (test, builder))
# pylint: disable=W0201
self._results = {
results.KEY__HEADER__RESULTS_ALL: all_image_pairs.as_dict(),
results.KEY__HEADER__RESULTS_FAILURES: failing_image_pairs.as_dict(),
}
def main():
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument(
'--actuals', default=results.DEFAULT_ACTUALS_DIR,
help='Directory containing all actual-result JSON files; defaults to '
'\'%(default)s\' .')
parser.add_argument(
'config', nargs=2,
help='Two configurations to compare (8888, gpu, etc.).')
parser.add_argument(
'--outfile', required=True,
help='File to write result summary into, in JSON format.')
parser.add_argument(
'--results', default=results.KEY__HEADER__RESULTS_FAILURES,
help='Which result types to include. Defaults to \'%(default)s\'; '
'must be one of ' +
str([results.KEY__HEADER__RESULTS_FAILURES,
results.KEY__HEADER__RESULTS_ALL]))
parser.add_argument(
'--workdir', default=results.DEFAULT_GENERATED_IMAGES_ROOT,
help='Directory within which to download images and generate diffs; '
'defaults to \'%(default)s\' .')
args = parser.parse_args()
results_obj = ConfigComparisons(configs=args.config,
actuals_root=args.actuals,
generated_images_root=args.workdir)
gm_json.WriteToFile(
results_obj.get_packaged_results_of_type(results_type=args.results),
args.outfile)
if __name__ == '__main__':
main()
| bsd-3-clause |
kevinmost/LiteSync | venv/lib/python2.7/distutils/__init__.py | 1211 | 3983 | import os
import sys
import warnings
import imp
import opcode # opcode is not a virtualenv module, so we can use it to find the stdlib
# Important! To work on pypy, this must be a module that resides in the
# lib-python/modified-x.y.z directory
dirname = os.path.dirname
distutils_path = os.path.join(os.path.dirname(opcode.__file__), 'distutils')
if os.path.normpath(distutils_path) == os.path.dirname(os.path.normpath(__file__)):
warnings.warn(
"The virtualenv distutils package at %s appears to be in the same location as the system distutils?")
else:
__path__.insert(0, distutils_path)
real_distutils = imp.load_module("_virtualenv_distutils", None, distutils_path, ('', '', imp.PKG_DIRECTORY))
# Copy the relevant attributes
try:
__revision__ = real_distutils.__revision__
except AttributeError:
pass
__version__ = real_distutils.__version__
from distutils import dist, sysconfig
try:
basestring
except NameError:
basestring = str
## patch build_ext (distutils doesn't know how to get the libs directory
## path on windows - it hardcodes the paths around the patched sys.prefix)
if sys.platform == 'win32':
from distutils.command.build_ext import build_ext as old_build_ext
class build_ext(old_build_ext):
def finalize_options (self):
if self.library_dirs is None:
self.library_dirs = []
elif isinstance(self.library_dirs, basestring):
self.library_dirs = self.library_dirs.split(os.pathsep)
self.library_dirs.insert(0, os.path.join(sys.real_prefix, "Libs"))
old_build_ext.finalize_options(self)
from distutils.command import build_ext as build_ext_module
build_ext_module.build_ext = build_ext
## distutils.dist patches:
old_find_config_files = dist.Distribution.find_config_files
def find_config_files(self):
found = old_find_config_files(self)
system_distutils = os.path.join(distutils_path, 'distutils.cfg')
#if os.path.exists(system_distutils):
# found.insert(0, system_distutils)
# What to call the per-user config file
if os.name == 'posix':
user_filename = ".pydistutils.cfg"
else:
user_filename = "pydistutils.cfg"
user_filename = os.path.join(sys.prefix, user_filename)
if os.path.isfile(user_filename):
for item in list(found):
if item.endswith('pydistutils.cfg'):
found.remove(item)
found.append(user_filename)
return found
dist.Distribution.find_config_files = find_config_files
## distutils.sysconfig patches:
old_get_python_inc = sysconfig.get_python_inc
def sysconfig_get_python_inc(plat_specific=0, prefix=None):
if prefix is None:
prefix = sys.real_prefix
return old_get_python_inc(plat_specific, prefix)
sysconfig_get_python_inc.__doc__ = old_get_python_inc.__doc__
sysconfig.get_python_inc = sysconfig_get_python_inc
old_get_python_lib = sysconfig.get_python_lib
def sysconfig_get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
if standard_lib and prefix is None:
prefix = sys.real_prefix
return old_get_python_lib(plat_specific, standard_lib, prefix)
sysconfig_get_python_lib.__doc__ = old_get_python_lib.__doc__
sysconfig.get_python_lib = sysconfig_get_python_lib
old_get_config_vars = sysconfig.get_config_vars
def sysconfig_get_config_vars(*args):
real_vars = old_get_config_vars(*args)
if sys.platform == 'win32':
lib_dir = os.path.join(sys.real_prefix, "libs")
if isinstance(real_vars, dict) and 'LIBDIR' not in real_vars:
real_vars['LIBDIR'] = lib_dir # asked for all
elif isinstance(real_vars, list) and 'LIBDIR' in args:
real_vars = real_vars + [lib_dir] # asked for list
return real_vars
sysconfig_get_config_vars.__doc__ = old_get_config_vars.__doc__
sysconfig.get_config_vars = sysconfig_get_config_vars
| gpl-3.0 |
fredericlepied/ansible | lib/ansible/modules/files/stat.py | 13 | 19405 | #!/usr/bin/python
# 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/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: stat
version_added: "1.3"
short_description: Retrieve file or file system status
description:
- Retrieves facts for a file similar to the linux/unix 'stat' command.
- For Windows targets, use the M(win_stat) module instead.
options:
path:
description:
- The full path of the file/object to get the facts of.
required: true
follow:
description:
- Whether to follow symlinks.
choices: [ 'no', 'yes' ]
default: 'no'
get_md5:
description:
- Whether to return the md5 sum of the file.
- Will return None if not a regular file or if we're
unable to use md5 (Common for FIPS-140 compliant systems).
choices: [ 'no', 'yes' ]
default: 'yes'
get_checksum:
description:
- Whether to return a checksum of the file (default sha1).
choices: [ 'no', 'yes' ]
default: 'yes'
version_added: "1.8"
checksum_algorithm:
description:
- Algorithm to determine checksum of file. Will throw an error if the
host is unable to use specified algorithm.
choices: [ sha1, sha224, sha256, sha384, sha512 ]
default: sha1
aliases: [ checksum, checksum_algo ]
version_added: "2.0"
get_mime:
description:
- Use file magic and return data about the nature of the file. this uses
the 'file' utility found on most Linux/Unix systems.
- This will add both `mime_type` and 'charset' fields to the return, if possible.
- In 2.3 this option changed from 'mime' to 'get_mime' and the default changed to 'Yes'.
choices: [ 'no', 'yes' ]
default: 'yes'
version_added: "2.1"
aliases: [ mime, mime_type, mime-type ]
get_attributes:
description:
- Get file attributes using lsattr tool if present.
choices: [ 'no', 'yes' ]
default: 'yes'
version_added: "2.3"
aliases: [ attr, attributes ]
notes:
- For Windows targets, use the M(win_stat) module instead.
author: Bruce Pennypacker (@bpennypacker)
'''
EXAMPLES = '''
# Obtain the stats of /etc/foo.conf, and check that the file still belongs
# to 'root'. Fail otherwise.
- stat:
path: /etc/foo.conf
register: st
- fail:
msg: "Whoops! file ownership has changed"
when: st.stat.pw_name != 'root'
# Determine if a path exists and is a symlink. Note that if the path does
# not exist, and we test sym.stat.islnk, it will fail with an error. So
# therefore, we must test whether it is defined.
# Run this to understand the structure, the skipped ones do not pass the
# check performed by 'when'
- stat:
path: /path/to/something
register: sym
- debug:
msg: "islnk isn't defined (path doesn't exist)"
when: sym.stat.islnk is not defined
- debug:
msg: "islnk is defined (path must exist)"
when: sym.stat.islnk is defined
- debug:
msg: "Path exists and is a symlink"
when: sym.stat.islnk is defined and sym.stat.islnk
- debug:
msg: "Path exists and isn't a symlink"
when: sym.stat.islnk is defined and sym.stat.islnk == False
# Determine if a path exists and is a directory. Note that we need to test
# both that p.stat.isdir actually exists, and also that it's set to true.
- stat:
path: /path/to/something
register: p
- debug:
msg: "Path exists and is a directory"
when: p.stat.isdir is defined and p.stat.isdir
# Don't do md5 checksum
- stat:
path: /path/to/myhugefile
get_md5: no
# Use sha256 to calculate checksum
- stat:
path: /path/to/something
checksum_algorithm: sha256
'''
RETURN = r'''
stat:
description: dictionary containing all the stat data, some platforms might add additional fields
returned: success
type: complex
contains:
exists:
description: if the destination path actually exists or not
returned: success
type: boolean
sample: True
path:
description: The full path of the file/object to get the facts of
returned: success and if path exists
type: string
sample: '/path/to/file'
mode:
description: Unix permissions of the file in octal
returned: success, path exists and user can read stats
type: octal
sample: 1755
isdir:
description: Tells you if the path is a directory
returned: success, path exists and user can read stats
type: boolean
sample: False
ischr:
description: Tells you if the path is a character device
returned: success, path exists and user can read stats
type: boolean
sample: False
isblk:
description: Tells you if the path is a block device
returned: success, path exists and user can read stats
type: boolean
sample: False
isreg:
description: Tells you if the path is a regular file
returned: success, path exists and user can read stats
type: boolean
sample: True
isfifo:
description: Tells you if the path is a named pipe
returned: success, path exists and user can read stats
type: boolean
sample: False
islnk:
description: Tells you if the path is a symbolic link
returned: success, path exists and user can read stats
type: boolean
sample: False
issock:
description: Tells you if the path is a unix domain socket
returned: success, path exists and user can read stats
type: boolean
sample: False
uid:
description: Numeric id representing the file owner
returned: success, path exists and user can read stats
type: int
sample: 1003
gid:
description: Numeric id representing the group of the owner
returned: success, path exists and user can read stats
type: int
sample: 1003
size:
description: Size in bytes for a plain file, amount of data for some special files
returned: success, path exists and user can read stats
type: int
sample: 203
inode:
description: Inode number of the path
returned: success, path exists and user can read stats
type: int
sample: 12758
dev:
description: Device the inode resides on
returned: success, path exists and user can read stats
type: int
sample: 33
nlink:
description: Number of links to the inode (hard links)
returned: success, path exists and user can read stats
type: int
sample: 1
atime:
description: Time of last access
returned: success, path exists and user can read stats
type: float
sample: 1424348972.575
mtime:
description: Time of last modification
returned: success, path exists and user can read stats
type: float
sample: 1424348972.575
ctime:
description: Time of last metadata update or creation (depends on OS)
returned: success, path exists and user can read stats
type: float
sample: 1424348972.575
wusr:
description: Tells you if the owner has write permission
returned: success, path exists and user can read stats
type: boolean
sample: True
rusr:
description: Tells you if the owner has read permission
returned: success, path exists and user can read stats
type: boolean
sample: True
xusr:
description: Tells you if the owner has execute permission
returned: success, path exists and user can read stats
type: boolean
sample: True
wgrp:
description: Tells you if the owner's group has write permission
returned: success, path exists and user can read stats
type: boolean
sample: False
rgrp:
description: Tells you if the owner's group has read permission
returned: success, path exists and user can read stats
type: boolean
sample: True
xgrp:
description: Tells you if the owner's group has execute permission
returned: success, path exists and user can read stats
type: boolean
sample: True
woth:
description: Tells you if others have write permission
returned: success, path exists and user can read stats
type: boolean
sample: False
roth:
description: Tells you if others have read permission
returned: success, path exists and user can read stats
type: boolean
sample: True
xoth:
description: Tells you if others have execute permission
returned: success, path exists and user can read stats
type: boolean
sample: True
isuid:
description: Tells you if the invoking user's id matches the owner's id
returned: success, path exists and user can read stats
type: boolean
sample: False
isgid:
description: Tells you if the invoking user's group id matches the owner's group id
returned: success, path exists and user can read stats
type: boolean
sample: False
lnk_source:
description: Target of the symlink normalized for the remote filesystem
returned: success, path exists and user can read stats and the path is a symbolic link
type: string
sample: /home/foobar/21102015-1445431274-908472971
lnk_target:
description: Target of the symlink. Note that relative paths remain relative
returned: success, path exists and user can read stats and the path is a symbolic link
type: string
sample: ../foobar/21102015-1445431274-908472971
version_added: 2.4
md5:
description: md5 hash of the path
returned: success, path exists and user can read stats and path
supports hashing and md5 is supported
type: string
sample: f88fa92d8cf2eeecf4c0a50ccc96d0c0
checksum:
description: hash of the path
returned: success, path exists, user can read stats, path supports
hashing and supplied checksum algorithm is available
type: string
sample: 50ba294cdf28c0d5bcde25708df53346825a429f
pw_name:
description: User name of owner
returned: success, path exists and user can read stats and installed python supports it
type: string
sample: httpd
gr_name:
description: Group name of owner
returned: success, path exists and user can read stats and installed python supports it
type: string
sample: www-data
mime_type:
description: file magic data or mime-type
returned: success, path exists and user can read stats and
installed python supports it and the `mime` option was true, will
return 'unknown' on error.
type: string
sample: PDF document, version 1.2
charset:
description: file character set or encoding
returned: success, path exists and user can read stats and
installed python supports it and the `mime` option was true, will
return 'unknown' on error.
type: string
sample: us-ascii
readable:
description: Tells you if the invoking user has the right to read the path
returned: success, path exists and user can read the path
type: boolean
sample: False
version_added: 2.2
writeable:
description: Tells you if the invoking user has the right to write the path
returned: success, path exists and user can write the path
type: boolean
sample: False
version_added: 2.2
executable:
description: Tells you if the invoking user has the execute the path
returned: success, path exists and user can execute the path
type: boolean
sample: False
version_added: 2.2
attributes:
description: list of file attributes
returned: success, path exists and user can execute the path
type: list
sample: [ immutable, extent ]
version_added: 2.3
'''
import errno
import grp
import os
import pwd
import stat
# import module snippets
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils._text import to_bytes
def format_output(module, path, st):
mode = st.st_mode
# back to ansible
output = dict(
exists=True,
path=path,
mode="%04o" % stat.S_IMODE(mode),
isdir=stat.S_ISDIR(mode),
ischr=stat.S_ISCHR(mode),
isblk=stat.S_ISBLK(mode),
isreg=stat.S_ISREG(mode),
isfifo=stat.S_ISFIFO(mode),
islnk=stat.S_ISLNK(mode),
issock=stat.S_ISSOCK(mode),
uid=st.st_uid,
gid=st.st_gid,
size=st.st_size,
inode=st.st_ino,
dev=st.st_dev,
nlink=st.st_nlink,
atime=st.st_atime,
mtime=st.st_mtime,
ctime=st.st_ctime,
wusr=bool(mode & stat.S_IWUSR),
rusr=bool(mode & stat.S_IRUSR),
xusr=bool(mode & stat.S_IXUSR),
wgrp=bool(mode & stat.S_IWGRP),
rgrp=bool(mode & stat.S_IRGRP),
xgrp=bool(mode & stat.S_IXGRP),
woth=bool(mode & stat.S_IWOTH),
roth=bool(mode & stat.S_IROTH),
xoth=bool(mode & stat.S_IXOTH),
isuid=bool(mode & stat.S_ISUID),
isgid=bool(mode & stat.S_ISGID),
)
# Platform dependent flags:
for other in [
# Some Linux
('st_blocks', 'blocks'),
('st_blksize', 'block_size'),
('st_rdev', 'device_type'),
('st_flags', 'flags'),
# Some Berkley based
('st_gen', 'generation'),
('st_birthtime', 'birthtime'),
# RISCOS
('st_ftype', 'file_type'),
('st_attrs', 'attrs'),
('st_obtype', 'object_type'),
# OS X
('st_rsize', 'real_size'),
('st_creator', 'creator'),
('st_type', 'file_type'),
]:
if hasattr(st, other[0]):
output[other[1]] = getattr(st, other[0])
return output
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(required=True, type='path'),
follow=dict(type='bool', default='no'),
get_md5=dict(type='bool', default='yes'),
get_checksum=dict(type='bool', default='yes'),
get_mime=dict(type='bool', default='yes', aliases=['mime', 'mime_type', 'mime-type']),
get_attributes=dict(type='bool', default='yes', aliases=['attr', 'attributes']),
checksum_algorithm=dict(type='str', default='sha1',
choices=['sha1', 'sha224', 'sha256', 'sha384', 'sha512'],
aliases=['checksum', 'checksum_algo']),
),
supports_check_mode=True,
)
path = module.params.get('path')
b_path = to_bytes(path, errors='surrogate_or_strict')
follow = module.params.get('follow')
get_mime = module.params.get('get_mime')
get_attr = module.params.get('get_attributes')
get_md5 = module.params.get('get_md5')
get_checksum = module.params.get('get_checksum')
checksum_algorithm = module.params.get('checksum_algorithm')
# main stat data
try:
if follow:
st = os.stat(b_path)
else:
st = os.lstat(b_path)
except OSError:
e = get_exception()
if e.errno == errno.ENOENT:
output = {'exists': False}
module.exit_json(changed=False, stat=output)
module.fail_json(msg=e.strerror)
# process base results
output = format_output(module, path, st)
# resolved permissions
for perm in [('readable', os.R_OK), ('writeable', os.W_OK), ('executable', os.X_OK)]:
output[perm[0]] = os.access(b_path, perm[1])
# symlink info
if output.get('islnk'):
output['lnk_source'] = os.path.realpath(b_path)
output['lnk_target'] = os.readlink(b_path)
try: # user data
pw = pwd.getpwuid(st.st_uid)
output['pw_name'] = pw.pw_name
except:
pass
try: # group data
grp_info = grp.getgrgid(st.st_gid)
output['gr_name'] = grp_info.gr_name
except:
pass
# checksums
if output.get('isreg') and output.get('readable'):
if get_md5:
# Will fail on FIPS-140 compliant systems
try:
output['md5'] = module.md5(b_path)
except ValueError:
output['md5'] = None
if get_checksum:
output['checksum'] = module.digest_from_file(b_path, checksum_algorithm)
# try to get mime data if requested
if get_mime:
output['mimetype'] = output['charset'] = 'unknown'
mimecmd = module.get_bin_path('file')
if mimecmd:
mimecmd = [mimecmd, '-i', b_path]
try:
rc, out, err = module.run_command(mimecmd)
if rc == 0:
mimetype, charset = out.split(':')[1].split(';')
output['mimetype'] = mimetype.strip()
output['charset'] = charset.split('=')[1].strip()
except:
pass
# try to get attr data
if get_attr:
output['version'] = None
output['attributes'] = []
output['attr_flags'] = ''
out = module.get_file_attributes(b_path)
for x in ('version', 'attributes', 'attr_flags'):
if x in out:
output[x] = out[x]
module.exit_json(changed=False, stat=output)
if __name__ == '__main__':
main()
| gpl-3.0 |
Zyell/home-assistant | homeassistant/components/influxdb.py | 3 | 3611 | """
A component which allows you to send data to an Influx database.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/influxdb/
"""
import logging
import homeassistant.util as util
from homeassistant.const import (EVENT_STATE_CHANGED, STATE_UNAVAILABLE,
STATE_UNKNOWN)
from homeassistant.helpers import state as state_helper
from homeassistant.helpers import validate_config
_LOGGER = logging.getLogger(__name__)
DOMAIN = "influxdb"
DEPENDENCIES = []
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 8086
DEFAULT_DATABASE = 'home_assistant'
DEFAULT_SSL = False
DEFAULT_VERIFY_SSL = False
REQUIREMENTS = ['influxdb==2.12.0']
CONF_HOST = 'host'
CONF_PORT = 'port'
CONF_DB_NAME = 'database'
CONF_USERNAME = 'username'
CONF_PASSWORD = 'password'
CONF_SSL = 'ssl'
CONF_VERIFY_SSL = 'verify_ssl'
CONF_BLACKLIST = 'blacklist'
# pylint: disable=too-many-locals
def setup(hass, config):
"""Setup the InfluxDB component."""
from influxdb import InfluxDBClient, exceptions
if not validate_config(config, {DOMAIN: ['host',
CONF_USERNAME,
CONF_PASSWORD]}, _LOGGER):
return False
conf = config[DOMAIN]
host = conf[CONF_HOST]
port = util.convert(conf.get(CONF_PORT), int, DEFAULT_PORT)
database = util.convert(conf.get(CONF_DB_NAME), str, DEFAULT_DATABASE)
username = util.convert(conf.get(CONF_USERNAME), str)
password = util.convert(conf.get(CONF_PASSWORD), str)
ssl = util.convert(conf.get(CONF_SSL), bool, DEFAULT_SSL)
verify_ssl = util.convert(conf.get(CONF_VERIFY_SSL), bool,
DEFAULT_VERIFY_SSL)
blacklist = conf.get(CONF_BLACKLIST, [])
try:
influx = InfluxDBClient(host=host, port=port, username=username,
password=password, database=database,
ssl=ssl, verify_ssl=verify_ssl)
influx.query("select * from /.*/ LIMIT 1;")
except exceptions.InfluxDBClientError as exc:
_LOGGER.error("Database host is not accessible due to '%s', please "
"check your entries in the configuration file and that "
"the database exists and is READ/WRITE.", exc)
return False
def influx_event_listener(event):
"""Listen for new messages on the bus and sends them to Influx."""
state = event.data.get('new_state')
if state is None or state.state in (
STATE_UNKNOWN, '', STATE_UNAVAILABLE) or \
state.entity_id in blacklist:
return
try:
_state = state_helper.state_as_number(state)
except ValueError:
_state = state.state
measurement = state.attributes.get('unit_of_measurement')
if measurement in (None, ''):
measurement = state.entity_id
json_body = [
{
'measurement': measurement,
'tags': {
'domain': state.domain,
'entity_id': state.object_id,
},
'time': event.time_fired,
'fields': {
'value': _state,
}
}
]
try:
influx.write_points(json_body)
except exceptions.InfluxDBClientError:
_LOGGER.exception('Error saving event "%s" to InfluxDB', json_body)
hass.bus.listen(EVENT_STATE_CHANGED, influx_event_listener)
return True
| mit |
yograterol/django | django/db/migrations/topological_sort.py | 538 | 1129 | def topological_sort_as_sets(dependency_graph):
"""Variation of Kahn's algorithm (1962) that returns sets.
Takes a dependency graph as a dictionary of node => dependencies.
Yields sets of items in topological order, where the first set contains
all nodes without dependencies, and each following set contains all
nodes that depend on the nodes in the previously yielded sets.
"""
todo = dependency_graph.copy()
while todo:
current = {node for node, deps in todo.items() if len(deps) == 0}
if not current:
raise ValueError('Cyclic dependency in graph: {}'.format(
', '.join(repr(x) for x in todo.items())))
yield current
# remove current from todo's nodes & dependencies
todo = {node: (dependencies - current) for node, dependencies in
todo.items() if node not in current}
def stable_topological_sort(l, dependency_graph):
result = []
for layer in topological_sort_as_sets(dependency_graph):
for node in l:
if node in layer:
result.append(node)
return result
| bsd-3-clause |
ivanov/urwid | urwid/escape.py | 7 | 13820 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Urwid escape sequences common to curses_display and raw_display
# Copyright (C) 2004-2011 Ian Ward
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: http://excess.org/urwid/
"""
Terminal Escape Sequences for input and display
"""
import re
try:
from urwid import str_util
except ImportError:
from urwid import old_str_util as str_util
from urwid.compat import bytes, bytes3
within_double_byte = str_util.within_double_byte
SO = "\x0e"
SI = "\x0f"
IBMPC_ON = "\x1b[11m"
IBMPC_OFF = "\x1b[10m"
DEC_TAG = "0"
DEC_SPECIAL_CHARS = u'▮◆▒␉␌␍␊°±␋┘┐┌└┼⎺⎻─⎼⎽├┤┴┬│≤≥π≠£·'
ALT_DEC_SPECIAL_CHARS = u"_`abcdefghijklmnopqrstuvwxyz{|}~"
DEC_SPECIAL_CHARMAP = {}
assert len(DEC_SPECIAL_CHARS) == len(ALT_DEC_SPECIAL_CHARS), repr((DEC_SPECIAL_CHARS, ALT_DEC_SPECIAL_CHARS))
for c, alt in zip(DEC_SPECIAL_CHARS, ALT_DEC_SPECIAL_CHARS):
DEC_SPECIAL_CHARMAP[ord(c)] = SO + alt + SI
SAFE_ASCII_DEC_SPECIAL_RE = re.compile(u"^[ -~%s]*$" % DEC_SPECIAL_CHARS)
DEC_SPECIAL_RE = re.compile(u"[%s]" % DEC_SPECIAL_CHARS)
###################
## Input sequences
###################
class MoreInputRequired(Exception):
pass
def escape_modifier( digit ):
mode = ord(digit) - ord("1")
return "shift "*(mode&1) + "meta "*((mode&2)//2) + "ctrl "*((mode&4)//4)
input_sequences = [
('[A','up'),('[B','down'),('[C','right'),('[D','left'),
('[E','5'),('[F','end'),('[G','5'),('[H','home'),
('[1~','home'),('[2~','insert'),('[3~','delete'),('[4~','end'),
('[5~','page up'),('[6~','page down'),
('[7~','home'),('[8~','end'),
('[[A','f1'),('[[B','f2'),('[[C','f3'),('[[D','f4'),('[[E','f5'),
('[11~','f1'),('[12~','f2'),('[13~','f3'),('[14~','f4'),
('[15~','f5'),('[17~','f6'),('[18~','f7'),('[19~','f8'),
('[20~','f9'),('[21~','f10'),('[23~','f11'),('[24~','f12'),
('[25~','f13'),('[26~','f14'),('[28~','f15'),('[29~','f16'),
('[31~','f17'),('[32~','f18'),('[33~','f19'),('[34~','f20'),
('OA','up'),('OB','down'),('OC','right'),('OD','left'),
('OH','home'),('OF','end'),
('OP','f1'),('OQ','f2'),('OR','f3'),('OS','f4'),
('Oo','/'),('Oj','*'),('Om','-'),('Ok','+'),
('[Z','shift tab'),
('On', '.'),
] + [
(prefix + letter, modifier + key)
for prefix, modifier in zip('O[', ('meta ', 'shift '))
for letter, key in zip('abcd', ('up', 'down', 'right', 'left'))
] + [
("[" + digit + symbol, modifier + key)
for modifier, symbol in zip(('shift ', 'meta '), '$^')
for digit, key in zip('235678',
('insert', 'delete', 'page up', 'page down', 'home', 'end'))
] + [
('O' + chr(ord('p')+n), str(n)) for n in range(10)
] + [
# modified cursor keys + home, end, 5 -- [#X and [1;#X forms
(prefix+digit+letter, escape_modifier(digit) + key)
for prefix in "[","[1;"
for digit in "12345678"
for letter,key in zip("ABCDEFGH",
('up','down','right','left','5','end','5','home'))
] + [
# modified F1-F4 keys -- O#X form
("O"+digit+letter, escape_modifier(digit) + key)
for digit in "12345678"
for letter,key in zip("PQRS",('f1','f2','f3','f4'))
] + [
# modified F1-F13 keys -- [XX;#~ form
("["+str(num)+";"+digit+"~", escape_modifier(digit) + key)
for digit in "12345678"
for num,key in zip(
(3,5,6,11,12,13,14,15,17,18,19,20,21,23,24,25,26,28,29,31,32,33,34),
('delete', 'page up', 'page down',
'f1','f2','f3','f4','f5','f6','f7','f8','f9','f10','f11',
'f12','f13','f14','f15','f16','f17','f18','f19','f20'))
] + [
# mouse reporting (special handling done in KeyqueueTrie)
('[M', 'mouse'),
# report status response
('[0n', 'status ok')
]
class KeyqueueTrie(object):
def __init__( self, sequences ):
self.data = {}
for s, result in sequences:
assert type(result) != dict
self.add(self.data, s, result)
def add(self, root, s, result):
assert type(root) == dict, "trie conflict detected"
assert len(s) > 0, "trie conflict detected"
if root.has_key(ord(s[0])):
return self.add(root[ord(s[0])], s[1:], result)
if len(s)>1:
d = {}
root[ord(s[0])] = d
return self.add(d, s[1:], result)
root[ord(s)] = result
def get(self, keys, more_available):
result = self.get_recurse(self.data, keys, more_available)
if not result:
result = self.read_cursor_position(keys, more_available)
return result
def get_recurse(self, root, keys, more_available):
if type(root) != dict:
if root == "mouse":
return self.read_mouse_info(keys,
more_available)
return (root, keys)
if not keys:
# get more keys
if more_available:
raise MoreInputRequired()
return None
if not root.has_key(keys[0]):
return None
return self.get_recurse(root[keys[0]], keys[1:], more_available)
def read_mouse_info(self, keys, more_available):
if len(keys) < 3:
if more_available:
raise MoreInputRequired()
return None
b = keys[0] - 32
x, y = (keys[1] - 33)%256, (keys[2] - 33)%256 # supports 0-255
prefix = ""
if b & 4: prefix = prefix + "shift "
if b & 8: prefix = prefix + "meta "
if b & 16: prefix = prefix + "ctrl "
if (b & MOUSE_MULTIPLE_CLICK_MASK)>>9 == 1: prefix = prefix + "double "
if (b & MOUSE_MULTIPLE_CLICK_MASK)>>9 == 2: prefix = prefix + "triple "
# 0->1, 1->2, 2->3, 64->4, 65->5
button = ((b&64)/64*3) + (b & 3) + 1
if b & 3 == 3:
action = "release"
button = 0
elif b & MOUSE_RELEASE_FLAG:
action = "release"
elif b & MOUSE_DRAG_FLAG:
action = "drag"
elif b & MOUSE_MULTIPLE_CLICK_MASK:
action = "click"
else:
action = "press"
return ( (prefix + "mouse " + action, button, x, y), keys[3:] )
def read_cursor_position(self, keys, more_available):
"""
Interpret cursor position information being sent by the
user's terminal. Returned as ('cursor position', x, y)
where (x, y) == (0, 0) is the top left of the screen.
"""
if not keys:
if more_available:
raise MoreInputRequired()
return None
if keys[0] != ord('['):
return None
# read y value
y = 0
i = 1
for k in keys[i:]:
i += 1
if k == ord(';'):
if not y:
return None
break
if k < ord('0') or k > ord('9'):
return None
if not y and k == ord('0'):
return None
y = y * 10 + k - ord('0')
if not keys[i:]:
if more_available:
raise MoreInputRequired()
return None
# read x value
x = 0
for k in keys[i:]:
i += 1
if k == ord('R'):
if not x:
return None
return (("cursor position", x-1, y-1), keys[i:])
if k < ord('0') or k > ord('9'):
return None
if not x and k == ord('0'):
return None
x = x * 10 + k - ord('0')
if not keys[i:]:
if more_available:
raise MoreInputRequired()
return None
# This is added to button value to signal mouse release by curses_display
# and raw_display when we know which button was released. NON-STANDARD
MOUSE_RELEASE_FLAG = 2048
# This 2-bit mask is used to check if the mouse release from curses or gpm
# is a double or triple release. 00 means single click, 01 double,
# 10 triple. NON-STANDARD
MOUSE_MULTIPLE_CLICK_MASK = 1536
# This is added to button value at mouse release to differentiate between
# single, double and triple press. Double release adds this times one,
# triple release adds this times two. NON-STANDARD
MOUSE_MULTIPLE_CLICK_FLAG = 512
# xterm adds this to the button value to signal a mouse drag event
MOUSE_DRAG_FLAG = 32
#################################################
# Build the input trie from input_sequences list
input_trie = KeyqueueTrie(input_sequences)
#################################################
_keyconv = {
-1:None,
8:'backspace',
9:'tab',
10:'enter',
13:'enter',
127:'backspace',
# curses-only keycodes follow.. (XXX: are these used anymore?)
258:'down',
259:'up',
260:'left',
261:'right',
262:'home',
263:'backspace',
265:'f1', 266:'f2', 267:'f3', 268:'f4',
269:'f5', 270:'f6', 271:'f7', 272:'f8',
273:'f9', 274:'f10', 275:'f11', 276:'f12',
277:'shift f1', 278:'shift f2', 279:'shift f3', 280:'shift f4',
281:'shift f5', 282:'shift f6', 283:'shift f7', 284:'shift f8',
285:'shift f9', 286:'shift f10', 287:'shift f11', 288:'shift f12',
330:'delete',
331:'insert',
338:'page down',
339:'page up',
343:'enter', # on numpad
350:'5', # on numpad
360:'end',
}
def process_keyqueue(codes, more_available):
"""
codes -- list of key codes
more_available -- if True then raise MoreInputRequired when in the
middle of a character sequence (escape/utf8/wide) and caller
will attempt to send more key codes on the next call.
returns (list of input, list of remaining key codes).
"""
code = codes[0]
if code >= 32 and code <= 126:
key = chr(code)
return [key], codes[1:]
if _keyconv.has_key(code):
return [_keyconv[code]], codes[1:]
if code >0 and code <27:
return ["ctrl %s" % chr(ord('a')+code-1)], codes[1:]
if code >27 and code <32:
return ["ctrl %s" % chr(ord('A')+code-1)], codes[1:]
em = str_util.get_byte_encoding()
if (em == 'wide' and code < 256 and
within_double_byte(chr(code),0,0)):
if not codes[1:]:
if more_available:
raise MoreInputRequired()
if codes[1:] and codes[1] < 256:
db = chr(code)+chr(codes[1])
if within_double_byte(db, 0, 1):
return [db], codes[2:]
if em == 'utf8' and code>127 and code<256:
if code & 0xe0 == 0xc0: # 2-byte form
need_more = 1
elif code & 0xf0 == 0xe0: # 3-byte form
need_more = 2
elif code & 0xf8 == 0xf0: # 4-byte form
need_more = 3
else:
return ["<%d>"%code], codes[1:]
for i in range(need_more):
if len(codes)-1 <= i:
if more_available:
raise MoreInputRequired()
else:
return ["<%d>"%code], codes[1:]
k = codes[i+1]
if k>256 or k&0xc0 != 0x80:
return ["<%d>"%code], codes[1:]
s = bytes3(codes[:need_more+1])
assert isinstance(s, bytes)
try:
return [s.decode("utf-8")], codes[need_more+1:]
except UnicodeDecodeError:
return ["<%d>"%code], codes[1:]
if code >127 and code <256:
key = chr(code)
return [key], codes[1:]
if code != 27:
return ["<%d>"%code], codes[1:]
result = input_trie.get(codes[1:], more_available)
if result is not None:
result, remaining_codes = result
return [result], remaining_codes
if codes[1:]:
# Meta keys -- ESC+Key form
run, remaining_codes = process_keyqueue(codes[1:],
more_available)
if run[0] == "esc" or run[0].find("meta ") >= 0:
return ['esc']+run, remaining_codes
return ['meta '+run[0]]+run[1:], remaining_codes
return ['esc'], codes[1:]
####################
## Output sequences
####################
ESC = "\x1b"
CURSOR_HOME = ESC+"[H"
CURSOR_HOME_COL = "\r"
APP_KEYPAD_MODE = ESC+"="
NUM_KEYPAD_MODE = ESC+">"
SWITCH_TO_ALTERNATE_BUFFER = ESC+"7"+ESC+"[?47h"
RESTORE_NORMAL_BUFFER = ESC+"[?47l"+ESC+"8"
#RESET_SCROLL_REGION = ESC+"[;r"
#RESET = ESC+"c"
REPORT_STATUS = ESC + "[5n"
REPORT_CURSOR_POSITION = ESC+"[6n"
INSERT_ON = ESC + "[4h"
INSERT_OFF = ESC + "[4l"
def set_cursor_position( x, y ):
assert type(x) == int
assert type(y) == int
return ESC+"[%d;%dH" %(y+1, x+1)
def move_cursor_right(x):
if x < 1: return ""
return ESC+"[%dC" % x
def move_cursor_up(x):
if x < 1: return ""
return ESC+"[%dA" % x
def move_cursor_down(x):
if x < 1: return ""
return ESC+"[%dB" % x
HIDE_CURSOR = ESC+"[?25l"
SHOW_CURSOR = ESC+"[?25h"
MOUSE_TRACKING_ON = ESC+"[?1000h"+ESC+"[?1002h"
MOUSE_TRACKING_OFF = ESC+"[?1002l"+ESC+"[?1000l"
DESIGNATE_G1_SPECIAL = ESC+")0"
ERASE_IN_LINE_RIGHT = ESC+"[K"
| lgpl-2.1 |
LLNL/spack | var/spack/repos/builtin/packages/polymake/package.py | 5 | 1848 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Polymake(Package):
"""polymake is open source software for research in polyhedral geometry"""
homepage = "https://polymake.org/doku.php"
url = "https://polymake.org/lib/exe/fetch.php/download/polymake-3.0r1.tar.bz2"
version('3.5', sha256='c649f8536ccef5a5e22b82c514a09278ebcd99d0815aa7170461fe12843109bd')
version('3.0r2', sha256='e7c0f8e3a45ea288d2fb4ae781a1dcea913ef9c275fed401632cdb11a672d6dc')
version('3.0r1', sha256='cdc223716b1cc3f4f3cc126089a438f9d12390caeed78291a87565717c7b504d')
# Note: Could also be built with nauty instead of bliss
depends_on("bliss")
depends_on("boost")
depends_on("cddlib")
depends_on("gmp")
depends_on("lrslib")
depends_on("mpfr")
depends_on("ninja", type='build', when='@3.2:')
depends_on("perl")
depends_on("perl-json")
depends_on("perl-termreadkey")
depends_on("perl-term-readline-gnu")
depends_on("perl-xml-libxml")
depends_on("perl-xml-libxslt")
depends_on("perl-xml-writer")
depends_on("ppl")
depends_on("ppl@1.2:", when='@3.2:')
depends_on("readline")
def install(self, spec, prefix):
configure("--prefix=%s" % prefix,
"--with-bliss=%s" % spec["bliss"].prefix,
"--with-boost=%s" % spec["boost"].prefix,
"--with-cdd=%s" % spec["cddlib"].prefix,
"--with-gmp=%s" % spec["gmp"].prefix,
"--with-lrs=%s" % spec["lrslib"].prefix,
"--with-mpfr=%s" % spec["mpfr"].prefix,
"--with-ppl=%s" % spec["ppl"].prefix)
make()
make("install")
| lgpl-2.1 |
whip112/Whip112 | kuma/wiki/middleware.py | 3 | 2015 | from django.shortcuts import render
from django.http import HttpResponseRedirect
from jingo.helpers import urlparams
from .exceptions import ReadOnlyException
from .jobs import DocumentZoneURLRemapsJob
class ReadOnlyMiddleware(object):
"""
Renders a 403.html page with a flag for a specific message.
"""
def process_exception(self, request, exception):
if isinstance(exception, ReadOnlyException):
context = {'reason': exception.args[0]}
return render(request, '403.html', context, status=403)
return None
class DocumentZoneMiddleware(object):
"""
For document zones with specified URL roots, this middleware modifies the
incoming path_info to point at the internal wiki path
"""
def process_request(self, request):
remaps = DocumentZoneURLRemapsJob().get(request.locale)
for original_path, new_path in remaps:
if request.path_info.startswith(original_path):
# Is this a request for the "original" wiki path? Redirect to
# new URL root, if so.
new_path = request.path_info.replace(original_path,
new_path,
1)
new_path = '/%s%s' % (request.locale, new_path)
query = request.GET.copy()
if 'lang' in query:
query.pop('lang')
new_path = urlparams(new_path, query_dict=query)
return HttpResponseRedirect(new_path)
elif request.path_info.startswith(new_path):
# Is this a request for the relocated wiki path? If so, rewrite
# the path as a request for the proper wiki view.
request.path_info = request.path_info.replace(new_path,
original_path,
1)
break
| mpl-2.0 |
migonzalvar/youtube-dl | youtube_dl/extractor/ebaumsworld.py | 149 | 1055 | from __future__ import unicode_literals
from .common import InfoExtractor
class EbaumsWorldIE(InfoExtractor):
_VALID_URL = r'https?://www\.ebaumsworld\.com/video/watch/(?P<id>\d+)'
_TEST = {
'url': 'http://www.ebaumsworld.com/video/watch/83367677/',
'info_dict': {
'id': '83367677',
'ext': 'mp4',
'title': 'A Giant Python Opens The Door',
'description': 'This is how nightmares start...',
'uploader': 'jihadpizza',
},
}
def _real_extract(self, url):
video_id = self._match_id(url)
config = self._download_xml(
'http://www.ebaumsworld.com/video/player/%s' % video_id, video_id)
video_url = config.find('file').text
return {
'id': video_id,
'title': config.find('title').text,
'url': video_url,
'description': config.find('description').text,
'thumbnail': config.find('image').text,
'uploader': config.find('username').text,
}
| unlicense |
palantir/giraffe | docs/src/gh-pages.py | 2 | 2799 | # https://github.com/dinoboff/github-tools/blob/master/src/github/tools/sphinx.py
#
# Copyright (c) 2009, Damien Lebrun
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Modifications
# -------------
# Changed move_private_folders to better handle existing directories
"""
:Description: Sphinx extension to remove leading under-scores from directories names in the html build output directory.
"""
import os
import shutil
def setup(app):
"""
Add a html-page-context and a build-finished event handlers
"""
app.connect('html-page-context', change_pathto)
app.connect('build-finished', move_private_folders)
def change_pathto(app, pagename, templatename, context, doctree):
"""
Replace pathto helper to change paths to folders with a leading underscore.
"""
pathto = context.get('pathto')
def gh_pathto(otheruri, *args, **kw):
if otheruri.startswith('_'):
otheruri = otheruri[1:]
return pathto(otheruri, *args, **kw)
context['pathto'] = gh_pathto
def move_private_folders(app, e):
"""
remove leading underscore from folders in in the output folder.
:todo: should only affect html built
"""
def join(dir):
return os.path.join(app.builder.outdir, dir)
for item in os.listdir(app.builder.outdir):
if item.startswith('_') and os.path.isdir(join(item)):
target = join(item[1:])
if os.path.isdir(target):
shutil.rmtree(target)
shutil.move(join(item), target)
| apache-2.0 |
googleapis/googleapis-gen | google/ads/googleads/v8/googleads-py/google/ads/googleads/v8/services/services/carrier_constant_service/transports/base.py | 1 | 3752 | # -*- 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 abc
import typing
import pkg_resources
import google.auth # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.ads.googleads.v8.resources.types import carrier_constant
from google.ads.googleads.v8.services.types import carrier_constant_service
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
'google-ads',
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
class CarrierConstantServiceTransport(metaclass=abc.ABCMeta):
"""Abstract transport class for CarrierConstantService."""
AUTH_SCOPES = (
'https://www.googleapis.com/auth/adwords',
)
def __init__(
self, *,
host: str = 'googleads.googleapis.com',
credentials: ga_credentials.Credentials = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> 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.
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.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ':' not in host:
host += ':443'
self._host = host
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials is None:
credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES)
# Save the credentials.
self._credentials = credentials
# Lifted into its own function so it can be stubbed out during tests.
self._prep_wrapped_messages(client_info)
def _prep_wrapped_messages(self, client_info):
# Precomputed wrapped methods
self._wrapped_methods = {
self.get_carrier_constant: gapic_v1.method.wrap_method(
self.get_carrier_constant,
default_timeout=None,
client_info=client_info,
),
}
@property
def get_carrier_constant(self) -> typing.Callable[
[carrier_constant_service.GetCarrierConstantRequest],
carrier_constant.CarrierConstant]:
raise NotImplementedError
__all__ = (
'CarrierConstantServiceTransport',
)
| apache-2.0 |
karec/ics2web | deployement/fabfile.py | 1 | 3348 | from fabric.api import sudo, cd, run, env
from fabric.colors import green, yellow
from fabric.contrib.files import append
import ConfigParser
env.hosts = ['10.104.10.63']
def install_api_server(conf_file):
config = ConfigParser.ConfigParser()
config.read(conf_file)
api_path = config.get('Global', 'api_path')
print(yellow("Warning : You need to execute this script with sudoer"))
print(green("Installing linux packages..."))
sudo("apt-get install -y nginx supervisor python-dev python-virtualenv git")
print(green("Linux packages installed"))
print(green("Creating project path"))
run("git clone https://karec@bitbucket.org/karec/ics2web.git {0}".format(api_path))
with cd(api_path):
run("virtualenv ics2web")
print(green("setting up virtualenv"))
source = "source {0} && ".format(api_path + "/ics2web/bin/activate")
print(green("Installing requirements for project"))
run(source + "pip install -r " + api_path + "/scripts/requirements.txt")
run(source + "pip install gunicorn")
print(green("Configuring gunicorn"))
with open(config.get('Files', 'gunicorn_template')) as f:
content = f.read()
content = content.format(api_path, config.get('Global', 'user'),
config.get('Global', 'group'),
config.getint('Global', 'workers'))
run('touch {0}'.format(api_path + '/ics2web/bin/gunicorn_start'))
append(api_path + '/ics2web/bin/gunicorn_start', content, escape=True)
run('chmod a+x ' + api_path + '/ics2web/bin/gunicorn_start')
print(green("Configuring nginx"))
with open(config.get('Files', 'nginx_template')) as f:
content = f.read()
content = content.format(api_path, config.get('Nginx', 'access_log'),
config.get('Nginx', 'error_log'),
config.get('Nginx', 'server_name'))
sudo("touch {0}".format("/etc/nginx/sites-available/ics2web"))
append('/etc/nginx/sites-available/ics2web', content, use_sudo=True)
sudo("ln -s /etc/nginx/sites-available/ics2web /etc/nginx/sites-enabled/ics2web")
sudo('service nginx restart')
print(green("Configuring supervisor"))
with open(config.get('Files', 'supervisor_template')) as f:
content = f.read()
content = content.format(api_path,
config.get('Global', 'user'),
config.get('Global', 'group'),
config.get('Supervisor', 'log_file'))
sudo("touch {0}".format("/etc/supervisor/conf.d/ics2web.conf"))
append('/etc/supervisor/conf.d/ics2web.conf', content, use_sudo=True)
sudo('supervisorctl reload')
print(green("Starting application"))
sudo('supervisorctl start ics2web')
def update_api(conf_file):
config = ConfigParser.ConfigParser()
config.read(conf_file)
print(yellow("Warning : the use need rights for supervisor"))
print(green("Pulling last version"))
api_path = config.get('Global', 'api_path')
with cd(api_path):
run('git pull origin master')
print(green("Restarting app"))
app_name = config.get('Global', 'app_name')
sudo('supervisorctl restart {0}'.format(app_name))
print(green("Update done")) | mit |
andrewyoung1991/scons | test/Fortran/FORTRAN.py | 3 | 4571 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import TestSCons
from common import write_fake_link
_python_ = TestSCons._python_
_exe = TestSCons._exe
test = TestSCons.TestSCons()
write_fake_link(test)
test.write('myg77.py', r"""
import getopt
import sys
opts, args = getopt.getopt(sys.argv[1:], 'co:')
for opt, arg in opts:
if opt == '-o': out = arg
infile = open(args[0], 'rb')
outfile = open(out, 'wb')
for l in infile.readlines():
if l[:4] != '#g77':
outfile.write(l)
sys.exit(0)
""")
test.write('SConstruct', """
env = Environment(LINK = r'%(_python_)s mylink.py',
LINKFLAGS = [],
FORTRAN = r'%(_python_)s myg77.py')
env.Program(target = 'test01', source = 'test01.f')
env.Program(target = 'test02', source = 'test02.F')
env.Program(target = 'test03', source = 'test03.for')
env.Program(target = 'test04', source = 'test04.FOR')
env.Program(target = 'test05', source = 'test05.ftn')
env.Program(target = 'test06', source = 'test06.FTN')
env.Program(target = 'test07', source = 'test07.fpp')
env.Program(target = 'test08', source = 'test08.FPP')
""" % locals())
test.write('test01.f', "This is a .f file.\n#link\n#g77\n")
test.write('test02.F', "This is a .F file.\n#link\n#g77\n")
test.write('test03.for', "This is a .for file.\n#link\n#g77\n")
test.write('test04.FOR', "This is a .FOR file.\n#link\n#g77\n")
test.write('test05.ftn', "This is a .ftn file.\n#link\n#g77\n")
test.write('test06.FTN', "This is a .FTN file.\n#link\n#g77\n")
test.write('test07.fpp', "This is a .fpp file.\n#link\n#g77\n")
test.write('test08.FPP', "This is a .FPP file.\n#link\n#g77\n")
test.run(arguments = '.', stderr = None)
test.must_match('test01' + _exe, "This is a .f file.\n")
test.must_match('test02' + _exe, "This is a .F file.\n")
test.must_match('test03' + _exe, "This is a .for file.\n")
test.must_match('test04' + _exe, "This is a .FOR file.\n")
test.must_match('test05' + _exe, "This is a .ftn file.\n")
test.must_match('test06' + _exe, "This is a .FTN file.\n")
test.must_match('test07' + _exe, "This is a .fpp file.\n")
test.must_match('test08' + _exe, "This is a .FPP file.\n")
fc = 'f77'
f77 = test.detect_tool(fc)
FTN_LIB = test.gccFortranLibs()
if f77:
test.write("wrapper.py",
"""import os
import sys
open('%s', 'wb').write("wrapper.py\\n")
os.system(" ".join(sys.argv[1:]))
""" % test.workpath('wrapper.out').replace('\\', '\\\\'))
test.write('SConstruct', """
foo = Environment(FORTRAN = '%(fc)s')
f77 = foo.Dictionary('FORTRAN')
bar = foo.Clone(FORTRAN = r'%(_python_)s wrapper.py ' + f77)
foo.Program(target = 'foo', source = 'foo.f')
bar.Program(target = 'bar', source = 'bar.f')
""" % locals())
test.write('foo.f', r"""
PROGRAM FOO
PRINT *,'foo.f'
STOP
END
""")
test.write('bar.f', r"""
PROGRAM BAR
PRINT *,'bar.f'
STOP
END
""")
test.run(arguments = 'foo' + _exe, stderr = None)
test.run(program = test.workpath('foo'), stdout = " foo.f\n")
test.must_not_exist('wrapper.out')
import sys
if sys.platform[:5] == 'sunos':
test.run(arguments = 'bar' + _exe, stderr = None)
else:
test.run(arguments = 'bar' + _exe)
test.run(program = test.workpath('bar'), stdout = " bar.f\n")
test.must_match('wrapper.out', "wrapper.py\n")
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| mit |
mordred-descriptor/mordred | mordred/EState.py | 1 | 3679 | from enum import IntEnum
from functools import reduce
from rdkit.Chem import EState
from ._base import Descriptor
from ._util import parse_enum
try:
import builtins
except ImportError:
import __builtin__ as builtins
__all__ = ("AtomTypeEState",)
es_types = (
"sLi",
"ssBe",
"ssssBe",
"ssBH",
"sssB",
"ssssB",
"sCH3",
"dCH2",
"ssCH2",
"tCH",
"dsCH",
"aaCH",
"sssCH",
"ddC",
"tsC",
"dssC",
"aasC",
"aaaC",
"ssssC",
"sNH3",
"sNH2",
"ssNH2",
"dNH",
"ssNH",
"aaNH",
"tN",
"sssNH",
"dsN",
"aaN",
"sssN",
"ddsN",
"aasN",
"ssssN",
"sOH",
"dO",
"ssO",
"aaO",
"sF",
"sSiH3",
"ssSiH2",
"sssSiH",
"ssssSi",
"sPH2",
"ssPH",
"sssP",
"dsssP",
"sssssP",
"sSH",
"dS",
"ssS",
"aaS",
"dssS",
"ddssS",
"sCl",
"sGeH3",
"ssGeH2",
"sssGeH",
"ssssGe",
"sAsH2",
"ssAsH",
"sssAs",
"sssdAs",
"sssssAs",
"sSeH",
"dSe",
"ssSe",
"aaSe",
"dssSe",
"ddssSe",
"sBr",
"sSnH3",
"ssSnH2",
"sssSnH",
"ssssSn",
"sI",
"sPbH3",
"ssPbH2",
"sssPbH",
"ssssPb",
)
es_type_set = set(es_types)
class EStateBase(Descriptor):
__slots__ = ()
explicit_hydrogens = False
class EStateCache(EStateBase):
__slots__ = ()
def parameters(self):
return ()
def calculate(self):
return EState.TypeAtoms(self.mol), EState.EStateIndices(self.mol)
class AggrType(IntEnum):
__slots__ = ()
count = 1
sum = 2
max = 3
min = 4
@property
def as_argument(self):
return self.name
def description(self):
d = {self.count: "number", self.sum: "sum", self.max: "max", self.min: "min"}
return d[self]
aggr_names = (
(AggrType.count, "N"),
(AggrType.sum, "S"),
(AggrType.max, "MAX"),
(AggrType.min, "MIN"),
)
aggr_name_dict = dict(aggr_names)
class AtomTypeEState(EStateBase):
r"""atom type e-state descriptor.
:type type: str
:param type: one of aggr_types
:type estate: str
:param estate: one of es_types
:returns: NaN when type in ["min", "max"] and :math:`N_{\rm X} = 0`
References
* :doi:`10.1021/ci00028a014`
"""
since = "1.0.0"
__slots__ = ("_type", "_estate")
def description(self):
return "{} of {}".format(self._type.description(), self._estate)
aggr_types = tuple(a.name for a in AggrType)
es_types = es_types
@classmethod
def preset(cls, version):
return (cls(a, t) for a in AggrType for t in es_types)
def __str__(self):
aggr = aggr_name_dict[self._type]
return aggr + self._estate
def parameters(self):
return self._type, self._estate
def __init__(self, type="count", estate="sLi"):
assert estate in es_type_set
self._type = parse_enum(AggrType, type)
self._estate = estate
def dependencies(self):
return {"E": EStateCache()}
def calculate(self, E):
if self._type == AggrType.count:
return reduce(lambda a, b: a + b, E[0]).count(self._estate)
indices = map(lambda e: e[1], filter(lambda e: self._estate in e[0], zip(*E)))
with self.rethrow_na(ValueError):
return getattr(builtins, self._type.name)(indices)
@property
def rtype(self):
r"""Return type.
* "count": :py:class:`int`
* "other": :py:class:`float`
"""
return int if self._type == AggrType.count else float
_extra_docs = "aggr_types", "es_types"
| bsd-3-clause |
matmutant/sl4a | python/src/Mac/Modules/help/helpscan.py | 34 | 1968 | # Scan an Apple header file, generating a Python file of generator calls.
import sys
from bgenlocations import TOOLBOXDIR, BGENDIR
sys.path.append(BGENDIR)
from scantools import Scanner
LONG = "MacHelp"
SHORT = "help"
OBJECT = "NOTUSED"
def main():
input = LONG + ".h"
output = SHORT + "gen.py"
defsoutput = TOOLBOXDIR + LONG + ".py"
scanner = MyScanner(input, output, defsoutput)
scanner.scan()
scanner.close()
print "=== Testing definitions output code ==="
execfile(defsoutput, {}, {})
print "=== Done scanning and generating, now importing the generated code... ==="
exec "import " + SHORT + "support"
print "=== Done. It's up to you to compile it now! ==="
class MyScanner(Scanner):
def destination(self, type, name, arglist):
classname = "Function"
listname = "functions"
if arglist:
t, n, m = arglist[0]
# This is non-functional today
if t == OBJECT and m == "InMode":
classname = "Method"
listname = "methods"
return classname, listname
def writeinitialdefs(self):
self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n")
def makeblacklistnames(self):
return [
]
def makeblacklisttypes(self):
return [
## "TipFunctionUPP",
## "HMMessageRecord",
## "HMMessageRecord_ptr",
"HMWindowContentUPP",
"HMMenuTitleContentUPP",
"HMControlContentUPP",
"HMMenuItemContentUPP",
# For the moment
"HMHelpContentRec",
"HMHelpContentRec_ptr",
]
def makerepairinstructions(self):
return [
## ([("WindowPtr", "*", "OutMode")],
## [("ExistingWindowPtr", "*", "*")]),
]
if __name__ == "__main__":
main()
| apache-2.0 |
umitanuki/chainer | cupy/cuda/cublas.py | 4 | 8751 | """Thin wrapper of CUBLAS."""
import ctypes
from cupy.cuda import driver
from cupy.cuda import internal
_cublas = internal.load_library('cublas')
_I = ctypes.c_int
_P = ctypes.c_void_p
_F = ctypes.c_float
_D = ctypes.c_double
_IP = ctypes.POINTER(_I)
_FP = ctypes.POINTER(_F)
_DP = ctypes.POINTER(_D)
Handle = _P
CUBLAS_OP_N = 0
CUBLAS_OP_T = 1
CUBLAS_OP_C = 2
CUBLAS_POINTER_MODE_HOST = 0
CUBLAS_POINTER_MODE_DEVICE = 1
###############################################################################
# Error handling
###############################################################################
STATUS = {
0: 'CUBLAS_STATUS_SUCCESS',
1: 'CUBLAS_STATUS_NOT_INITIALIZED',
3: 'CUBLAS_STATUS_ALLOC_FAILED',
7: 'CUBLAS_STATUS_INVALID_VALUE',
8: 'CUBLAS_STATUS_ARCH_MISMATCH',
11: 'CUBLAS_STATUS_MAPPING_ERROR',
13: 'CUBLAS_STATUS_EXECUTION_FAILED',
14: 'CUBLAS_STATUS_INTERNAL_ERROR',
15: 'CUBLAS_STATUS_NOT_SUPPORTED',
16: 'CUBLAS_STATUS_LICENSE_ERROR',
}
class CUBLASError(RuntimeError):
def __init__(self, status):
self.status = status
super(CUBLASError, self).__init__(STATUS[status])
def check_status(status):
if status != 0:
raise CUBLASError(status)
###############################################################################
# Context
###############################################################################
_cublas.cublasCreate_v2.argtypes = [_P]
def create():
handle = Handle()
status = _cublas.cublasCreate_v2(ctypes.byref(handle))
check_status(status)
return handle
_cublas.cublasDestroy_v2.argtypes = [Handle]
def destroy(handle):
status = _cublas.cublasDestroy_v2(handle)
check_status(status)
_cublas.cublasGetVersion_v2.argtypes = [Handle, _IP]
def getVersion(handle):
version = ctypes.c_int()
status = _cublas.cublasGetVersion_v2(handle, ctypes.byref(version))
check_status(status)
return version
_cublas.cublasGetPointerMode_v2.argtypes = [Handle, _IP]
def getPointerMode(handle):
mode = ctypes.c_int()
status = _cublas.cublasGetPointerMode_v2(handle, ctypes.byref(mode))
check_status(status)
return mode.value
_cublas.cublasSetPointerMode_v2.argtypes = [Handle, _I]
def setPointerMode(handle, mode):
status = _cublas.cublasSetPointerMode_v2(handle, mode)
check_status(status)
###############################################################################
# Stream
###############################################################################
_cublas.cublasSetStream_v2.argtypes = [Handle, driver.Stream]
def setStream(handle, stream):
status = _cublas.cublasSetStream_v2(handle, stream)
check_status(status)
_cublas.cublasGetStream_v2.argtypes = [Handle, _P]
def getStream(handle):
stream = driver.Stream()
status = _cublas.cublasGetStream_v2(handle, ctypes.byref(stream))
check_status(status)
return stream
###############################################################################
# BLAS Level 1
###############################################################################
_cublas.cublasIsamax_v2.argtypes = [Handle, _I, _FP, _I, _IP]
def isamax(handle, n, x, incx):
result = ctypes.c_int()
status = _cublas.cublasIsamax_v2(
handle, n, x, incx, ctypes.byref(result))
check_status(status)
return result.value
_cublas.cublasIsamin_v2.argtypes = [Handle, _I, _FP, _I, _IP]
def isamin(handle, n, x, incx):
result = ctypes.c_int()
status = _cublas.cublasIsamin_v2(
handle, n, x, incx, ctypes.byref(result))
check_status(status)
return result.value
_cublas.cublasSasum_v2.argtypes = [Handle, _I, _FP, _I, _FP]
def sasum(handle, n, x, incx):
result = ctypes.c_float()
status = _cublas.cublasSasum_v2(
handle, n, x, incx, ctypes.byref(result))
check_status(status)
return result.value
_cublas.cublasSaxpy_v2.argtypes = [Handle, _I, _FP, _FP, _I, _FP, _I]
def saxpy(handle, n, alpha, x, incx, y, incy):
status = _cublas.cublasSaxpy_v2(
handle, n, ctypes.byref(_F(alpha)), x, incx, y, incy)
check_status(status)
_cublas.cublasDaxpy_v2.argtypes = [Handle, _I, _DP, _DP, _I, _DP, _I]
def daxpy(handle, n, alpha, x, incx, y, incy):
status = _cublas.cublasDaxpy_v2(
handle, n, ctypes.byref(_D(alpha)), x, incx, y, incy)
check_status(status)
_cublas.cublasSdot_v2.argtypes = [Handle, _I, _FP, _I, _FP, _I, _FP]
def sdot(handle, n, x, incx, y, incy, result):
status = _cublas.cublasSdot_v2(
handle, n, x, incx, y, incy, result)
check_status(status)
_cublas.cublasDdot_v2.argtypes = [Handle, _I, _DP, _I, _DP, _I, _DP]
def ddot(handle, n, x, incx, y, incy, result):
status = _cublas.cublasDdot_v2(
handle, n, x, incx, y, incy, result)
check_status(status)
_cublas.cublasSnrm2_v2.argtypes = [Handle, _I, _FP, _I, _FP]
def snrm2(handle, n, x, incx):
result = ctypes.c_float()
status = _cublas.cublasSnrm2_v2(
handle, n, x, incx, ctypes.byref(result))
check_status(status)
return result.value
_cublas.cublasSscal_v2.argtypes = [Handle, _I, _FP, _FP, _I]
def sscal(handle, n, alpha, x, incx):
status = _cublas.cublasSscal_v2(
handle, n, ctypes.byref(_F(alpha)), x, incx)
check_status(status)
###############################################################################
# BLAS Level 2
###############################################################################
_cublas.cublasSgemv_v2.argtypes = [Handle, _I, _I, _I, _FP, _FP, _I, _FP, _I,
_FP, _FP, _I]
def sgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy):
status = _cublas.cublasSgemv_v2(
handle, trans, m, n, ctypes.byref(_F(alpha)),
A, lda, x, incx, ctypes.byref(_F(beta)), y, incy)
check_status(status)
_cublas.cublasDgemv_v2.argtypes = [Handle, _I, _I, _I, _DP, _DP, _I, _DP, _I,
_DP, _DP, _I]
def dgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy):
status = _cublas.cublasDgemv_v2(
handle, trans, m, n, ctypes.byref(_D(alpha)),
A, lda, x, incx, ctypes.byref(_D(beta)), y, incy)
check_status(status)
_cublas.cublasSger_v2.argtypes = [
Handle, _I, _I, _FP, _FP, _I, _FP, _I, _FP, _I]
def sger(handle, m, n, alpha, x, incx, y, incy, A, lda):
status = _cublas.cublasSger_v2(
handle, m, n, ctypes.byref(_F(alpha)), x, incx, y, incy, A, lda)
check_status(status)
_cublas.cublasDger_v2.argtypes = [
Handle, _I, _I, _DP, _DP, _I, _DP, _I, _DP, _I]
def dger(handle, m, n, alpha, x, incx, y, incy, A, lda):
status = _cublas.cublasDger_v2(
handle, m, n, ctypes.byref(_D(alpha)), x, incx, y, incy, A, lda)
check_status(status)
###############################################################################
# BLAS Level 3
###############################################################################
_cublas.cublasSgemm_v2.argtypes = [Handle, _I, _I, _I, _I, _I, _FP, _FP, _I,
_FP, _I, _FP, _FP, _I]
def sgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C,
ldc):
status = _cublas.cublasSgemm_v2(
handle, transa, transb, m, n, k, ctypes.byref(_F(alpha)),
A, lda, B, ldb, ctypes.byref(_F(beta)), C, ldc)
check_status(status)
_cublas.cublasDgemm_v2.argtypes = [Handle, _I, _I, _I, _I, _I, _DP, _DP, _I,
_DP, _I, _DP, _DP, _I]
def dgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C,
ldc):
status = _cublas.cublasDgemm_v2(
handle, transa, transb, m, n, k, ctypes.byref(_D(alpha)),
A, lda, B, ldb, ctypes.byref(_D(beta)), C, ldc)
check_status(status)
_cublas.cublasSgemmBatched.argtypes = [
Handle, _I, _I, _I, _I, _I, _FP, _P, _I, _P, _I, _FP, _P, _I, _I]
def sgemmBatched(handle, transa, transb, m, n, k, alpha, Aarray, lda, Barray,
ldb, beta, Carray, ldc, batchCount):
status = _cublas.cublasSgemmBatched(
handle, transa, transb, m, n, k, ctypes.byref(_F(alpha)),
Aarray, lda, Barray, ldb, ctypes.byref(_F(beta)),
Carray, ldc, batchCount)
check_status(status)
###############################################################################
# BLAS extension
###############################################################################
CUBLAS_SIDE_LEFT = 0
CUBLAS_SIDE_RIGHT = 1
_cublas.cublasSdgmm.argtypes = [Handle, _I, _I, _I, _FP, _I, _FP, _I, _FP, _I]
def sdgmm(handle, mode, m, n, A, lda, x, incx, C, ldc):
status = _cublas.cublasSdgmm(handle, mode, m, n, A, lda, x, incx, C, ldc)
check_status(status)
| mit |
jayceyxc/hue | desktop/core/ext-py/pycrypto-2.6.1/lib/Crypto/Util/number.py | 127 | 95488 | #
# number.py : Number-theoretic functions
#
# Part of the Python Cryptography Toolkit
#
# Written by Andrew M. Kuchling, Barry A. Warsaw, and others
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
#
__revision__ = "$Id$"
from Crypto.pct_warnings import GetRandomNumber_DeprecationWarning, PowmInsecureWarning
from warnings import warn as _warn
import math
import sys
from Crypto.Util.py3compat import *
bignum = long
try:
from Crypto.PublicKey import _fastmath
except ImportError:
# For production, we are going to let import issues due to gmp/mpir shared
# libraries not loading slide silently and use slowmath. If you'd rather
# see an exception raised if _fastmath exists but cannot be imported,
# uncomment the below
#
# from distutils.sysconfig import get_config_var
# import inspect, os
# _fm_path = os.path.normpath(os.path.dirname(os.path.abspath(
# inspect.getfile(inspect.currentframe())))
# +"/../../PublicKey/_fastmath"+get_config_var("SO"))
# if os.path.exists(_fm_path):
# raise ImportError("While the _fastmath module exists, importing "+
# "it failed. This may point to the gmp or mpir shared library "+
# "not being in the path. _fastmath was found at "+_fm_path)
_fastmath = None
# You need libgmp v5 or later to get mpz_powm_sec. Warn if it's not available.
if _fastmath is not None and not _fastmath.HAVE_DECL_MPZ_POWM_SEC:
_warn("Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning)
# New functions
from _number_new import *
# Commented out and replaced with faster versions below
## def long2str(n):
## s=''
## while n>0:
## s=chr(n & 255)+s
## n=n>>8
## return s
## import types
## def str2long(s):
## if type(s)!=types.StringType: return s # Integers will be left alone
## return reduce(lambda x,y : x*256+ord(y), s, 0L)
def size (N):
"""size(N:long) : int
Returns the size of the number N in bits.
"""
bits = 0
while N >> bits:
bits += 1
return bits
def getRandomNumber(N, randfunc=None):
"""Deprecated. Use getRandomInteger or getRandomNBitInteger instead."""
warnings.warn("Crypto.Util.number.getRandomNumber has confusing semantics"+
"and has been deprecated. Use getRandomInteger or getRandomNBitInteger instead.",
GetRandomNumber_DeprecationWarning)
return getRandomNBitInteger(N, randfunc)
def getRandomInteger(N, randfunc=None):
"""getRandomInteger(N:int, randfunc:callable):long
Return a random number with at most N bits.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future.
"""
if randfunc is None:
_import_Random()
randfunc = Random.new().read
S = randfunc(N>>3)
odd_bits = N % 8
if odd_bits != 0:
char = ord(randfunc(1)) >> (8-odd_bits)
S = bchr(char) + S
value = bytes_to_long(S)
return value
def getRandomRange(a, b, randfunc=None):
"""getRandomRange(a:int, b:int, randfunc:callable):long
Return a random number n so that a <= n < b.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future.
"""
range_ = b - a - 1
bits = size(range_)
value = getRandomInteger(bits, randfunc)
while value > range_:
value = getRandomInteger(bits, randfunc)
return a + value
def getRandomNBitInteger(N, randfunc=None):
"""getRandomInteger(N:int, randfunc:callable):long
Return a random number with exactly N-bits, i.e. a random number
between 2**(N-1) and (2**N)-1.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future.
"""
value = getRandomInteger (N-1, randfunc)
value |= 2L ** (N-1) # Ensure high bit is set
assert size(value) >= N
return value
def GCD(x,y):
"""GCD(x:long, y:long): long
Return the GCD of x and y.
"""
x = abs(x) ; y = abs(y)
while x > 0:
x, y = y % x, x
return y
def inverse(u, v):
"""inverse(u:long, v:long):long
Return the inverse of u mod v.
"""
u3, v3 = long(u), long(v)
u1, v1 = 1L, 0L
while v3 > 0:
q=divmod(u3, v3)[0]
u1, v1 = v1, u1 - v1*q
u3, v3 = v3, u3 - v3*q
while u1<0:
u1 = u1 + v
return u1
# Given a number of bits to generate and a random generation function,
# find a prime number of the appropriate size.
def getPrime(N, randfunc=None):
"""getPrime(N:int, randfunc:callable):long
Return a random N-bit prime number.
If randfunc is omitted, then Random.new().read is used.
"""
if randfunc is None:
_import_Random()
randfunc = Random.new().read
number=getRandomNBitInteger(N, randfunc) | 1
while (not isPrime(number, randfunc=randfunc)):
number=number+2
return number
def _rabinMillerTest(n, rounds, randfunc=None):
"""_rabinMillerTest(n:long, rounds:int, randfunc:callable):int
Tests if n is prime.
Returns 0 when n is definitly composite.
Returns 1 when n is probably prime.
Returns 2 when n is definitly prime.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future.
"""
# check special cases (n==2, n even, n < 2)
if n < 3 or (n & 1) == 0:
return n == 2
# n might be very large so it might be beneficial to precalculate n-1
n_1 = n - 1
# determine m and b so that 2**b * m = n - 1 and b maximal
b = 0
m = n_1
while (m & 1) == 0:
b += 1
m >>= 1
tested = []
# we need to do at most n-2 rounds.
for i in xrange (min (rounds, n-2)):
# randomly choose a < n and make sure it hasn't been tested yet
a = getRandomRange (2, n, randfunc)
while a in tested:
a = getRandomRange (2, n, randfunc)
tested.append (a)
# do the rabin-miller test
z = pow (a, m, n) # (a**m) % n
if z == 1 or z == n_1:
continue
composite = 1
for r in xrange (b):
z = (z * z) % n
if z == 1:
return 0
elif z == n_1:
composite = 0
break
if composite:
return 0
return 1
def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None):
"""getStrongPrime(N:int, e:int, false_positive_prob:float, randfunc:callable):long
Return a random strong N-bit prime number.
In this context p is a strong prime if p-1 and p+1 have at
least one large prime factor.
N should be a multiple of 128 and > 512.
If e is provided the returned prime p-1 will be coprime to e
and thus suitable for RSA where e is the public exponent.
The optional false_positive_prob is the statistical probability
that true is returned even though it is not (pseudo-prime).
It defaults to 1e-6 (less than 1:1000000).
Note that the real probability of a false-positive is far less. This is
just the mathematically provable limit.
randfunc should take a single int parameter and return that
many random bytes as a string.
If randfunc is omitted, then Random.new().read is used.
"""
# This function was implemented following the
# instructions found in the paper:
# "FAST GENERATION OF RANDOM, STRONG RSA PRIMES"
# by Robert D. Silverman
# RSA Laboratories
# May 17, 1997
# which by the time of writing could be freely downloaded here:
# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.17.2713&rep=rep1&type=pdf
# Use the accelerator if available
if _fastmath is not None:
return _fastmath.getStrongPrime(long(N), long(e), false_positive_prob,
randfunc)
if (N < 512) or ((N % 128) != 0):
raise ValueError ("bits must be multiple of 128 and > 512")
rabin_miller_rounds = int(math.ceil(-math.log(false_positive_prob)/math.log(4)))
# calculate range for X
# lower_bound = sqrt(2) * 2^{511 + 128*x}
# upper_bound = 2^{512 + 128*x} - 1
x = (N - 512) >> 7;
# We need to approximate the sqrt(2) in the lower_bound by an integer
# expression because floating point math overflows with these numbers
lower_bound = divmod(14142135623730950489L * (2L ** (511 + 128*x)),
10000000000000000000L)[0]
upper_bound = (1L << (512 + 128*x)) - 1
# Randomly choose X in calculated range
X = getRandomRange (lower_bound, upper_bound, randfunc)
# generate p1 and p2
p = [0, 0]
for i in (0, 1):
# randomly choose 101-bit y
y = getRandomNBitInteger (101, randfunc)
# initialize the field for sieving
field = [0] * 5 * len (sieve_base)
# sieve the field
for prime in sieve_base:
offset = y % prime
for j in xrange ((prime - offset) % prime, len (field), prime):
field[j] = 1
# look for suitable p[i] starting at y
result = 0
for j in range(len(field)):
composite = field[j]
# look for next canidate
if composite:
continue
tmp = y + j
result = _rabinMillerTest (tmp, rabin_miller_rounds)
if result > 0:
p[i] = tmp
break
if result == 0:
raise RuntimeError ("Couln't find prime in field. "
"Developer: Increase field_size")
# Calculate R
# R = (p2^{-1} mod p1) * p2 - (p1^{-1} mod p2) * p1
tmp1 = inverse (p[1], p[0]) * p[1] # (p2^-1 mod p1)*p2
tmp2 = inverse (p[0], p[1]) * p[0] # (p1^-1 mod p2)*p1
R = tmp1 - tmp2 # (p2^-1 mod p1)*p2 - (p1^-1 mod p2)*p1
# search for final prime number starting by Y0
# Y0 = X + (R - X mod p1p2)
increment = p[0] * p[1]
X = X + (R - (X % increment))
while 1:
is_possible_prime = 1
# first check candidate against sieve_base
for prime in sieve_base:
if (X % prime) == 0:
is_possible_prime = 0
break
# if e is given make sure that e and X-1 are coprime
# this is not necessarily a strong prime criterion but useful when
# creating them for RSA where the p-1 and q-1 should be coprime to
# the public exponent e
if e and is_possible_prime:
if e & 1:
if GCD (e, X-1) != 1:
is_possible_prime = 0
else:
if GCD (e, divmod((X-1),2)[0]) != 1:
is_possible_prime = 0
# do some Rabin-Miller-Tests
if is_possible_prime:
result = _rabinMillerTest (X, rabin_miller_rounds)
if result > 0:
break
X += increment
# abort when X has more bits than requested
# TODO: maybe we shouldn't abort but rather start over.
if X >= 1L << N:
raise RuntimeError ("Couln't find prime in field. "
"Developer: Increase field_size")
return X
def isPrime(N, false_positive_prob=1e-6, randfunc=None):
"""isPrime(N:long, false_positive_prob:float, randfunc:callable):bool
Return true if N is prime.
The optional false_positive_prob is the statistical probability
that true is returned even though it is not (pseudo-prime).
It defaults to 1e-6 (less than 1:1000000).
Note that the real probability of a false-positive is far less. This is
just the mathematically provable limit.
If randfunc is omitted, then Random.new().read is used.
"""
if _fastmath is not None:
return _fastmath.isPrime(long(N), false_positive_prob, randfunc)
if N < 3 or N & 1 == 0:
return N == 2
for p in sieve_base:
if N == p:
return 1
if N % p == 0:
return 0
rounds = int(math.ceil(-math.log(false_positive_prob)/math.log(4)))
return _rabinMillerTest(N, rounds, randfunc)
# Improved conversion functions contributed by Barry Warsaw, after
# careful benchmarking
import struct
def long_to_bytes(n, blocksize=0):
"""long_to_bytes(n:long, blocksize:int) : string
Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front of the
byte string with binary zeros so that the length is a multiple of
blocksize.
"""
# after much testing, this algorithm was deemed to be the fastest
s = b('')
n = long(n)
pack = struct.pack
while n > 0:
s = pack('>I', n & 0xffffffffL) + s
n = n >> 32
# strip off leading zeros
for i in range(len(s)):
if s[i] != b('\000')[0]:
break
else:
# only happens when n == 0
s = b('\000')
i = 0
s = s[i:]
# add back some pad bytes. this could be done more efficiently w.r.t. the
# de-padding being done above, but sigh...
if blocksize > 0 and len(s) % blocksize:
s = (blocksize - len(s) % blocksize) * b('\000') + s
return s
def bytes_to_long(s):
"""bytes_to_long(string) : long
Convert a byte string to a long integer.
This is (essentially) the inverse of long_to_bytes().
"""
acc = 0L
unpack = struct.unpack
length = len(s)
if length % 4:
extra = (4 - length % 4)
s = b('\000') * extra + s
length = length + extra
for i in range(0, length, 4):
acc = (acc << 32) + unpack('>I', s[i:i+4])[0]
return acc
# For backwards compatibility...
import warnings
def long2str(n, blocksize=0):
warnings.warn("long2str() has been replaced by long_to_bytes()")
return long_to_bytes(n, blocksize)
def str2long(s):
warnings.warn("str2long() has been replaced by bytes_to_long()")
return bytes_to_long(s)
def _import_Random():
# This is called in a function instead of at the module level in order to
# avoid problems with recursive imports
global Random, StrongRandom
from Crypto import Random
from Crypto.Random.random import StrongRandom
# The first 10000 primes used for checking primality.
# This should be enough to eliminate most of the odd
# numbers before needing to do a Rabin-Miller test at all.
sieve_base = (
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129,
2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213,
2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287,
2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423,
2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531,
2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617,
2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741,
2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819,
2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903,
2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079,
3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181,
3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257,
3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413,
3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511,
3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571,
3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727,
3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821,
3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907,
3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057,
4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139,
4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231,
4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409,
4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493,
4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583,
4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751,
4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831,
4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937,
4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003,
5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087,
5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179,
5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279,
5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387,
5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443,
5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521,
5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639,
5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693,
5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791,
5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857,
5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939,
5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053,
6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133,
6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221,
6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301,
6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367,
6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473,
6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571,
6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673,
6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761,
6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833,
6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917,
6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997,
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103,
7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207,
7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297,
7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411,
7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499,
7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561,
7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643,
7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723,
7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829,
7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919,
7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017,
8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111,
8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219,
8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291,
8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387,
8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501,
8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597,
8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677,
8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741,
8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831,
8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929,
8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011,
9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109,
9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199,
9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283,
9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377,
9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439,
9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533,
9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631,
9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733,
9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811,
9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887,
9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973, 10007,
10009, 10037, 10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099,
10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163, 10169, 10177,
10181, 10193, 10211, 10223, 10243, 10247, 10253, 10259, 10267, 10271,
10273, 10289, 10301, 10303, 10313, 10321, 10331, 10333, 10337, 10343,
10357, 10369, 10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459,
10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531, 10559, 10567,
10589, 10597, 10601, 10607, 10613, 10627, 10631, 10639, 10651, 10657,
10663, 10667, 10687, 10691, 10709, 10711, 10723, 10729, 10733, 10739,
10753, 10771, 10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859,
10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937, 10939, 10949,
10957, 10973, 10979, 10987, 10993, 11003, 11027, 11047, 11057, 11059,
11069, 11071, 11083, 11087, 11093, 11113, 11117, 11119, 11131, 11149,
11159, 11161, 11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251,
11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317, 11321, 11329,
11351, 11353, 11369, 11383, 11393, 11399, 11411, 11423, 11437, 11443,
11447, 11467, 11471, 11483, 11489, 11491, 11497, 11503, 11519, 11527,
11549, 11551, 11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657,
11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731, 11743, 11777,
11779, 11783, 11789, 11801, 11807, 11813, 11821, 11827, 11831, 11833,
11839, 11863, 11867, 11887, 11897, 11903, 11909, 11923, 11927, 11933,
11939, 11941, 11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011,
12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101, 12107, 12109,
12113, 12119, 12143, 12149, 12157, 12161, 12163, 12197, 12203, 12211,
12227, 12239, 12241, 12251, 12253, 12263, 12269, 12277, 12281, 12289,
12301, 12323, 12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401,
12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473, 12479, 12487,
12491, 12497, 12503, 12511, 12517, 12527, 12539, 12541, 12547, 12553,
12569, 12577, 12583, 12589, 12601, 12611, 12613, 12619, 12637, 12641,
12647, 12653, 12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739,
12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821, 12823, 12829,
12841, 12853, 12889, 12893, 12899, 12907, 12911, 12917, 12919, 12923,
12941, 12953, 12959, 12967, 12973, 12979, 12983, 13001, 13003, 13007,
13009, 13033, 13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109,
13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177, 13183, 13187,
13217, 13219, 13229, 13241, 13249, 13259, 13267, 13291, 13297, 13309,
13313, 13327, 13331, 13337, 13339, 13367, 13381, 13397, 13399, 13411,
13417, 13421, 13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499,
13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597, 13613, 13619,
13627, 13633, 13649, 13669, 13679, 13681, 13687, 13691, 13693, 13697,
13709, 13711, 13721, 13723, 13729, 13751, 13757, 13759, 13763, 13781,
13789, 13799, 13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879,
13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933, 13963, 13967,
13997, 13999, 14009, 14011, 14029, 14033, 14051, 14057, 14071, 14081,
14083, 14087, 14107, 14143, 14149, 14153, 14159, 14173, 14177, 14197,
14207, 14221, 14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323,
14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407, 14411, 14419,
14423, 14431, 14437, 14447, 14449, 14461, 14479, 14489, 14503, 14519,
14533, 14537, 14543, 14549, 14551, 14557, 14561, 14563, 14591, 14593,
14621, 14627, 14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699,
14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753, 14759, 14767,
14771, 14779, 14783, 14797, 14813, 14821, 14827, 14831, 14843, 14851,
14867, 14869, 14879, 14887, 14891, 14897, 14923, 14929, 14939, 14947,
14951, 14957, 14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073,
15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137, 15139, 15149,
15161, 15173, 15187, 15193, 15199, 15217, 15227, 15233, 15241, 15259,
15263, 15269, 15271, 15277, 15287, 15289, 15299, 15307, 15313, 15319,
15329, 15331, 15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401,
15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473, 15493, 15497,
15511, 15527, 15541, 15551, 15559, 15569, 15581, 15583, 15601, 15607,
15619, 15629, 15641, 15643, 15647, 15649, 15661, 15667, 15671, 15679,
15683, 15727, 15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773,
15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859, 15877, 15881,
15887, 15889, 15901, 15907, 15913, 15919, 15923, 15937, 15959, 15971,
15973, 15991, 16001, 16007, 16033, 16057, 16061, 16063, 16067, 16069,
16073, 16087, 16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183,
16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249, 16253, 16267,
16273, 16301, 16319, 16333, 16339, 16349, 16361, 16363, 16369, 16381,
16411, 16417, 16421, 16427, 16433, 16447, 16451, 16453, 16477, 16481,
16487, 16493, 16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603,
16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661, 16673, 16691,
16693, 16699, 16703, 16729, 16741, 16747, 16759, 16763, 16787, 16811,
16823, 16829, 16831, 16843, 16871, 16879, 16883, 16889, 16901, 16903,
16921, 16927, 16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993,
17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053, 17077, 17093,
17099, 17107, 17117, 17123, 17137, 17159, 17167, 17183, 17189, 17191,
17203, 17207, 17209, 17231, 17239, 17257, 17291, 17293, 17299, 17317,
17321, 17327, 17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389,
17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467, 17471, 17477,
17483, 17489, 17491, 17497, 17509, 17519, 17539, 17551, 17569, 17573,
17579, 17581, 17597, 17599, 17609, 17623, 17627, 17657, 17659, 17669,
17681, 17683, 17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783,
17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863, 17881, 17891,
17903, 17909, 17911, 17921, 17923, 17929, 17939, 17957, 17959, 17971,
17977, 17981, 17987, 17989, 18013, 18041, 18043, 18047, 18049, 18059,
18061, 18077, 18089, 18097, 18119, 18121, 18127, 18131, 18133, 18143,
18149, 18169, 18181, 18191, 18199, 18211, 18217, 18223, 18229, 18233,
18251, 18253, 18257, 18269, 18287, 18289, 18301, 18307, 18311, 18313,
18329, 18341, 18353, 18367, 18371, 18379, 18397, 18401, 18413, 18427,
18433, 18439, 18443, 18451, 18457, 18461, 18481, 18493, 18503, 18517,
18521, 18523, 18539, 18541, 18553, 18583, 18587, 18593, 18617, 18637,
18661, 18671, 18679, 18691, 18701, 18713, 18719, 18731, 18743, 18749,
18757, 18773, 18787, 18793, 18797, 18803, 18839, 18859, 18869, 18899,
18911, 18913, 18917, 18919, 18947, 18959, 18973, 18979, 19001, 19009,
19013, 19031, 19037, 19051, 19069, 19073, 19079, 19081, 19087, 19121,
19139, 19141, 19157, 19163, 19181, 19183, 19207, 19211, 19213, 19219,
19231, 19237, 19249, 19259, 19267, 19273, 19289, 19301, 19309, 19319,
19333, 19373, 19379, 19381, 19387, 19391, 19403, 19417, 19421, 19423,
19427, 19429, 19433, 19441, 19447, 19457, 19463, 19469, 19471, 19477,
19483, 19489, 19501, 19507, 19531, 19541, 19543, 19553, 19559, 19571,
19577, 19583, 19597, 19603, 19609, 19661, 19681, 19687, 19697, 19699,
19709, 19717, 19727, 19739, 19751, 19753, 19759, 19763, 19777, 19793,
19801, 19813, 19819, 19841, 19843, 19853, 19861, 19867, 19889, 19891,
19913, 19919, 19927, 19937, 19949, 19961, 19963, 19973, 19979, 19991,
19993, 19997, 20011, 20021, 20023, 20029, 20047, 20051, 20063, 20071,
20089, 20101, 20107, 20113, 20117, 20123, 20129, 20143, 20147, 20149,
20161, 20173, 20177, 20183, 20201, 20219, 20231, 20233, 20249, 20261,
20269, 20287, 20297, 20323, 20327, 20333, 20341, 20347, 20353, 20357,
20359, 20369, 20389, 20393, 20399, 20407, 20411, 20431, 20441, 20443,
20477, 20479, 20483, 20507, 20509, 20521, 20533, 20543, 20549, 20551,
20563, 20593, 20599, 20611, 20627, 20639, 20641, 20663, 20681, 20693,
20707, 20717, 20719, 20731, 20743, 20747, 20749, 20753, 20759, 20771,
20773, 20789, 20807, 20809, 20849, 20857, 20873, 20879, 20887, 20897,
20899, 20903, 20921, 20929, 20939, 20947, 20959, 20963, 20981, 20983,
21001, 21011, 21013, 21017, 21019, 21023, 21031, 21059, 21061, 21067,
21089, 21101, 21107, 21121, 21139, 21143, 21149, 21157, 21163, 21169,
21179, 21187, 21191, 21193, 21211, 21221, 21227, 21247, 21269, 21277,
21283, 21313, 21317, 21319, 21323, 21341, 21347, 21377, 21379, 21383,
21391, 21397, 21401, 21407, 21419, 21433, 21467, 21481, 21487, 21491,
21493, 21499, 21503, 21517, 21521, 21523, 21529, 21557, 21559, 21563,
21569, 21577, 21587, 21589, 21599, 21601, 21611, 21613, 21617, 21647,
21649, 21661, 21673, 21683, 21701, 21713, 21727, 21737, 21739, 21751,
21757, 21767, 21773, 21787, 21799, 21803, 21817, 21821, 21839, 21841,
21851, 21859, 21863, 21871, 21881, 21893, 21911, 21929, 21937, 21943,
21961, 21977, 21991, 21997, 22003, 22013, 22027, 22031, 22037, 22039,
22051, 22063, 22067, 22073, 22079, 22091, 22093, 22109, 22111, 22123,
22129, 22133, 22147, 22153, 22157, 22159, 22171, 22189, 22193, 22229,
22247, 22259, 22271, 22273, 22277, 22279, 22283, 22291, 22303, 22307,
22343, 22349, 22367, 22369, 22381, 22391, 22397, 22409, 22433, 22441,
22447, 22453, 22469, 22481, 22483, 22501, 22511, 22531, 22541, 22543,
22549, 22567, 22571, 22573, 22613, 22619, 22621, 22637, 22639, 22643,
22651, 22669, 22679, 22691, 22697, 22699, 22709, 22717, 22721, 22727,
22739, 22741, 22751, 22769, 22777, 22783, 22787, 22807, 22811, 22817,
22853, 22859, 22861, 22871, 22877, 22901, 22907, 22921, 22937, 22943,
22961, 22963, 22973, 22993, 23003, 23011, 23017, 23021, 23027, 23029,
23039, 23041, 23053, 23057, 23059, 23063, 23071, 23081, 23087, 23099,
23117, 23131, 23143, 23159, 23167, 23173, 23189, 23197, 23201, 23203,
23209, 23227, 23251, 23269, 23279, 23291, 23293, 23297, 23311, 23321,
23327, 23333, 23339, 23357, 23369, 23371, 23399, 23417, 23431, 23447,
23459, 23473, 23497, 23509, 23531, 23537, 23539, 23549, 23557, 23561,
23563, 23567, 23581, 23593, 23599, 23603, 23609, 23623, 23627, 23629,
23633, 23663, 23669, 23671, 23677, 23687, 23689, 23719, 23741, 23743,
23747, 23753, 23761, 23767, 23773, 23789, 23801, 23813, 23819, 23827,
23831, 23833, 23857, 23869, 23873, 23879, 23887, 23893, 23899, 23909,
23911, 23917, 23929, 23957, 23971, 23977, 23981, 23993, 24001, 24007,
24019, 24023, 24029, 24043, 24049, 24061, 24071, 24077, 24083, 24091,
24097, 24103, 24107, 24109, 24113, 24121, 24133, 24137, 24151, 24169,
24179, 24181, 24197, 24203, 24223, 24229, 24239, 24247, 24251, 24281,
24317, 24329, 24337, 24359, 24371, 24373, 24379, 24391, 24407, 24413,
24419, 24421, 24439, 24443, 24469, 24473, 24481, 24499, 24509, 24517,
24527, 24533, 24547, 24551, 24571, 24593, 24611, 24623, 24631, 24659,
24671, 24677, 24683, 24691, 24697, 24709, 24733, 24749, 24763, 24767,
24781, 24793, 24799, 24809, 24821, 24841, 24847, 24851, 24859, 24877,
24889, 24907, 24917, 24919, 24923, 24943, 24953, 24967, 24971, 24977,
24979, 24989, 25013, 25031, 25033, 25037, 25057, 25073, 25087, 25097,
25111, 25117, 25121, 25127, 25147, 25153, 25163, 25169, 25171, 25183,
25189, 25219, 25229, 25237, 25243, 25247, 25253, 25261, 25301, 25303,
25307, 25309, 25321, 25339, 25343, 25349, 25357, 25367, 25373, 25391,
25409, 25411, 25423, 25439, 25447, 25453, 25457, 25463, 25469, 25471,
25523, 25537, 25541, 25561, 25577, 25579, 25583, 25589, 25601, 25603,
25609, 25621, 25633, 25639, 25643, 25657, 25667, 25673, 25679, 25693,
25703, 25717, 25733, 25741, 25747, 25759, 25763, 25771, 25793, 25799,
25801, 25819, 25841, 25847, 25849, 25867, 25873, 25889, 25903, 25913,
25919, 25931, 25933, 25939, 25943, 25951, 25969, 25981, 25997, 25999,
26003, 26017, 26021, 26029, 26041, 26053, 26083, 26099, 26107, 26111,
26113, 26119, 26141, 26153, 26161, 26171, 26177, 26183, 26189, 26203,
26209, 26227, 26237, 26249, 26251, 26261, 26263, 26267, 26293, 26297,
26309, 26317, 26321, 26339, 26347, 26357, 26371, 26387, 26393, 26399,
26407, 26417, 26423, 26431, 26437, 26449, 26459, 26479, 26489, 26497,
26501, 26513, 26539, 26557, 26561, 26573, 26591, 26597, 26627, 26633,
26641, 26647, 26669, 26681, 26683, 26687, 26693, 26699, 26701, 26711,
26713, 26717, 26723, 26729, 26731, 26737, 26759, 26777, 26783, 26801,
26813, 26821, 26833, 26839, 26849, 26861, 26863, 26879, 26881, 26891,
26893, 26903, 26921, 26927, 26947, 26951, 26953, 26959, 26981, 26987,
26993, 27011, 27017, 27031, 27043, 27059, 27061, 27067, 27073, 27077,
27091, 27103, 27107, 27109, 27127, 27143, 27179, 27191, 27197, 27211,
27239, 27241, 27253, 27259, 27271, 27277, 27281, 27283, 27299, 27329,
27337, 27361, 27367, 27397, 27407, 27409, 27427, 27431, 27437, 27449,
27457, 27479, 27481, 27487, 27509, 27527, 27529, 27539, 27541, 27551,
27581, 27583, 27611, 27617, 27631, 27647, 27653, 27673, 27689, 27691,
27697, 27701, 27733, 27737, 27739, 27743, 27749, 27751, 27763, 27767,
27773, 27779, 27791, 27793, 27799, 27803, 27809, 27817, 27823, 27827,
27847, 27851, 27883, 27893, 27901, 27917, 27919, 27941, 27943, 27947,
27953, 27961, 27967, 27983, 27997, 28001, 28019, 28027, 28031, 28051,
28057, 28069, 28081, 28087, 28097, 28099, 28109, 28111, 28123, 28151,
28163, 28181, 28183, 28201, 28211, 28219, 28229, 28277, 28279, 28283,
28289, 28297, 28307, 28309, 28319, 28349, 28351, 28387, 28393, 28403,
28409, 28411, 28429, 28433, 28439, 28447, 28463, 28477, 28493, 28499,
28513, 28517, 28537, 28541, 28547, 28549, 28559, 28571, 28573, 28579,
28591, 28597, 28603, 28607, 28619, 28621, 28627, 28631, 28643, 28649,
28657, 28661, 28663, 28669, 28687, 28697, 28703, 28711, 28723, 28729,
28751, 28753, 28759, 28771, 28789, 28793, 28807, 28813, 28817, 28837,
28843, 28859, 28867, 28871, 28879, 28901, 28909, 28921, 28927, 28933,
28949, 28961, 28979, 29009, 29017, 29021, 29023, 29027, 29033, 29059,
29063, 29077, 29101, 29123, 29129, 29131, 29137, 29147, 29153, 29167,
29173, 29179, 29191, 29201, 29207, 29209, 29221, 29231, 29243, 29251,
29269, 29287, 29297, 29303, 29311, 29327, 29333, 29339, 29347, 29363,
29383, 29387, 29389, 29399, 29401, 29411, 29423, 29429, 29437, 29443,
29453, 29473, 29483, 29501, 29527, 29531, 29537, 29567, 29569, 29573,
29581, 29587, 29599, 29611, 29629, 29633, 29641, 29663, 29669, 29671,
29683, 29717, 29723, 29741, 29753, 29759, 29761, 29789, 29803, 29819,
29833, 29837, 29851, 29863, 29867, 29873, 29879, 29881, 29917, 29921,
29927, 29947, 29959, 29983, 29989, 30011, 30013, 30029, 30047, 30059,
30071, 30089, 30091, 30097, 30103, 30109, 30113, 30119, 30133, 30137,
30139, 30161, 30169, 30181, 30187, 30197, 30203, 30211, 30223, 30241,
30253, 30259, 30269, 30271, 30293, 30307, 30313, 30319, 30323, 30341,
30347, 30367, 30389, 30391, 30403, 30427, 30431, 30449, 30467, 30469,
30491, 30493, 30497, 30509, 30517, 30529, 30539, 30553, 30557, 30559,
30577, 30593, 30631, 30637, 30643, 30649, 30661, 30671, 30677, 30689,
30697, 30703, 30707, 30713, 30727, 30757, 30763, 30773, 30781, 30803,
30809, 30817, 30829, 30839, 30841, 30851, 30853, 30859, 30869, 30871,
30881, 30893, 30911, 30931, 30937, 30941, 30949, 30971, 30977, 30983,
31013, 31019, 31033, 31039, 31051, 31063, 31069, 31079, 31081, 31091,
31121, 31123, 31139, 31147, 31151, 31153, 31159, 31177, 31181, 31183,
31189, 31193, 31219, 31223, 31231, 31237, 31247, 31249, 31253, 31259,
31267, 31271, 31277, 31307, 31319, 31321, 31327, 31333, 31337, 31357,
31379, 31387, 31391, 31393, 31397, 31469, 31477, 31481, 31489, 31511,
31513, 31517, 31531, 31541, 31543, 31547, 31567, 31573, 31583, 31601,
31607, 31627, 31643, 31649, 31657, 31663, 31667, 31687, 31699, 31721,
31723, 31727, 31729, 31741, 31751, 31769, 31771, 31793, 31799, 31817,
31847, 31849, 31859, 31873, 31883, 31891, 31907, 31957, 31963, 31973,
31981, 31991, 32003, 32009, 32027, 32029, 32051, 32057, 32059, 32063,
32069, 32077, 32083, 32089, 32099, 32117, 32119, 32141, 32143, 32159,
32173, 32183, 32189, 32191, 32203, 32213, 32233, 32237, 32251, 32257,
32261, 32297, 32299, 32303, 32309, 32321, 32323, 32327, 32341, 32353,
32359, 32363, 32369, 32371, 32377, 32381, 32401, 32411, 32413, 32423,
32429, 32441, 32443, 32467, 32479, 32491, 32497, 32503, 32507, 32531,
32533, 32537, 32561, 32563, 32569, 32573, 32579, 32587, 32603, 32609,
32611, 32621, 32633, 32647, 32653, 32687, 32693, 32707, 32713, 32717,
32719, 32749, 32771, 32779, 32783, 32789, 32797, 32801, 32803, 32831,
32833, 32839, 32843, 32869, 32887, 32909, 32911, 32917, 32933, 32939,
32941, 32957, 32969, 32971, 32983, 32987, 32993, 32999, 33013, 33023,
33029, 33037, 33049, 33053, 33071, 33073, 33083, 33091, 33107, 33113,
33119, 33149, 33151, 33161, 33179, 33181, 33191, 33199, 33203, 33211,
33223, 33247, 33287, 33289, 33301, 33311, 33317, 33329, 33331, 33343,
33347, 33349, 33353, 33359, 33377, 33391, 33403, 33409, 33413, 33427,
33457, 33461, 33469, 33479, 33487, 33493, 33503, 33521, 33529, 33533,
33547, 33563, 33569, 33577, 33581, 33587, 33589, 33599, 33601, 33613,
33617, 33619, 33623, 33629, 33637, 33641, 33647, 33679, 33703, 33713,
33721, 33739, 33749, 33751, 33757, 33767, 33769, 33773, 33791, 33797,
33809, 33811, 33827, 33829, 33851, 33857, 33863, 33871, 33889, 33893,
33911, 33923, 33931, 33937, 33941, 33961, 33967, 33997, 34019, 34031,
34033, 34039, 34057, 34061, 34123, 34127, 34129, 34141, 34147, 34157,
34159, 34171, 34183, 34211, 34213, 34217, 34231, 34253, 34259, 34261,
34267, 34273, 34283, 34297, 34301, 34303, 34313, 34319, 34327, 34337,
34351, 34361, 34367, 34369, 34381, 34403, 34421, 34429, 34439, 34457,
34469, 34471, 34483, 34487, 34499, 34501, 34511, 34513, 34519, 34537,
34543, 34549, 34583, 34589, 34591, 34603, 34607, 34613, 34631, 34649,
34651, 34667, 34673, 34679, 34687, 34693, 34703, 34721, 34729, 34739,
34747, 34757, 34759, 34763, 34781, 34807, 34819, 34841, 34843, 34847,
34849, 34871, 34877, 34883, 34897, 34913, 34919, 34939, 34949, 34961,
34963, 34981, 35023, 35027, 35051, 35053, 35059, 35069, 35081, 35083,
35089, 35099, 35107, 35111, 35117, 35129, 35141, 35149, 35153, 35159,
35171, 35201, 35221, 35227, 35251, 35257, 35267, 35279, 35281, 35291,
35311, 35317, 35323, 35327, 35339, 35353, 35363, 35381, 35393, 35401,
35407, 35419, 35423, 35437, 35447, 35449, 35461, 35491, 35507, 35509,
35521, 35527, 35531, 35533, 35537, 35543, 35569, 35573, 35591, 35593,
35597, 35603, 35617, 35671, 35677, 35729, 35731, 35747, 35753, 35759,
35771, 35797, 35801, 35803, 35809, 35831, 35837, 35839, 35851, 35863,
35869, 35879, 35897, 35899, 35911, 35923, 35933, 35951, 35963, 35969,
35977, 35983, 35993, 35999, 36007, 36011, 36013, 36017, 36037, 36061,
36067, 36073, 36083, 36097, 36107, 36109, 36131, 36137, 36151, 36161,
36187, 36191, 36209, 36217, 36229, 36241, 36251, 36263, 36269, 36277,
36293, 36299, 36307, 36313, 36319, 36341, 36343, 36353, 36373, 36383,
36389, 36433, 36451, 36457, 36467, 36469, 36473, 36479, 36493, 36497,
36523, 36527, 36529, 36541, 36551, 36559, 36563, 36571, 36583, 36587,
36599, 36607, 36629, 36637, 36643, 36653, 36671, 36677, 36683, 36691,
36697, 36709, 36713, 36721, 36739, 36749, 36761, 36767, 36779, 36781,
36787, 36791, 36793, 36809, 36821, 36833, 36847, 36857, 36871, 36877,
36887, 36899, 36901, 36913, 36919, 36923, 36929, 36931, 36943, 36947,
36973, 36979, 36997, 37003, 37013, 37019, 37021, 37039, 37049, 37057,
37061, 37087, 37097, 37117, 37123, 37139, 37159, 37171, 37181, 37189,
37199, 37201, 37217, 37223, 37243, 37253, 37273, 37277, 37307, 37309,
37313, 37321, 37337, 37339, 37357, 37361, 37363, 37369, 37379, 37397,
37409, 37423, 37441, 37447, 37463, 37483, 37489, 37493, 37501, 37507,
37511, 37517, 37529, 37537, 37547, 37549, 37561, 37567, 37571, 37573,
37579, 37589, 37591, 37607, 37619, 37633, 37643, 37649, 37657, 37663,
37691, 37693, 37699, 37717, 37747, 37781, 37783, 37799, 37811, 37813,
37831, 37847, 37853, 37861, 37871, 37879, 37889, 37897, 37907, 37951,
37957, 37963, 37967, 37987, 37991, 37993, 37997, 38011, 38039, 38047,
38053, 38069, 38083, 38113, 38119, 38149, 38153, 38167, 38177, 38183,
38189, 38197, 38201, 38219, 38231, 38237, 38239, 38261, 38273, 38281,
38287, 38299, 38303, 38317, 38321, 38327, 38329, 38333, 38351, 38371,
38377, 38393, 38431, 38447, 38449, 38453, 38459, 38461, 38501, 38543,
38557, 38561, 38567, 38569, 38593, 38603, 38609, 38611, 38629, 38639,
38651, 38653, 38669, 38671, 38677, 38693, 38699, 38707, 38711, 38713,
38723, 38729, 38737, 38747, 38749, 38767, 38783, 38791, 38803, 38821,
38833, 38839, 38851, 38861, 38867, 38873, 38891, 38903, 38917, 38921,
38923, 38933, 38953, 38959, 38971, 38977, 38993, 39019, 39023, 39041,
39043, 39047, 39079, 39089, 39097, 39103, 39107, 39113, 39119, 39133,
39139, 39157, 39161, 39163, 39181, 39191, 39199, 39209, 39217, 39227,
39229, 39233, 39239, 39241, 39251, 39293, 39301, 39313, 39317, 39323,
39341, 39343, 39359, 39367, 39371, 39373, 39383, 39397, 39409, 39419,
39439, 39443, 39451, 39461, 39499, 39503, 39509, 39511, 39521, 39541,
39551, 39563, 39569, 39581, 39607, 39619, 39623, 39631, 39659, 39667,
39671, 39679, 39703, 39709, 39719, 39727, 39733, 39749, 39761, 39769,
39779, 39791, 39799, 39821, 39827, 39829, 39839, 39841, 39847, 39857,
39863, 39869, 39877, 39883, 39887, 39901, 39929, 39937, 39953, 39971,
39979, 39983, 39989, 40009, 40013, 40031, 40037, 40039, 40063, 40087,
40093, 40099, 40111, 40123, 40127, 40129, 40151, 40153, 40163, 40169,
40177, 40189, 40193, 40213, 40231, 40237, 40241, 40253, 40277, 40283,
40289, 40343, 40351, 40357, 40361, 40387, 40423, 40427, 40429, 40433,
40459, 40471, 40483, 40487, 40493, 40499, 40507, 40519, 40529, 40531,
40543, 40559, 40577, 40583, 40591, 40597, 40609, 40627, 40637, 40639,
40693, 40697, 40699, 40709, 40739, 40751, 40759, 40763, 40771, 40787,
40801, 40813, 40819, 40823, 40829, 40841, 40847, 40849, 40853, 40867,
40879, 40883, 40897, 40903, 40927, 40933, 40939, 40949, 40961, 40973,
40993, 41011, 41017, 41023, 41039, 41047, 41051, 41057, 41077, 41081,
41113, 41117, 41131, 41141, 41143, 41149, 41161, 41177, 41179, 41183,
41189, 41201, 41203, 41213, 41221, 41227, 41231, 41233, 41243, 41257,
41263, 41269, 41281, 41299, 41333, 41341, 41351, 41357, 41381, 41387,
41389, 41399, 41411, 41413, 41443, 41453, 41467, 41479, 41491, 41507,
41513, 41519, 41521, 41539, 41543, 41549, 41579, 41593, 41597, 41603,
41609, 41611, 41617, 41621, 41627, 41641, 41647, 41651, 41659, 41669,
41681, 41687, 41719, 41729, 41737, 41759, 41761, 41771, 41777, 41801,
41809, 41813, 41843, 41849, 41851, 41863, 41879, 41887, 41893, 41897,
41903, 41911, 41927, 41941, 41947, 41953, 41957, 41959, 41969, 41981,
41983, 41999, 42013, 42017, 42019, 42023, 42043, 42061, 42071, 42073,
42083, 42089, 42101, 42131, 42139, 42157, 42169, 42179, 42181, 42187,
42193, 42197, 42209, 42221, 42223, 42227, 42239, 42257, 42281, 42283,
42293, 42299, 42307, 42323, 42331, 42337, 42349, 42359, 42373, 42379,
42391, 42397, 42403, 42407, 42409, 42433, 42437, 42443, 42451, 42457,
42461, 42463, 42467, 42473, 42487, 42491, 42499, 42509, 42533, 42557,
42569, 42571, 42577, 42589, 42611, 42641, 42643, 42649, 42667, 42677,
42683, 42689, 42697, 42701, 42703, 42709, 42719, 42727, 42737, 42743,
42751, 42767, 42773, 42787, 42793, 42797, 42821, 42829, 42839, 42841,
42853, 42859, 42863, 42899, 42901, 42923, 42929, 42937, 42943, 42953,
42961, 42967, 42979, 42989, 43003, 43013, 43019, 43037, 43049, 43051,
43063, 43067, 43093, 43103, 43117, 43133, 43151, 43159, 43177, 43189,
43201, 43207, 43223, 43237, 43261, 43271, 43283, 43291, 43313, 43319,
43321, 43331, 43391, 43397, 43399, 43403, 43411, 43427, 43441, 43451,
43457, 43481, 43487, 43499, 43517, 43541, 43543, 43573, 43577, 43579,
43591, 43597, 43607, 43609, 43613, 43627, 43633, 43649, 43651, 43661,
43669, 43691, 43711, 43717, 43721, 43753, 43759, 43777, 43781, 43783,
43787, 43789, 43793, 43801, 43853, 43867, 43889, 43891, 43913, 43933,
43943, 43951, 43961, 43963, 43969, 43973, 43987, 43991, 43997, 44017,
44021, 44027, 44029, 44041, 44053, 44059, 44071, 44087, 44089, 44101,
44111, 44119, 44123, 44129, 44131, 44159, 44171, 44179, 44189, 44201,
44203, 44207, 44221, 44249, 44257, 44263, 44267, 44269, 44273, 44279,
44281, 44293, 44351, 44357, 44371, 44381, 44383, 44389, 44417, 44449,
44453, 44483, 44491, 44497, 44501, 44507, 44519, 44531, 44533, 44537,
44543, 44549, 44563, 44579, 44587, 44617, 44621, 44623, 44633, 44641,
44647, 44651, 44657, 44683, 44687, 44699, 44701, 44711, 44729, 44741,
44753, 44771, 44773, 44777, 44789, 44797, 44809, 44819, 44839, 44843,
44851, 44867, 44879, 44887, 44893, 44909, 44917, 44927, 44939, 44953,
44959, 44963, 44971, 44983, 44987, 45007, 45013, 45053, 45061, 45077,
45083, 45119, 45121, 45127, 45131, 45137, 45139, 45161, 45179, 45181,
45191, 45197, 45233, 45247, 45259, 45263, 45281, 45289, 45293, 45307,
45317, 45319, 45329, 45337, 45341, 45343, 45361, 45377, 45389, 45403,
45413, 45427, 45433, 45439, 45481, 45491, 45497, 45503, 45523, 45533,
45541, 45553, 45557, 45569, 45587, 45589, 45599, 45613, 45631, 45641,
45659, 45667, 45673, 45677, 45691, 45697, 45707, 45737, 45751, 45757,
45763, 45767, 45779, 45817, 45821, 45823, 45827, 45833, 45841, 45853,
45863, 45869, 45887, 45893, 45943, 45949, 45953, 45959, 45971, 45979,
45989, 46021, 46027, 46049, 46051, 46061, 46073, 46091, 46093, 46099,
46103, 46133, 46141, 46147, 46153, 46171, 46181, 46183, 46187, 46199,
46219, 46229, 46237, 46261, 46271, 46273, 46279, 46301, 46307, 46309,
46327, 46337, 46349, 46351, 46381, 46399, 46411, 46439, 46441, 46447,
46451, 46457, 46471, 46477, 46489, 46499, 46507, 46511, 46523, 46549,
46559, 46567, 46573, 46589, 46591, 46601, 46619, 46633, 46639, 46643,
46649, 46663, 46679, 46681, 46687, 46691, 46703, 46723, 46727, 46747,
46751, 46757, 46769, 46771, 46807, 46811, 46817, 46819, 46829, 46831,
46853, 46861, 46867, 46877, 46889, 46901, 46919, 46933, 46957, 46993,
46997, 47017, 47041, 47051, 47057, 47059, 47087, 47093, 47111, 47119,
47123, 47129, 47137, 47143, 47147, 47149, 47161, 47189, 47207, 47221,
47237, 47251, 47269, 47279, 47287, 47293, 47297, 47303, 47309, 47317,
47339, 47351, 47353, 47363, 47381, 47387, 47389, 47407, 47417, 47419,
47431, 47441, 47459, 47491, 47497, 47501, 47507, 47513, 47521, 47527,
47533, 47543, 47563, 47569, 47581, 47591, 47599, 47609, 47623, 47629,
47639, 47653, 47657, 47659, 47681, 47699, 47701, 47711, 47713, 47717,
47737, 47741, 47743, 47777, 47779, 47791, 47797, 47807, 47809, 47819,
47837, 47843, 47857, 47869, 47881, 47903, 47911, 47917, 47933, 47939,
47947, 47951, 47963, 47969, 47977, 47981, 48017, 48023, 48029, 48049,
48073, 48079, 48091, 48109, 48119, 48121, 48131, 48157, 48163, 48179,
48187, 48193, 48197, 48221, 48239, 48247, 48259, 48271, 48281, 48299,
48311, 48313, 48337, 48341, 48353, 48371, 48383, 48397, 48407, 48409,
48413, 48437, 48449, 48463, 48473, 48479, 48481, 48487, 48491, 48497,
48523, 48527, 48533, 48539, 48541, 48563, 48571, 48589, 48593, 48611,
48619, 48623, 48647, 48649, 48661, 48673, 48677, 48679, 48731, 48733,
48751, 48757, 48761, 48767, 48779, 48781, 48787, 48799, 48809, 48817,
48821, 48823, 48847, 48857, 48859, 48869, 48871, 48883, 48889, 48907,
48947, 48953, 48973, 48989, 48991, 49003, 49009, 49019, 49031, 49033,
49037, 49043, 49057, 49069, 49081, 49103, 49109, 49117, 49121, 49123,
49139, 49157, 49169, 49171, 49177, 49193, 49199, 49201, 49207, 49211,
49223, 49253, 49261, 49277, 49279, 49297, 49307, 49331, 49333, 49339,
49363, 49367, 49369, 49391, 49393, 49409, 49411, 49417, 49429, 49433,
49451, 49459, 49463, 49477, 49481, 49499, 49523, 49529, 49531, 49537,
49547, 49549, 49559, 49597, 49603, 49613, 49627, 49633, 49639, 49663,
49667, 49669, 49681, 49697, 49711, 49727, 49739, 49741, 49747, 49757,
49783, 49787, 49789, 49801, 49807, 49811, 49823, 49831, 49843, 49853,
49871, 49877, 49891, 49919, 49921, 49927, 49937, 49939, 49943, 49957,
49991, 49993, 49999, 50021, 50023, 50033, 50047, 50051, 50053, 50069,
50077, 50087, 50093, 50101, 50111, 50119, 50123, 50129, 50131, 50147,
50153, 50159, 50177, 50207, 50221, 50227, 50231, 50261, 50263, 50273,
50287, 50291, 50311, 50321, 50329, 50333, 50341, 50359, 50363, 50377,
50383, 50387, 50411, 50417, 50423, 50441, 50459, 50461, 50497, 50503,
50513, 50527, 50539, 50543, 50549, 50551, 50581, 50587, 50591, 50593,
50599, 50627, 50647, 50651, 50671, 50683, 50707, 50723, 50741, 50753,
50767, 50773, 50777, 50789, 50821, 50833, 50839, 50849, 50857, 50867,
50873, 50891, 50893, 50909, 50923, 50929, 50951, 50957, 50969, 50971,
50989, 50993, 51001, 51031, 51043, 51047, 51059, 51061, 51071, 51109,
51131, 51133, 51137, 51151, 51157, 51169, 51193, 51197, 51199, 51203,
51217, 51229, 51239, 51241, 51257, 51263, 51283, 51287, 51307, 51329,
51341, 51343, 51347, 51349, 51361, 51383, 51407, 51413, 51419, 51421,
51427, 51431, 51437, 51439, 51449, 51461, 51473, 51479, 51481, 51487,
51503, 51511, 51517, 51521, 51539, 51551, 51563, 51577, 51581, 51593,
51599, 51607, 51613, 51631, 51637, 51647, 51659, 51673, 51679, 51683,
51691, 51713, 51719, 51721, 51749, 51767, 51769, 51787, 51797, 51803,
51817, 51827, 51829, 51839, 51853, 51859, 51869, 51871, 51893, 51899,
51907, 51913, 51929, 51941, 51949, 51971, 51973, 51977, 51991, 52009,
52021, 52027, 52051, 52057, 52067, 52069, 52081, 52103, 52121, 52127,
52147, 52153, 52163, 52177, 52181, 52183, 52189, 52201, 52223, 52237,
52249, 52253, 52259, 52267, 52289, 52291, 52301, 52313, 52321, 52361,
52363, 52369, 52379, 52387, 52391, 52433, 52453, 52457, 52489, 52501,
52511, 52517, 52529, 52541, 52543, 52553, 52561, 52567, 52571, 52579,
52583, 52609, 52627, 52631, 52639, 52667, 52673, 52691, 52697, 52709,
52711, 52721, 52727, 52733, 52747, 52757, 52769, 52783, 52807, 52813,
52817, 52837, 52859, 52861, 52879, 52883, 52889, 52901, 52903, 52919,
52937, 52951, 52957, 52963, 52967, 52973, 52981, 52999, 53003, 53017,
53047, 53051, 53069, 53077, 53087, 53089, 53093, 53101, 53113, 53117,
53129, 53147, 53149, 53161, 53171, 53173, 53189, 53197, 53201, 53231,
53233, 53239, 53267, 53269, 53279, 53281, 53299, 53309, 53323, 53327,
53353, 53359, 53377, 53381, 53401, 53407, 53411, 53419, 53437, 53441,
53453, 53479, 53503, 53507, 53527, 53549, 53551, 53569, 53591, 53593,
53597, 53609, 53611, 53617, 53623, 53629, 53633, 53639, 53653, 53657,
53681, 53693, 53699, 53717, 53719, 53731, 53759, 53773, 53777, 53783,
53791, 53813, 53819, 53831, 53849, 53857, 53861, 53881, 53887, 53891,
53897, 53899, 53917, 53923, 53927, 53939, 53951, 53959, 53987, 53993,
54001, 54011, 54013, 54037, 54049, 54059, 54083, 54091, 54101, 54121,
54133, 54139, 54151, 54163, 54167, 54181, 54193, 54217, 54251, 54269,
54277, 54287, 54293, 54311, 54319, 54323, 54331, 54347, 54361, 54367,
54371, 54377, 54401, 54403, 54409, 54413, 54419, 54421, 54437, 54443,
54449, 54469, 54493, 54497, 54499, 54503, 54517, 54521, 54539, 54541,
54547, 54559, 54563, 54577, 54581, 54583, 54601, 54617, 54623, 54629,
54631, 54647, 54667, 54673, 54679, 54709, 54713, 54721, 54727, 54751,
54767, 54773, 54779, 54787, 54799, 54829, 54833, 54851, 54869, 54877,
54881, 54907, 54917, 54919, 54941, 54949, 54959, 54973, 54979, 54983,
55001, 55009, 55021, 55049, 55051, 55057, 55061, 55073, 55079, 55103,
55109, 55117, 55127, 55147, 55163, 55171, 55201, 55207, 55213, 55217,
55219, 55229, 55243, 55249, 55259, 55291, 55313, 55331, 55333, 55337,
55339, 55343, 55351, 55373, 55381, 55399, 55411, 55439, 55441, 55457,
55469, 55487, 55501, 55511, 55529, 55541, 55547, 55579, 55589, 55603,
55609, 55619, 55621, 55631, 55633, 55639, 55661, 55663, 55667, 55673,
55681, 55691, 55697, 55711, 55717, 55721, 55733, 55763, 55787, 55793,
55799, 55807, 55813, 55817, 55819, 55823, 55829, 55837, 55843, 55849,
55871, 55889, 55897, 55901, 55903, 55921, 55927, 55931, 55933, 55949,
55967, 55987, 55997, 56003, 56009, 56039, 56041, 56053, 56081, 56087,
56093, 56099, 56101, 56113, 56123, 56131, 56149, 56167, 56171, 56179,
56197, 56207, 56209, 56237, 56239, 56249, 56263, 56267, 56269, 56299,
56311, 56333, 56359, 56369, 56377, 56383, 56393, 56401, 56417, 56431,
56437, 56443, 56453, 56467, 56473, 56477, 56479, 56489, 56501, 56503,
56509, 56519, 56527, 56531, 56533, 56543, 56569, 56591, 56597, 56599,
56611, 56629, 56633, 56659, 56663, 56671, 56681, 56687, 56701, 56711,
56713, 56731, 56737, 56747, 56767, 56773, 56779, 56783, 56807, 56809,
56813, 56821, 56827, 56843, 56857, 56873, 56891, 56893, 56897, 56909,
56911, 56921, 56923, 56929, 56941, 56951, 56957, 56963, 56983, 56989,
56993, 56999, 57037, 57041, 57047, 57059, 57073, 57077, 57089, 57097,
57107, 57119, 57131, 57139, 57143, 57149, 57163, 57173, 57179, 57191,
57193, 57203, 57221, 57223, 57241, 57251, 57259, 57269, 57271, 57283,
57287, 57301, 57329, 57331, 57347, 57349, 57367, 57373, 57383, 57389,
57397, 57413, 57427, 57457, 57467, 57487, 57493, 57503, 57527, 57529,
57557, 57559, 57571, 57587, 57593, 57601, 57637, 57641, 57649, 57653,
57667, 57679, 57689, 57697, 57709, 57713, 57719, 57727, 57731, 57737,
57751, 57773, 57781, 57787, 57791, 57793, 57803, 57809, 57829, 57839,
57847, 57853, 57859, 57881, 57899, 57901, 57917, 57923, 57943, 57947,
57973, 57977, 57991, 58013, 58027, 58031, 58043, 58049, 58057, 58061,
58067, 58073, 58099, 58109, 58111, 58129, 58147, 58151, 58153, 58169,
58171, 58189, 58193, 58199, 58207, 58211, 58217, 58229, 58231, 58237,
58243, 58271, 58309, 58313, 58321, 58337, 58363, 58367, 58369, 58379,
58391, 58393, 58403, 58411, 58417, 58427, 58439, 58441, 58451, 58453,
58477, 58481, 58511, 58537, 58543, 58549, 58567, 58573, 58579, 58601,
58603, 58613, 58631, 58657, 58661, 58679, 58687, 58693, 58699, 58711,
58727, 58733, 58741, 58757, 58763, 58771, 58787, 58789, 58831, 58889,
58897, 58901, 58907, 58909, 58913, 58921, 58937, 58943, 58963, 58967,
58979, 58991, 58997, 59009, 59011, 59021, 59023, 59029, 59051, 59053,
59063, 59069, 59077, 59083, 59093, 59107, 59113, 59119, 59123, 59141,
59149, 59159, 59167, 59183, 59197, 59207, 59209, 59219, 59221, 59233,
59239, 59243, 59263, 59273, 59281, 59333, 59341, 59351, 59357, 59359,
59369, 59377, 59387, 59393, 59399, 59407, 59417, 59419, 59441, 59443,
59447, 59453, 59467, 59471, 59473, 59497, 59509, 59513, 59539, 59557,
59561, 59567, 59581, 59611, 59617, 59621, 59627, 59629, 59651, 59659,
59663, 59669, 59671, 59693, 59699, 59707, 59723, 59729, 59743, 59747,
59753, 59771, 59779, 59791, 59797, 59809, 59833, 59863, 59879, 59887,
59921, 59929, 59951, 59957, 59971, 59981, 59999, 60013, 60017, 60029,
60037, 60041, 60077, 60083, 60089, 60091, 60101, 60103, 60107, 60127,
60133, 60139, 60149, 60161, 60167, 60169, 60209, 60217, 60223, 60251,
60257, 60259, 60271, 60289, 60293, 60317, 60331, 60337, 60343, 60353,
60373, 60383, 60397, 60413, 60427, 60443, 60449, 60457, 60493, 60497,
60509, 60521, 60527, 60539, 60589, 60601, 60607, 60611, 60617, 60623,
60631, 60637, 60647, 60649, 60659, 60661, 60679, 60689, 60703, 60719,
60727, 60733, 60737, 60757, 60761, 60763, 60773, 60779, 60793, 60811,
60821, 60859, 60869, 60887, 60889, 60899, 60901, 60913, 60917, 60919,
60923, 60937, 60943, 60953, 60961, 61001, 61007, 61027, 61031, 61043,
61051, 61057, 61091, 61099, 61121, 61129, 61141, 61151, 61153, 61169,
61211, 61223, 61231, 61253, 61261, 61283, 61291, 61297, 61331, 61333,
61339, 61343, 61357, 61363, 61379, 61381, 61403, 61409, 61417, 61441,
61463, 61469, 61471, 61483, 61487, 61493, 61507, 61511, 61519, 61543,
61547, 61553, 61559, 61561, 61583, 61603, 61609, 61613, 61627, 61631,
61637, 61643, 61651, 61657, 61667, 61673, 61681, 61687, 61703, 61717,
61723, 61729, 61751, 61757, 61781, 61813, 61819, 61837, 61843, 61861,
61871, 61879, 61909, 61927, 61933, 61949, 61961, 61967, 61979, 61981,
61987, 61991, 62003, 62011, 62017, 62039, 62047, 62053, 62057, 62071,
62081, 62099, 62119, 62129, 62131, 62137, 62141, 62143, 62171, 62189,
62191, 62201, 62207, 62213, 62219, 62233, 62273, 62297, 62299, 62303,
62311, 62323, 62327, 62347, 62351, 62383, 62401, 62417, 62423, 62459,
62467, 62473, 62477, 62483, 62497, 62501, 62507, 62533, 62539, 62549,
62563, 62581, 62591, 62597, 62603, 62617, 62627, 62633, 62639, 62653,
62659, 62683, 62687, 62701, 62723, 62731, 62743, 62753, 62761, 62773,
62791, 62801, 62819, 62827, 62851, 62861, 62869, 62873, 62897, 62903,
62921, 62927, 62929, 62939, 62969, 62971, 62981, 62983, 62987, 62989,
63029, 63031, 63059, 63067, 63073, 63079, 63097, 63103, 63113, 63127,
63131, 63149, 63179, 63197, 63199, 63211, 63241, 63247, 63277, 63281,
63299, 63311, 63313, 63317, 63331, 63337, 63347, 63353, 63361, 63367,
63377, 63389, 63391, 63397, 63409, 63419, 63421, 63439, 63443, 63463,
63467, 63473, 63487, 63493, 63499, 63521, 63527, 63533, 63541, 63559,
63577, 63587, 63589, 63599, 63601, 63607, 63611, 63617, 63629, 63647,
63649, 63659, 63667, 63671, 63689, 63691, 63697, 63703, 63709, 63719,
63727, 63737, 63743, 63761, 63773, 63781, 63793, 63799, 63803, 63809,
63823, 63839, 63841, 63853, 63857, 63863, 63901, 63907, 63913, 63929,
63949, 63977, 63997, 64007, 64013, 64019, 64033, 64037, 64063, 64067,
64081, 64091, 64109, 64123, 64151, 64153, 64157, 64171, 64187, 64189,
64217, 64223, 64231, 64237, 64271, 64279, 64283, 64301, 64303, 64319,
64327, 64333, 64373, 64381, 64399, 64403, 64433, 64439, 64451, 64453,
64483, 64489, 64499, 64513, 64553, 64567, 64577, 64579, 64591, 64601,
64609, 64613, 64621, 64627, 64633, 64661, 64663, 64667, 64679, 64693,
64709, 64717, 64747, 64763, 64781, 64783, 64793, 64811, 64817, 64849,
64853, 64871, 64877, 64879, 64891, 64901, 64919, 64921, 64927, 64937,
64951, 64969, 64997, 65003, 65011, 65027, 65029, 65033, 65053, 65063,
65071, 65089, 65099, 65101, 65111, 65119, 65123, 65129, 65141, 65147,
65167, 65171, 65173, 65179, 65183, 65203, 65213, 65239, 65257, 65267,
65269, 65287, 65293, 65309, 65323, 65327, 65353, 65357, 65371, 65381,
65393, 65407, 65413, 65419, 65423, 65437, 65447, 65449, 65479, 65497,
65519, 65521, 65537, 65539, 65543, 65551, 65557, 65563, 65579, 65581,
65587, 65599, 65609, 65617, 65629, 65633, 65647, 65651, 65657, 65677,
65687, 65699, 65701, 65707, 65713, 65717, 65719, 65729, 65731, 65761,
65777, 65789, 65809, 65827, 65831, 65837, 65839, 65843, 65851, 65867,
65881, 65899, 65921, 65927, 65929, 65951, 65957, 65963, 65981, 65983,
65993, 66029, 66037, 66041, 66047, 66067, 66071, 66083, 66089, 66103,
66107, 66109, 66137, 66161, 66169, 66173, 66179, 66191, 66221, 66239,
66271, 66293, 66301, 66337, 66343, 66347, 66359, 66361, 66373, 66377,
66383, 66403, 66413, 66431, 66449, 66457, 66463, 66467, 66491, 66499,
66509, 66523, 66529, 66533, 66541, 66553, 66569, 66571, 66587, 66593,
66601, 66617, 66629, 66643, 66653, 66683, 66697, 66701, 66713, 66721,
66733, 66739, 66749, 66751, 66763, 66791, 66797, 66809, 66821, 66841,
66851, 66853, 66863, 66877, 66883, 66889, 66919, 66923, 66931, 66943,
66947, 66949, 66959, 66973, 66977, 67003, 67021, 67033, 67043, 67049,
67057, 67061, 67073, 67079, 67103, 67121, 67129, 67139, 67141, 67153,
67157, 67169, 67181, 67187, 67189, 67211, 67213, 67217, 67219, 67231,
67247, 67261, 67271, 67273, 67289, 67307, 67339, 67343, 67349, 67369,
67391, 67399, 67409, 67411, 67421, 67427, 67429, 67433, 67447, 67453,
67477, 67481, 67489, 67493, 67499, 67511, 67523, 67531, 67537, 67547,
67559, 67567, 67577, 67579, 67589, 67601, 67607, 67619, 67631, 67651,
67679, 67699, 67709, 67723, 67733, 67741, 67751, 67757, 67759, 67763,
67777, 67783, 67789, 67801, 67807, 67819, 67829, 67843, 67853, 67867,
67883, 67891, 67901, 67927, 67931, 67933, 67939, 67943, 67957, 67961,
67967, 67979, 67987, 67993, 68023, 68041, 68053, 68059, 68071, 68087,
68099, 68111, 68113, 68141, 68147, 68161, 68171, 68207, 68209, 68213,
68219, 68227, 68239, 68261, 68279, 68281, 68311, 68329, 68351, 68371,
68389, 68399, 68437, 68443, 68447, 68449, 68473, 68477, 68483, 68489,
68491, 68501, 68507, 68521, 68531, 68539, 68543, 68567, 68581, 68597,
68611, 68633, 68639, 68659, 68669, 68683, 68687, 68699, 68711, 68713,
68729, 68737, 68743, 68749, 68767, 68771, 68777, 68791, 68813, 68819,
68821, 68863, 68879, 68881, 68891, 68897, 68899, 68903, 68909, 68917,
68927, 68947, 68963, 68993, 69001, 69011, 69019, 69029, 69031, 69061,
69067, 69073, 69109, 69119, 69127, 69143, 69149, 69151, 69163, 69191,
69193, 69197, 69203, 69221, 69233, 69239, 69247, 69257, 69259, 69263,
69313, 69317, 69337, 69341, 69371, 69379, 69383, 69389, 69401, 69403,
69427, 69431, 69439, 69457, 69463, 69467, 69473, 69481, 69491, 69493,
69497, 69499, 69539, 69557, 69593, 69623, 69653, 69661, 69677, 69691,
69697, 69709, 69737, 69739, 69761, 69763, 69767, 69779, 69809, 69821,
69827, 69829, 69833, 69847, 69857, 69859, 69877, 69899, 69911, 69929,
69931, 69941, 69959, 69991, 69997, 70001, 70003, 70009, 70019, 70039,
70051, 70061, 70067, 70079, 70099, 70111, 70117, 70121, 70123, 70139,
70141, 70157, 70163, 70177, 70181, 70183, 70199, 70201, 70207, 70223,
70229, 70237, 70241, 70249, 70271, 70289, 70297, 70309, 70313, 70321,
70327, 70351, 70373, 70379, 70381, 70393, 70423, 70429, 70439, 70451,
70457, 70459, 70481, 70487, 70489, 70501, 70507, 70529, 70537, 70549,
70571, 70573, 70583, 70589, 70607, 70619, 70621, 70627, 70639, 70657,
70663, 70667, 70687, 70709, 70717, 70729, 70753, 70769, 70783, 70793,
70823, 70841, 70843, 70849, 70853, 70867, 70877, 70879, 70891, 70901,
70913, 70919, 70921, 70937, 70949, 70951, 70957, 70969, 70979, 70981,
70991, 70997, 70999, 71011, 71023, 71039, 71059, 71069, 71081, 71089,
71119, 71129, 71143, 71147, 71153, 71161, 71167, 71171, 71191, 71209,
71233, 71237, 71249, 71257, 71261, 71263, 71287, 71293, 71317, 71327,
71329, 71333, 71339, 71341, 71347, 71353, 71359, 71363, 71387, 71389,
71399, 71411, 71413, 71419, 71429, 71437, 71443, 71453, 71471, 71473,
71479, 71483, 71503, 71527, 71537, 71549, 71551, 71563, 71569, 71593,
71597, 71633, 71647, 71663, 71671, 71693, 71699, 71707, 71711, 71713,
71719, 71741, 71761, 71777, 71789, 71807, 71809, 71821, 71837, 71843,
71849, 71861, 71867, 71879, 71881, 71887, 71899, 71909, 71917, 71933,
71941, 71947, 71963, 71971, 71983, 71987, 71993, 71999, 72019, 72031,
72043, 72047, 72053, 72073, 72077, 72089, 72091, 72101, 72103, 72109,
72139, 72161, 72167, 72169, 72173, 72211, 72221, 72223, 72227, 72229,
72251, 72253, 72269, 72271, 72277, 72287, 72307, 72313, 72337, 72341,
72353, 72367, 72379, 72383, 72421, 72431, 72461, 72467, 72469, 72481,
72493, 72497, 72503, 72533, 72547, 72551, 72559, 72577, 72613, 72617,
72623, 72643, 72647, 72649, 72661, 72671, 72673, 72679, 72689, 72701,
72707, 72719, 72727, 72733, 72739, 72763, 72767, 72797, 72817, 72823,
72859, 72869, 72871, 72883, 72889, 72893, 72901, 72907, 72911, 72923,
72931, 72937, 72949, 72953, 72959, 72973, 72977, 72997, 73009, 73013,
73019, 73037, 73039, 73043, 73061, 73063, 73079, 73091, 73121, 73127,
73133, 73141, 73181, 73189, 73237, 73243, 73259, 73277, 73291, 73303,
73309, 73327, 73331, 73351, 73361, 73363, 73369, 73379, 73387, 73417,
73421, 73433, 73453, 73459, 73471, 73477, 73483, 73517, 73523, 73529,
73547, 73553, 73561, 73571, 73583, 73589, 73597, 73607, 73609, 73613,
73637, 73643, 73651, 73673, 73679, 73681, 73693, 73699, 73709, 73721,
73727, 73751, 73757, 73771, 73783, 73819, 73823, 73847, 73849, 73859,
73867, 73877, 73883, 73897, 73907, 73939, 73943, 73951, 73961, 73973,
73999, 74017, 74021, 74027, 74047, 74051, 74071, 74077, 74093, 74099,
74101, 74131, 74143, 74149, 74159, 74161, 74167, 74177, 74189, 74197,
74201, 74203, 74209, 74219, 74231, 74257, 74279, 74287, 74293, 74297,
74311, 74317, 74323, 74353, 74357, 74363, 74377, 74381, 74383, 74411,
74413, 74419, 74441, 74449, 74453, 74471, 74489, 74507, 74509, 74521,
74527, 74531, 74551, 74561, 74567, 74573, 74587, 74597, 74609, 74611,
74623, 74653, 74687, 74699, 74707, 74713, 74717, 74719, 74729, 74731,
74747, 74759, 74761, 74771, 74779, 74797, 74821, 74827, 74831, 74843,
74857, 74861, 74869, 74873, 74887, 74891, 74897, 74903, 74923, 74929,
74933, 74941, 74959, 75011, 75013, 75017, 75029, 75037, 75041, 75079,
75083, 75109, 75133, 75149, 75161, 75167, 75169, 75181, 75193, 75209,
75211, 75217, 75223, 75227, 75239, 75253, 75269, 75277, 75289, 75307,
75323, 75329, 75337, 75347, 75353, 75367, 75377, 75389, 75391, 75401,
75403, 75407, 75431, 75437, 75479, 75503, 75511, 75521, 75527, 75533,
75539, 75541, 75553, 75557, 75571, 75577, 75583, 75611, 75617, 75619,
75629, 75641, 75653, 75659, 75679, 75683, 75689, 75703, 75707, 75709,
75721, 75731, 75743, 75767, 75773, 75781, 75787, 75793, 75797, 75821,
75833, 75853, 75869, 75883, 75913, 75931, 75937, 75941, 75967, 75979,
75983, 75989, 75991, 75997, 76001, 76003, 76031, 76039, 76079, 76081,
76091, 76099, 76103, 76123, 76129, 76147, 76157, 76159, 76163, 76207,
76213, 76231, 76243, 76249, 76253, 76259, 76261, 76283, 76289, 76303,
76333, 76343, 76367, 76369, 76379, 76387, 76403, 76421, 76423, 76441,
76463, 76471, 76481, 76487, 76493, 76507, 76511, 76519, 76537, 76541,
76543, 76561, 76579, 76597, 76603, 76607, 76631, 76649, 76651, 76667,
76673, 76679, 76697, 76717, 76733, 76753, 76757, 76771, 76777, 76781,
76801, 76819, 76829, 76831, 76837, 76847, 76871, 76873, 76883, 76907,
76913, 76919, 76943, 76949, 76961, 76963, 76991, 77003, 77017, 77023,
77029, 77041, 77047, 77069, 77081, 77093, 77101, 77137, 77141, 77153,
77167, 77171, 77191, 77201, 77213, 77237, 77239, 77243, 77249, 77261,
77263, 77267, 77269, 77279, 77291, 77317, 77323, 77339, 77347, 77351,
77359, 77369, 77377, 77383, 77417, 77419, 77431, 77447, 77471, 77477,
77479, 77489, 77491, 77509, 77513, 77521, 77527, 77543, 77549, 77551,
77557, 77563, 77569, 77573, 77587, 77591, 77611, 77617, 77621, 77641,
77647, 77659, 77681, 77687, 77689, 77699, 77711, 77713, 77719, 77723,
77731, 77743, 77747, 77761, 77773, 77783, 77797, 77801, 77813, 77839,
77849, 77863, 77867, 77893, 77899, 77929, 77933, 77951, 77969, 77977,
77983, 77999, 78007, 78017, 78031, 78041, 78049, 78059, 78079, 78101,
78121, 78137, 78139, 78157, 78163, 78167, 78173, 78179, 78191, 78193,
78203, 78229, 78233, 78241, 78259, 78277, 78283, 78301, 78307, 78311,
78317, 78341, 78347, 78367, 78401, 78427, 78437, 78439, 78467, 78479,
78487, 78497, 78509, 78511, 78517, 78539, 78541, 78553, 78569, 78571,
78577, 78583, 78593, 78607, 78623, 78643, 78649, 78653, 78691, 78697,
78707, 78713, 78721, 78737, 78779, 78781, 78787, 78791, 78797, 78803,
78809, 78823, 78839, 78853, 78857, 78877, 78887, 78889, 78893, 78901,
78919, 78929, 78941, 78977, 78979, 78989, 79031, 79039, 79043, 79063,
79087, 79103, 79111, 79133, 79139, 79147, 79151, 79153, 79159, 79181,
79187, 79193, 79201, 79229, 79231, 79241, 79259, 79273, 79279, 79283,
79301, 79309, 79319, 79333, 79337, 79349, 79357, 79367, 79379, 79393,
79397, 79399, 79411, 79423, 79427, 79433, 79451, 79481, 79493, 79531,
79537, 79549, 79559, 79561, 79579, 79589, 79601, 79609, 79613, 79621,
79627, 79631, 79633, 79657, 79669, 79687, 79691, 79693, 79697, 79699,
79757, 79769, 79777, 79801, 79811, 79813, 79817, 79823, 79829, 79841,
79843, 79847, 79861, 79867, 79873, 79889, 79901, 79903, 79907, 79939,
79943, 79967, 79973, 79979, 79987, 79997, 79999, 80021, 80039, 80051,
80071, 80077, 80107, 80111, 80141, 80147, 80149, 80153, 80167, 80173,
80177, 80191, 80207, 80209, 80221, 80231, 80233, 80239, 80251, 80263,
80273, 80279, 80287, 80309, 80317, 80329, 80341, 80347, 80363, 80369,
80387, 80407, 80429, 80447, 80449, 80471, 80473, 80489, 80491, 80513,
80527, 80537, 80557, 80567, 80599, 80603, 80611, 80621, 80627, 80629,
80651, 80657, 80669, 80671, 80677, 80681, 80683, 80687, 80701, 80713,
80737, 80747, 80749, 80761, 80777, 80779, 80783, 80789, 80803, 80809,
80819, 80831, 80833, 80849, 80863, 80897, 80909, 80911, 80917, 80923,
80929, 80933, 80953, 80963, 80989, 81001, 81013, 81017, 81019, 81023,
81031, 81041, 81043, 81047, 81049, 81071, 81077, 81083, 81097, 81101,
81119, 81131, 81157, 81163, 81173, 81181, 81197, 81199, 81203, 81223,
81233, 81239, 81281, 81283, 81293, 81299, 81307, 81331, 81343, 81349,
81353, 81359, 81371, 81373, 81401, 81409, 81421, 81439, 81457, 81463,
81509, 81517, 81527, 81533, 81547, 81551, 81553, 81559, 81563, 81569,
81611, 81619, 81629, 81637, 81647, 81649, 81667, 81671, 81677, 81689,
81701, 81703, 81707, 81727, 81737, 81749, 81761, 81769, 81773, 81799,
81817, 81839, 81847, 81853, 81869, 81883, 81899, 81901, 81919, 81929,
81931, 81937, 81943, 81953, 81967, 81971, 81973, 82003, 82007, 82009,
82013, 82021, 82031, 82037, 82039, 82051, 82067, 82073, 82129, 82139,
82141, 82153, 82163, 82171, 82183, 82189, 82193, 82207, 82217, 82219,
82223, 82231, 82237, 82241, 82261, 82267, 82279, 82301, 82307, 82339,
82349, 82351, 82361, 82373, 82387, 82393, 82421, 82457, 82463, 82469,
82471, 82483, 82487, 82493, 82499, 82507, 82529, 82531, 82549, 82559,
82561, 82567, 82571, 82591, 82601, 82609, 82613, 82619, 82633, 82651,
82657, 82699, 82721, 82723, 82727, 82729, 82757, 82759, 82763, 82781,
82787, 82793, 82799, 82811, 82813, 82837, 82847, 82883, 82889, 82891,
82903, 82913, 82939, 82963, 82981, 82997, 83003, 83009, 83023, 83047,
83059, 83063, 83071, 83077, 83089, 83093, 83101, 83117, 83137, 83177,
83203, 83207, 83219, 83221, 83227, 83231, 83233, 83243, 83257, 83267,
83269, 83273, 83299, 83311, 83339, 83341, 83357, 83383, 83389, 83399,
83401, 83407, 83417, 83423, 83431, 83437, 83443, 83449, 83459, 83471,
83477, 83497, 83537, 83557, 83561, 83563, 83579, 83591, 83597, 83609,
83617, 83621, 83639, 83641, 83653, 83663, 83689, 83701, 83717, 83719,
83737, 83761, 83773, 83777, 83791, 83813, 83833, 83843, 83857, 83869,
83873, 83891, 83903, 83911, 83921, 83933, 83939, 83969, 83983, 83987,
84011, 84017, 84047, 84053, 84059, 84061, 84067, 84089, 84121, 84127,
84131, 84137, 84143, 84163, 84179, 84181, 84191, 84199, 84211, 84221,
84223, 84229, 84239, 84247, 84263, 84299, 84307, 84313, 84317, 84319,
84347, 84349, 84377, 84389, 84391, 84401, 84407, 84421, 84431, 84437,
84443, 84449, 84457, 84463, 84467, 84481, 84499, 84503, 84509, 84521,
84523, 84533, 84551, 84559, 84589, 84629, 84631, 84649, 84653, 84659,
84673, 84691, 84697, 84701, 84713, 84719, 84731, 84737, 84751, 84761,
84787, 84793, 84809, 84811, 84827, 84857, 84859, 84869, 84871, 84913,
84919, 84947, 84961, 84967, 84977, 84979, 84991, 85009, 85021, 85027,
85037, 85049, 85061, 85081, 85087, 85091, 85093, 85103, 85109, 85121,
85133, 85147, 85159, 85193, 85199, 85201, 85213, 85223, 85229, 85237,
85243, 85247, 85259, 85297, 85303, 85313, 85331, 85333, 85361, 85363,
85369, 85381, 85411, 85427, 85429, 85439, 85447, 85451, 85453, 85469,
85487, 85513, 85517, 85523, 85531, 85549, 85571, 85577, 85597, 85601,
85607, 85619, 85621, 85627, 85639, 85643, 85661, 85667, 85669, 85691,
85703, 85711, 85717, 85733, 85751, 85781, 85793, 85817, 85819, 85829,
85831, 85837, 85843, 85847, 85853, 85889, 85903, 85909, 85931, 85933,
85991, 85999, 86011, 86017, 86027, 86029, 86069, 86077, 86083, 86111,
86113, 86117, 86131, 86137, 86143, 86161, 86171, 86179, 86183, 86197,
86201, 86209, 86239, 86243, 86249, 86257, 86263, 86269, 86287, 86291,
86293, 86297, 86311, 86323, 86341, 86351, 86353, 86357, 86369, 86371,
86381, 86389, 86399, 86413, 86423, 86441, 86453, 86461, 86467, 86477,
86491, 86501, 86509, 86531, 86533, 86539, 86561, 86573, 86579, 86587,
86599, 86627, 86629, 86677, 86689, 86693, 86711, 86719, 86729, 86743,
86753, 86767, 86771, 86783, 86813, 86837, 86843, 86851, 86857, 86861,
86869, 86923, 86927, 86929, 86939, 86951, 86959, 86969, 86981, 86993,
87011, 87013, 87037, 87041, 87049, 87071, 87083, 87103, 87107, 87119,
87121, 87133, 87149, 87151, 87179, 87181, 87187, 87211, 87221, 87223,
87251, 87253, 87257, 87277, 87281, 87293, 87299, 87313, 87317, 87323,
87337, 87359, 87383, 87403, 87407, 87421, 87427, 87433, 87443, 87473,
87481, 87491, 87509, 87511, 87517, 87523, 87539, 87541, 87547, 87553,
87557, 87559, 87583, 87587, 87589, 87613, 87623, 87629, 87631, 87641,
87643, 87649, 87671, 87679, 87683, 87691, 87697, 87701, 87719, 87721,
87739, 87743, 87751, 87767, 87793, 87797, 87803, 87811, 87833, 87853,
87869, 87877, 87881, 87887, 87911, 87917, 87931, 87943, 87959, 87961,
87973, 87977, 87991, 88001, 88003, 88007, 88019, 88037, 88069, 88079,
88093, 88117, 88129, 88169, 88177, 88211, 88223, 88237, 88241, 88259,
88261, 88289, 88301, 88321, 88327, 88337, 88339, 88379, 88397, 88411,
88423, 88427, 88463, 88469, 88471, 88493, 88499, 88513, 88523, 88547,
88589, 88591, 88607, 88609, 88643, 88651, 88657, 88661, 88663, 88667,
88681, 88721, 88729, 88741, 88747, 88771, 88789, 88793, 88799, 88801,
88807, 88811, 88813, 88817, 88819, 88843, 88853, 88861, 88867, 88873,
88883, 88897, 88903, 88919, 88937, 88951, 88969, 88993, 88997, 89003,
89009, 89017, 89021, 89041, 89051, 89057, 89069, 89071, 89083, 89087,
89101, 89107, 89113, 89119, 89123, 89137, 89153, 89189, 89203, 89209,
89213, 89227, 89231, 89237, 89261, 89269, 89273, 89293, 89303, 89317,
89329, 89363, 89371, 89381, 89387, 89393, 89399, 89413, 89417, 89431,
89443, 89449, 89459, 89477, 89491, 89501, 89513, 89519, 89521, 89527,
89533, 89561, 89563, 89567, 89591, 89597, 89599, 89603, 89611, 89627,
89633, 89653, 89657, 89659, 89669, 89671, 89681, 89689, 89753, 89759,
89767, 89779, 89783, 89797, 89809, 89819, 89821, 89833, 89839, 89849,
89867, 89891, 89897, 89899, 89909, 89917, 89923, 89939, 89959, 89963,
89977, 89983, 89989, 90001, 90007, 90011, 90017, 90019, 90023, 90031,
90053, 90059, 90067, 90071, 90073, 90089, 90107, 90121, 90127, 90149,
90163, 90173, 90187, 90191, 90197, 90199, 90203, 90217, 90227, 90239,
90247, 90263, 90271, 90281, 90289, 90313, 90353, 90359, 90371, 90373,
90379, 90397, 90401, 90403, 90407, 90437, 90439, 90469, 90473, 90481,
90499, 90511, 90523, 90527, 90529, 90533, 90547, 90583, 90599, 90617,
90619, 90631, 90641, 90647, 90659, 90677, 90679, 90697, 90703, 90709,
90731, 90749, 90787, 90793, 90803, 90821, 90823, 90833, 90841, 90847,
90863, 90887, 90901, 90907, 90911, 90917, 90931, 90947, 90971, 90977,
90989, 90997, 91009, 91019, 91033, 91079, 91081, 91097, 91099, 91121,
91127, 91129, 91139, 91141, 91151, 91153, 91159, 91163, 91183, 91193,
91199, 91229, 91237, 91243, 91249, 91253, 91283, 91291, 91297, 91303,
91309, 91331, 91367, 91369, 91373, 91381, 91387, 91393, 91397, 91411,
91423, 91433, 91453, 91457, 91459, 91463, 91493, 91499, 91513, 91529,
91541, 91571, 91573, 91577, 91583, 91591, 91621, 91631, 91639, 91673,
91691, 91703, 91711, 91733, 91753, 91757, 91771, 91781, 91801, 91807,
91811, 91813, 91823, 91837, 91841, 91867, 91873, 91909, 91921, 91939,
91943, 91951, 91957, 91961, 91967, 91969, 91997, 92003, 92009, 92033,
92041, 92051, 92077, 92083, 92107, 92111, 92119, 92143, 92153, 92173,
92177, 92179, 92189, 92203, 92219, 92221, 92227, 92233, 92237, 92243,
92251, 92269, 92297, 92311, 92317, 92333, 92347, 92353, 92357, 92363,
92369, 92377, 92381, 92383, 92387, 92399, 92401, 92413, 92419, 92431,
92459, 92461, 92467, 92479, 92489, 92503, 92507, 92551, 92557, 92567,
92569, 92581, 92593, 92623, 92627, 92639, 92641, 92647, 92657, 92669,
92671, 92681, 92683, 92693, 92699, 92707, 92717, 92723, 92737, 92753,
92761, 92767, 92779, 92789, 92791, 92801, 92809, 92821, 92831, 92849,
92857, 92861, 92863, 92867, 92893, 92899, 92921, 92927, 92941, 92951,
92957, 92959, 92987, 92993, 93001, 93047, 93053, 93059, 93077, 93083,
93089, 93097, 93103, 93113, 93131, 93133, 93139, 93151, 93169, 93179,
93187, 93199, 93229, 93239, 93241, 93251, 93253, 93257, 93263, 93281,
93283, 93287, 93307, 93319, 93323, 93329, 93337, 93371, 93377, 93383,
93407, 93419, 93427, 93463, 93479, 93481, 93487, 93491, 93493, 93497,
93503, 93523, 93529, 93553, 93557, 93559, 93563, 93581, 93601, 93607,
93629, 93637, 93683, 93701, 93703, 93719, 93739, 93761, 93763, 93787,
93809, 93811, 93827, 93851, 93871, 93887, 93889, 93893, 93901, 93911,
93913, 93923, 93937, 93941, 93949, 93967, 93971, 93979, 93983, 93997,
94007, 94009, 94033, 94049, 94057, 94063, 94079, 94099, 94109, 94111,
94117, 94121, 94151, 94153, 94169, 94201, 94207, 94219, 94229, 94253,
94261, 94273, 94291, 94307, 94309, 94321, 94327, 94331, 94343, 94349,
94351, 94379, 94397, 94399, 94421, 94427, 94433, 94439, 94441, 94447,
94463, 94477, 94483, 94513, 94529, 94531, 94541, 94543, 94547, 94559,
94561, 94573, 94583, 94597, 94603, 94613, 94621, 94649, 94651, 94687,
94693, 94709, 94723, 94727, 94747, 94771, 94777, 94781, 94789, 94793,
94811, 94819, 94823, 94837, 94841, 94847, 94849, 94873, 94889, 94903,
94907, 94933, 94949, 94951, 94961, 94993, 94999, 95003, 95009, 95021,
95027, 95063, 95071, 95083, 95087, 95089, 95093, 95101, 95107, 95111,
95131, 95143, 95153, 95177, 95189, 95191, 95203, 95213, 95219, 95231,
95233, 95239, 95257, 95261, 95267, 95273, 95279, 95287, 95311, 95317,
95327, 95339, 95369, 95383, 95393, 95401, 95413, 95419, 95429, 95441,
95443, 95461, 95467, 95471, 95479, 95483, 95507, 95527, 95531, 95539,
95549, 95561, 95569, 95581, 95597, 95603, 95617, 95621, 95629, 95633,
95651, 95701, 95707, 95713, 95717, 95723, 95731, 95737, 95747, 95773,
95783, 95789, 95791, 95801, 95803, 95813, 95819, 95857, 95869, 95873,
95881, 95891, 95911, 95917, 95923, 95929, 95947, 95957, 95959, 95971,
95987, 95989, 96001, 96013, 96017, 96043, 96053, 96059, 96079, 96097,
96137, 96149, 96157, 96167, 96179, 96181, 96199, 96211, 96221, 96223,
96233, 96259, 96263, 96269, 96281, 96289, 96293, 96323, 96329, 96331,
96337, 96353, 96377, 96401, 96419, 96431, 96443, 96451, 96457, 96461,
96469, 96479, 96487, 96493, 96497, 96517, 96527, 96553, 96557, 96581,
96587, 96589, 96601, 96643, 96661, 96667, 96671, 96697, 96703, 96731,
96737, 96739, 96749, 96757, 96763, 96769, 96779, 96787, 96797, 96799,
96821, 96823, 96827, 96847, 96851, 96857, 96893, 96907, 96911, 96931,
96953, 96959, 96973, 96979, 96989, 96997, 97001, 97003, 97007, 97021,
97039, 97073, 97081, 97103, 97117, 97127, 97151, 97157, 97159, 97169,
97171, 97177, 97187, 97213, 97231, 97241, 97259, 97283, 97301, 97303,
97327, 97367, 97369, 97373, 97379, 97381, 97387, 97397, 97423, 97429,
97441, 97453, 97459, 97463, 97499, 97501, 97511, 97523, 97547, 97549,
97553, 97561, 97571, 97577, 97579, 97583, 97607, 97609, 97613, 97649,
97651, 97673, 97687, 97711, 97729, 97771, 97777, 97787, 97789, 97813,
97829, 97841, 97843, 97847, 97849, 97859, 97861, 97871, 97879, 97883,
97919, 97927, 97931, 97943, 97961, 97967, 97973, 97987, 98009, 98011,
98017, 98041, 98047, 98057, 98081, 98101, 98123, 98129, 98143, 98179,
98207, 98213, 98221, 98227, 98251, 98257, 98269, 98297, 98299, 98317,
98321, 98323, 98327, 98347, 98369, 98377, 98387, 98389, 98407, 98411,
98419, 98429, 98443, 98453, 98459, 98467, 98473, 98479, 98491, 98507,
98519, 98533, 98543, 98561, 98563, 98573, 98597, 98621, 98627, 98639,
98641, 98663, 98669, 98689, 98711, 98713, 98717, 98729, 98731, 98737,
98773, 98779, 98801, 98807, 98809, 98837, 98849, 98867, 98869, 98873,
98887, 98893, 98897, 98899, 98909, 98911, 98927, 98929, 98939, 98947,
98953, 98963, 98981, 98993, 98999, 99013, 99017, 99023, 99041, 99053,
99079, 99083, 99089, 99103, 99109, 99119, 99131, 99133, 99137, 99139,
99149, 99173, 99181, 99191, 99223, 99233, 99241, 99251, 99257, 99259,
99277, 99289, 99317, 99347, 99349, 99367, 99371, 99377, 99391, 99397,
99401, 99409, 99431, 99439, 99469, 99487, 99497, 99523, 99527, 99529,
99551, 99559, 99563, 99571, 99577, 99581, 99607, 99611, 99623, 99643,
99661, 99667, 99679, 99689, 99707, 99709, 99713, 99719, 99721, 99733,
99761, 99767, 99787, 99793, 99809, 99817, 99823, 99829, 99833, 99839,
99859, 99871, 99877, 99881, 99901, 99907, 99923, 99929, 99961, 99971,
99989, 99991, 100003, 100019, 100043, 100049, 100057, 100069, 100103, 100109,
100129, 100151, 100153, 100169, 100183, 100189, 100193, 100207, 100213, 100237,
100267, 100271, 100279, 100291, 100297, 100313, 100333, 100343, 100357, 100361,
100363, 100379, 100391, 100393, 100403, 100411, 100417, 100447, 100459, 100469,
100483, 100493, 100501, 100511, 100517, 100519, 100523, 100537, 100547, 100549,
100559, 100591, 100609, 100613, 100621, 100649, 100669, 100673, 100693, 100699,
100703, 100733, 100741, 100747, 100769, 100787, 100799, 100801, 100811, 100823,
100829, 100847, 100853, 100907, 100913, 100927, 100931, 100937, 100943, 100957,
100981, 100987, 100999, 101009, 101021, 101027, 101051, 101063, 101081, 101089,
101107, 101111, 101113, 101117, 101119, 101141, 101149, 101159, 101161, 101173,
101183, 101197, 101203, 101207, 101209, 101221, 101267, 101273, 101279, 101281,
101287, 101293, 101323, 101333, 101341, 101347, 101359, 101363, 101377, 101383,
101399, 101411, 101419, 101429, 101449, 101467, 101477, 101483, 101489, 101501,
101503, 101513, 101527, 101531, 101533, 101537, 101561, 101573, 101581, 101599,
101603, 101611, 101627, 101641, 101653, 101663, 101681, 101693, 101701, 101719,
101723, 101737, 101741, 101747, 101749, 101771, 101789, 101797, 101807, 101833,
101837, 101839, 101863, 101869, 101873, 101879, 101891, 101917, 101921, 101929,
101939, 101957, 101963, 101977, 101987, 101999, 102001, 102013, 102019, 102023,
102031, 102043, 102059, 102061, 102071, 102077, 102079, 102101, 102103, 102107,
102121, 102139, 102149, 102161, 102181, 102191, 102197, 102199, 102203, 102217,
102229, 102233, 102241, 102251, 102253, 102259, 102293, 102299, 102301, 102317,
102329, 102337, 102359, 102367, 102397, 102407, 102409, 102433, 102437, 102451,
102461, 102481, 102497, 102499, 102503, 102523, 102533, 102539, 102547, 102551,
102559, 102563, 102587, 102593, 102607, 102611, 102643, 102647, 102653, 102667,
102673, 102677, 102679, 102701, 102761, 102763, 102769, 102793, 102797, 102811,
102829, 102841, 102859, 102871, 102877, 102881, 102911, 102913, 102929, 102931,
102953, 102967, 102983, 103001, 103007, 103043, 103049, 103067, 103069, 103079,
103087, 103091, 103093, 103099, 103123, 103141, 103171, 103177, 103183, 103217,
103231, 103237, 103289, 103291, 103307, 103319, 103333, 103349, 103357, 103387,
103391, 103393, 103399, 103409, 103421, 103423, 103451, 103457, 103471, 103483,
103511, 103529, 103549, 103553, 103561, 103567, 103573, 103577, 103583, 103591,
103613, 103619, 103643, 103651, 103657, 103669, 103681, 103687, 103699, 103703,
103723, 103769, 103787, 103801, 103811, 103813, 103837, 103841, 103843, 103867,
103889, 103903, 103913, 103919, 103951, 103963, 103967, 103969, 103979, 103981,
103991, 103993, 103997, 104003, 104009, 104021, 104033, 104047, 104053, 104059,
104087, 104089, 104107, 104113, 104119, 104123, 104147, 104149, 104161, 104173,
104179, 104183, 104207, 104231, 104233, 104239, 104243, 104281, 104287, 104297,
104309, 104311, 104323, 104327, 104347, 104369, 104381, 104383, 104393, 104399,
104417, 104459, 104471, 104473, 104479, 104491, 104513, 104527, 104537, 104543,
104549, 104551, 104561, 104579, 104593, 104597, 104623, 104639, 104651, 104659,
104677, 104681, 104683, 104693, 104701, 104707, 104711, 104717, 104723, 104729,
)
| apache-2.0 |
keflavich/scikit-image | skimage/transform/tests/test_geometric.py | 24 | 9151 | import numpy as np
from numpy.testing import (assert_equal, assert_almost_equal,
assert_raises)
from skimage.transform._geometric import _stackcopy
from skimage.transform._geometric import GeometricTransform
from skimage.transform import (estimate_transform, matrix_transform,
SimilarityTransform, AffineTransform,
ProjectiveTransform, PolynomialTransform,
PiecewiseAffineTransform)
from skimage._shared._warnings import expected_warnings
SRC = np.array([
[-12.3705, -10.5075],
[-10.7865, 15.4305],
[8.6985, 10.8675],
[11.4975, -9.5715],
[7.8435, 7.4835],
[-5.3325, 6.5025],
[6.7905, -6.3765],
[-6.1695, -0.8235],
])
DST = np.array([
[0, 0],
[0, 5800],
[4900, 5800],
[4900, 0],
[4479, 4580],
[1176, 3660],
[3754, 790],
[1024, 1931],
])
def test_stackcopy():
layers = 4
x = np.empty((3, 3, layers))
y = np.eye(3, 3)
_stackcopy(x, y)
for i in range(layers):
assert_almost_equal(x[..., i], y)
def test_estimate_transform():
for tform in ('similarity', 'affine', 'projective', 'polynomial'):
estimate_transform(tform, SRC[:2, :], DST[:2, :])
assert_raises(ValueError, estimate_transform, 'foobar',
SRC[:2, :], DST[:2, :])
def test_matrix_transform():
tform = AffineTransform(scale=(0.1, 0.5), rotation=2)
assert_equal(tform(SRC), matrix_transform(SRC, tform.params))
def test_similarity_estimation():
# exact solution
tform = estimate_transform('similarity', SRC[:2, :], DST[:2, :])
assert_almost_equal(tform(SRC[:2, :]), DST[:2, :])
assert_equal(tform.params[0, 0], tform.params[1, 1])
assert_equal(tform.params[0, 1], - tform.params[1, 0])
# over-determined
tform2 = estimate_transform('similarity', SRC, DST)
assert_almost_equal(tform2.inverse(tform2(SRC)), SRC)
assert_equal(tform2.params[0, 0], tform2.params[1, 1])
assert_equal(tform2.params[0, 1], - tform2.params[1, 0])
# via estimate method
tform3 = SimilarityTransform()
tform3.estimate(SRC, DST)
assert_almost_equal(tform3.params, tform2.params)
def test_similarity_init():
# init with implicit parameters
scale = 0.1
rotation = 1
translation = (1, 1)
tform = SimilarityTransform(scale=scale, rotation=rotation,
translation=translation)
assert_almost_equal(tform.scale, scale)
assert_almost_equal(tform.rotation, rotation)
assert_almost_equal(tform.translation, translation)
# init with transformation matrix
tform2 = SimilarityTransform(tform.params)
assert_almost_equal(tform2.scale, scale)
assert_almost_equal(tform2.rotation, rotation)
assert_almost_equal(tform2.translation, translation)
# test special case for scale if rotation=0
scale = 0.1
rotation = 0
translation = (1, 1)
tform = SimilarityTransform(scale=scale, rotation=rotation,
translation=translation)
assert_almost_equal(tform.scale, scale)
assert_almost_equal(tform.rotation, rotation)
assert_almost_equal(tform.translation, translation)
# test special case for scale if rotation=90deg
scale = 0.1
rotation = np.pi / 2
translation = (1, 1)
tform = SimilarityTransform(scale=scale, rotation=rotation,
translation=translation)
assert_almost_equal(tform.scale, scale)
assert_almost_equal(tform.rotation, rotation)
assert_almost_equal(tform.translation, translation)
def test_affine_estimation():
# exact solution
tform = estimate_transform('affine', SRC[:3, :], DST[:3, :])
assert_almost_equal(tform(SRC[:3, :]), DST[:3, :])
# over-determined
tform2 = estimate_transform('affine', SRC, DST)
assert_almost_equal(tform2.inverse(tform2(SRC)), SRC)
# via estimate method
tform3 = AffineTransform()
tform3.estimate(SRC, DST)
assert_almost_equal(tform3.params, tform2.params)
def test_affine_init():
# init with implicit parameters
scale = (0.1, 0.13)
rotation = 1
shear = 0.1
translation = (1, 1)
tform = AffineTransform(scale=scale, rotation=rotation, shear=shear,
translation=translation)
assert_almost_equal(tform.scale, scale)
assert_almost_equal(tform.rotation, rotation)
assert_almost_equal(tform.shear, shear)
assert_almost_equal(tform.translation, translation)
# init with transformation matrix
tform2 = AffineTransform(tform.params)
assert_almost_equal(tform2.scale, scale)
assert_almost_equal(tform2.rotation, rotation)
assert_almost_equal(tform2.shear, shear)
assert_almost_equal(tform2.translation, translation)
def test_piecewise_affine():
tform = PiecewiseAffineTransform()
tform.estimate(SRC, DST)
# make sure each single affine transform is exactly estimated
assert_almost_equal(tform(SRC), DST)
assert_almost_equal(tform.inverse(DST), SRC)
def test_projective_estimation():
# exact solution
tform = estimate_transform('projective', SRC[:4, :], DST[:4, :])
assert_almost_equal(tform(SRC[:4, :]), DST[:4, :])
# over-determined
tform2 = estimate_transform('projective', SRC, DST)
assert_almost_equal(tform2.inverse(tform2(SRC)), SRC)
# via estimate method
tform3 = ProjectiveTransform()
tform3.estimate(SRC, DST)
assert_almost_equal(tform3.params, tform2.params)
def test_projective_init():
tform = estimate_transform('projective', SRC, DST)
# init with transformation matrix
tform2 = ProjectiveTransform(tform.params)
assert_almost_equal(tform2.params, tform.params)
def test_polynomial_estimation():
# over-determined
tform = estimate_transform('polynomial', SRC, DST, order=10)
assert_almost_equal(tform(SRC), DST, 6)
# via estimate method
tform2 = PolynomialTransform()
tform2.estimate(SRC, DST, order=10)
assert_almost_equal(tform2.params, tform.params)
def test_polynomial_init():
tform = estimate_transform('polynomial', SRC, DST, order=10)
# init with transformation parameters
tform2 = PolynomialTransform(tform.params)
assert_almost_equal(tform2.params, tform.params)
def test_polynomial_default_order():
tform = estimate_transform('polynomial', SRC, DST)
tform2 = estimate_transform('polynomial', SRC, DST, order=2)
assert_almost_equal(tform2.params, tform.params)
def test_polynomial_inverse():
assert_raises(Exception, PolynomialTransform().inverse, 0)
def test_union():
tform1 = SimilarityTransform(scale=0.1, rotation=0.3)
tform2 = SimilarityTransform(scale=0.1, rotation=0.9)
tform3 = SimilarityTransform(scale=0.1 ** 2, rotation=0.3 + 0.9)
tform = tform1 + tform2
assert_almost_equal(tform.params, tform3.params)
tform1 = AffineTransform(scale=(0.1, 0.1), rotation=0.3)
tform2 = SimilarityTransform(scale=0.1, rotation=0.9)
tform3 = SimilarityTransform(scale=0.1 ** 2, rotation=0.3 + 0.9)
tform = tform1 + tform2
assert_almost_equal(tform.params, tform3.params)
assert tform.__class__ == ProjectiveTransform
tform = AffineTransform(scale=(0.1, 0.1), rotation=0.3)
assert_almost_equal((tform + tform.inverse).params, np.eye(3))
def test_union_differing_types():
tform1 = SimilarityTransform()
tform2 = PolynomialTransform()
assert_raises(TypeError, tform1.__add__, tform2)
def test_geometric_tform():
tform = GeometricTransform()
assert_raises(NotImplementedError, tform, 0)
assert_raises(NotImplementedError, tform.inverse, 0)
assert_raises(NotImplementedError, tform.__add__, 0)
def test_invalid_input():
assert_raises(ValueError, ProjectiveTransform, np.zeros((2, 3)))
assert_raises(ValueError, AffineTransform, np.zeros((2, 3)))
assert_raises(ValueError, SimilarityTransform, np.zeros((2, 3)))
assert_raises(ValueError, AffineTransform,
matrix=np.zeros((2, 3)), scale=1)
assert_raises(ValueError, SimilarityTransform,
matrix=np.zeros((2, 3)), scale=1)
assert_raises(ValueError, PolynomialTransform, np.zeros((3, 3)))
def test_deprecated_params_attributes():
for t in ('projective', 'affine', 'similarity'):
tform = estimate_transform(t, SRC, DST)
with expected_warnings(['`_matrix`.*deprecated']):
assert_equal(tform._matrix, tform.params)
tform = estimate_transform('polynomial', SRC, DST, order=3)
with expected_warnings(['`_params`.*deprecated']):
assert_equal(tform._params, tform.params)
def test_degenerate():
src = dst = np.zeros((10, 2))
tform = SimilarityTransform()
tform.estimate(src, dst)
assert np.all(np.isnan(tform.params))
tform = AffineTransform()
tform.estimate(src, dst)
assert np.all(np.isnan(tform.params))
tform = ProjectiveTransform()
tform.estimate(src, dst)
assert np.all(np.isnan(tform.params))
if __name__ == "__main__":
from numpy.testing import run_module_suite
run_module_suite()
| bsd-3-clause |
yaolinz/rethinkdb | packaging/osx/ds_store/store.py | 50 | 44334 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import binascii
import struct
import biplist
try:
next
except NameError:
next = lambda x: x.next()
try:
unicode
except NameError:
unicode = str
from . import buddy
class ILocCodec(object):
@staticmethod
def encode(point):
return struct.pack(b'>IIII', point[0], point[1],
0xffffffff, 0xffff0000)
@staticmethod
def decode(bytesData):
if isinstance(bytesData, bytearray):
x, y = struct.unpack_from(b'>II', bytes(bytesData[:8]))
else:
x, y = struct.unpack(b'>II', bytesData[:8])
return (x, y)
class PlistCodec(object):
@staticmethod
def encode(plist):
return biplist.writePlistToString(plist)
@staticmethod
def decode(bytes):
return biplist.readPlistFromString(bytes)
# This list tells the code how to decode particular kinds of entry in the
# .DS_Store file. This is really a convenience, and we currently only
# support a tiny subset of the possible entry types.
codecs = {
'Iloc': ILocCodec,
'bwsp': PlistCodec,
'lsvp': PlistCodec,
'lsvP': PlistCodec,
'icvp': PlistCodec,
}
class DSStoreEntry(object):
"""Holds the data from an entry in a ``.DS_Store`` file. Note that this is
not meant to represent the entry itself---i.e. if you change the type
or value, your changes will *not* be reflected in the underlying file.
If you want to make a change, you should either use the :class:`DSStore`
object's :meth:`DSStore.insert` method (which will replace a key if it
already exists), or the mapping access mode for :class:`DSStore` (often
simpler anyway).
"""
def __init__(self, filename, code, typecode, value=None):
if str != bytes and type(filename) == bytes:
filename = filename.decode('utf-8')
self.filename = filename
self.code = code
self.type = typecode
self.value = value
@classmethod
def read(cls, block):
"""Read a ``.DS_Store`` entry from the containing Block"""
# First read the filename
nlen = block.read(b'>I')[0]
filename = block.read(2 * nlen).decode('utf-16be')
# Next, read the code and type
code, typecode = block.read(b'>4s4s')
# Finally, read the data
if typecode == b'bool':
value = block.read(b'>?')[0]
elif typecode == b'long' or typecode == b'shor':
value = block.read(b'>I')[0]
elif typecode == b'blob':
vlen = block.read(b'>I')[0]
value = block.read(vlen)
codec = codecs.get(code, None)
if codec:
value = codec.decode(value)
typecode = codec
elif typecode == b'ustr':
vlen = block.read(b'>I')[0]
value = block.read(2 * vlen).decode('utf-16be')
elif typecode == b'type':
value = block.read(b'>4s')[0]
elif typecode == b'comp' or typecode == b'dutc':
value = block.read(b'>Q')[0]
else:
raise ValueError('Unknown type code "%s"' % typecode)
return DSStoreEntry(filename, code, typecode, value)
def __lt__(self, other):
if not isinstance(other, DSStoreEntry):
raise TypeError('Can only compare against other DSStoreEntry objects')
sfl = self.filename.lower()
ofl = other.filename.lower()
return (sfl < ofl
or (self.filename == other.filename
and self.code < other.code))
def __le__(self, other):
if not isinstance(other, DSStoreEntry):
raise TypeError('Can only compare against other DSStoreEntry objects')
sfl = self.filename.lower()
ofl = other.filename.lower()
return (sfl < ofl
or (sfl == ofl
and self.code <= other.code))
def __eq__(self, other):
if not isinstance(other, DSStoreEntry):
raise TypeError('Can only compare against other DSStoreEntry objects')
sfl = self.filename.lower()
ofl = other.filename.lower()
return (sfl == ofl
and self.code == other.code)
def __ne__(self, other):
if not isinstance(other, DSStoreEntry):
raise TypeError('Can only compare against other DSStoreEntry objects')
sfl = self.filename.lower()
ofl = other.filename.lower()
return (sfl != ofl
or self.code != other.code)
def __gt__(self, other):
if not isinstance(other, DSStoreEntry):
raise TypeError('Can only compare against other DSStoreEntry objects')
sfl = self.filename.lower()
ofl = other.filename.lower()
selfCode = self.code
if str != bytes and type(selfCode) is bytes:
selfCode = selfCode.decode('utf-8')
otherCode = other.code
if str != bytes and type(otherCode) is bytes:
otherCode = otherCode.decode('utf-8')
return (sfl > ofl or (sfl == ofl and selfCode > otherCode))
def __ge__(self, other):
if not isinstance(other, DSStoreEntry):
raise TypeError('Can only compare against other DSStoreEntry objects')
sfl = self.filename.lower()
ofl = other.filename.lower()
return (sfl > ofl
or (sfl == ofl
and self.code >= other.code))
def __cmp__(self, other):
if not isinstance(other, DSStoreEntry):
raise TypeError('Can only compare against other DSStoreEntry objects')
r = cmp(self.filename.lower(), other.filename.lower())
if r:
return r
return cmp(self.code, other.code)
def byte_length(self):
"""Compute the length of this entry, in bytes"""
utf16 = self.filename.encode('utf-16be')
l = 4 + len(utf16) + 8
if isinstance(self.type, (str, unicode)):
entry_type = self.type
value = self.value
else:
entry_type = 'blob'
value = self.type.encode(self.value)
if entry_type == 'bool':
l += 1
elif entry_type == 'long' or entry_type == 'shor':
l += 4
elif entry_type == 'blob':
l += 4 + len(value)
elif entry_type == 'ustr':
utf16 = value.encode('utf-16be')
l += 4 + len(utf16)
elif entry_type == 'type':
l += 4
elif entry_type == 'comp' or entry_type == 'dutc':
l += 8
else:
raise ValueError('Unknown type code "%s"' % entry_type)
return l
def write(self, block, insert=False):
"""Write this entry to the specified Block"""
if insert:
w = block.insert
else:
w = block.write
if isinstance(self.type, (str, unicode)):
entry_type = self.type
value = self.value
else:
entry_type = 'blob'
value = self.type.encode(self.value)
utf16 = self.filename.encode('utf-16be')
w(b'>I', len(utf16) // 2)
w(utf16)
w(b'>4s4s', self.code.encode('utf-8'), entry_type.encode('utf-8'))
if entry_type == 'bool':
w(b'>?', value)
elif entry_type == 'long' or entry_type == 'shor':
w(b'>I', value)
elif entry_type == 'blob':
w(b'>I', len(value))
w(value)
elif entry_type == 'ustr':
utf16 = value.encode('utf-16be')
w(b'>I', len(utf16) // 2)
w(utf16)
elif entry_type == 'type':
w(b'>4s', value.encode('utf-8'))
elif entry_type == 'comp' or entry_type == 'dutc':
w(b'>Q', value)
else:
raise ValueError('Unknown type code "%s"' % entry_type)
def __repr__(self):
return '<%s %s>' % (self.filename, self.code)
class DSStore(object):
"""Python interface to a ``.DS_Store`` file. Works by manipulating the file
on the disk---so this code will work with ``.DS_Store`` files for *very*
large directories.
A :class:`DSStore` object can be used as if it was a mapping, e.g.::
d['foobar.dat']['Iloc']
will fetch the "Iloc" record for "foobar.dat", or raise :class:`KeyError` if
there is no such record. If used in this manner, the :class:`DSStore` object
will return (type, value) tuples, unless the type is "blob" and the module
knows how to decode it.
Currently, we know how to decode "Iloc", "bwsp", "lsvp", "lsvP" and "icvp"
blobs. "Iloc" decodes to an (x, y) tuple, while the others are all decoded
using ``biplist``.
Assignment also works, e.g.::
d['foobar.dat']['note'] = ('ustr', u'Hello World!')
as does deletion with ``del``::
del d['foobar.dat']['note']
This is usually going to be the most convenient interface, though
occasionally (for instance when creating a new ``.DS_Store`` file) you
may wish to drop down to using :class:`DSStoreEntry` objects directly."""
def __init__(self, store):
self._store = store
self._superblk = self._store['DSDB']
with self._get_block(self._superblk) as s:
self._rootnode, self._levels, self._records, \
self._nodes, self._page_size = s.read(b'>IIIII')
self._min_usage = 2 * self._page_size // 3
self._dirty = False
@classmethod
def open(cls, file_or_name, mode='r+', initial_entries=None):
"""Open a ``.DS_Store`` file; pass either a Python file object, or a
filename in the ``file_or_name`` argument and a file access mode in
the ``mode`` argument. If you are creating a new file using the "w"
or "w+" modes, you may also specify a list of entries with which
to initialise the file."""
store = buddy.Allocator.open(file_or_name, mode)
if mode == 'w' or mode == 'w+':
superblk = store.allocate(20)
store['DSDB'] = superblk
page_size = 4096
if not initial_entries:
root = store.allocate(page_size)
with store.get_block(root) as rootblk:
rootblk.zero_fill()
with store.get_block(superblk) as s:
s.write(b'>IIIII', root, 0, 0, 1, page_size)
else:
# Make sure they're in sorted order
initial_entries = list(initial_entries)
initial_entries.sort()
# Construct the tree
current_level = initial_entries
next_level = []
levels = []
ptr_size = 0
node_count = 0
while True:
total = 8
nodes = []
node = []
for e in current_level:
new_total = total + ptr_size + e.byte_length()
if new_total > page_size:
nodes.append(node)
next_level.append(e)
total = 8
node = []
else:
total = new_total
node.append(e)
if node:
nodes.append(node)
node_count += len(nodes)
levels.append(nodes)
if len(nodes) == 1:
break
current_level = next_level
next_level = []
ptr_size = 4
# Allocate nodes
ptrs = [store.allocate(page_size) for n in range(node_count)]
# Generate nodes
pointers = []
prev_pointers = None
for level in levels:
ppndx = 0
lptrs = ptrs[-len(level):]
del ptrs[-len(level):]
for node in level:
ndx = lptrs.pop(0)
if prev_pointers is None:
with store.get_block(ndx) as block:
block.write(b'>II', 0, len(node))
for e in node:
e.write(block)
else:
next_node = prev_pointers[ppndx + len(node)]
node_ptrs = prev_pointers[ppndx:ppndx+len(node)]
with store.get_block(ndx) as block:
block.write(b'>II', next_node, len(node))
for ptr, e in zip(node_ptrs, node):
block.write(b'>I', ptr)
e.write(block)
pointers.append(ndx)
prev_pointers = pointers
pointers = []
root = prev_pointers[0]
with store.get_block(superblk) as s:
s.write(b'>IIIII', root, len(levels), len(initial_entries),
node_count, page_size)
return DSStore(store)
def _get_block(self, number):
return self._store.get_block(number)
def flush(self):
"""Flush any dirty data back to the file."""
if self._dirty:
self._dirty = False
with self._get_block(self._superblk) as s:
s.write(b'>IIIII', self._rootnode, self._levels, self._records,
self._nodes, self._page_size)
self._store.flush()
def close(self):
"""Flush dirty data and close the underlying file."""
self.flush()
self._store.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
# Internal B-Tree nodes look like this:
#
# [ next | count | (ptr0 | rec0) | (ptr1 | rec1) ... (ptrN | recN) ]
# Leaf nodes look like this:
#
# [ 0 | count | rec0 | rec1 ... recN ]
# Iterate over the tree, starting at `node'
def _traverse(self, node):
if node is None:
node = self._rootnode
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
if next_node:
for n in range(count):
ptr = block.read(b'>I')[0]
for e in self._traverse(ptr):
yield e
e = DSStoreEntry.read(block)
yield e
for e in self._traverse(next_node):
yield e
else:
for n in range(count):
e = DSStoreEntry.read(block)
yield e
# Display the data in `node'
def _dump_node(self, node):
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
print('next: %u\ncount: %u\n' % (next_node, count))
for n in range(count):
if next_node:
ptr = block.read(b'>I')[0]
print('%8u ' % ptr, end=' ')
else:
print(' ', end=' ')
e = DSStoreEntry.read(block)
print(e, ' (%u)' % e.byte_length())
print('used: %u' % block.tell())
# Display the data in the super block
def _dump_super(self):
print('root: %u\nlevels: %u\nrecords: %u\nnodes: %u\npage-size: %u' \
% (self._rootnode, self._levels, self._records,
self._nodes, self._page_size))
# Splits entries across two blocks, returning one pivot
#
# Tries to balance the block usage across the two as best it can
def _split2(self, blocks, entries, pointers, before, internal):
left_block = blocks[0]
right_block = blocks[1]
count = len(entries)
# Find the feasible splits
best_split = None
best_diff = None
total = before[count]
if 8 + total <= self._page_size:
# We can use a *single* node for this
best_split = count
else:
# Split into two nodes
for n in range(1, count - 1):
left_size = 8 + before[n]
right_size = 8 + total - before[n + 1]
if left_size > self._page_size:
break
if right_size > self._page_size:
continue
diff = abs(left_size - right_size)
if best_split is None or diff < best_diff:
best_split = n
best_diff = diff
if best_split is None:
return None
# Write the nodes
left_block.seek(0)
if internal:
next_node = pointers[best_split]
else:
next_node = 0
left_block.write(b'>II', next_node, best_split)
for n in range(best_split):
if internal:
left_block.write(b'>I', pointers[n])
entries[n].write(left_block)
left_block.zero_fill()
if best_split == count:
return []
right_block.seek(0)
if internal:
next_node = pointers[count]
else:
next_node = 0
right_block.write(b'>II', next_node, count - best_split - 1)
for n in range(best_split + 1, count):
if internal:
right_block.write(b'>I', pointers[n])
entries[n].write(right_block)
right_block.zero_fill()
pivot = entries[best_split]
return [pivot]
def _split(self, node, entry, right_ptr=0):
self._nodes += 1
self._dirty = True
new_right = self._store.allocate(self._page_size)
with self._get_block(node) as block, \
self._get_block(new_right) as right_block:
# First, measure and extract all the elements
entry_size = entry.byte_length()
entry_pos = None
next_node, count = block.read(b'>II')
if next_node:
entry_size += 4
pointers = []
entries = []
before = []
total = 0
for n in range(count):
pos = block.tell()
if next_node:
ptr = block.read(b'>I')[0]
pointers.append(ptr)
e = DSStoreEntry.read(block)
if e > entry:
entry_pos = n
entries.append(entry)
pointers.append(right_ptr)
before.append(total)
total += entry_Size
entries.append(e)
before.append(total)
total += block.tell() - pos
before.append(total)
if next_node:
pointers.append(next_node)
pivot = self._split2([left_block, right_block],
entries, pointers, before,
bool(next_node))[0]
self._records += 1
self._nodes += 1
self._dirty = True
return (pivot, new_right)
# Allocate a new root node containing the element `pivot' and the pointers
# `left' and `right'
def _new_root(self, left, pivot, right):
new_root = self._store.allocate(self._page_size)
with self._get_block(new_root) as block:
block.write(b'>III', right, 1, left)
pivot.write(block)
self._rootnode = new_root
self._levels += 1
self._nodes += 1
self._dirty = True
# Insert an entry into an inner node; `path' is the path from the root
# to `node', not including `node' itself. `right_ptr' is the new node
# pointer (inserted to the RIGHT of `entry')
def _insert_inner(self, path, node, entry, right_ptr):
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
insert_pos = None
insert_ndx = None
n = 0
while n < count:
pos = block.tell()
ptr = block.read(b'>I')[0]
e = DSStoreEntry.read(block)
if e == entry:
if n == count - 1:
right_ptr = next_node
next_node = ptr
block_seek(pos)
else:
right_ptr = block.read(b'>I')[0]
block.seek(pos + 4)
insert_pos = pos
insert_ndx = n
block.delete(e.byte_length() + 4)
count -= 1
self._records += 1
self._dirty = True
continue
elif insert_pos is None and e > entry:
insert_pos = pos
insert_ndx = n
n += 1
if insert_pos is None:
insert_pos = block.tell()
insert_ndx = count
remaining = self._page_size - block.tell()
if remaining < entry.byte_length() + 4:
pivot, new_right = self._split(node, entry, right_ptr)
if path:
self._insert_inner(path[:-1], path[-1], pivot, new_right)
else:
self._new_root(node, pivot, new_right)
else:
if insert_ndx == count:
block.seek(insert_pos)
block.write(b'>I', next_node)
entry.write(block)
next_node = right_ptr
else:
block.seek(insert_pos + 4)
entry.write(block, True)
block.insert('>I', right_ptr)
block.seek(0)
count += 1
block.write(b'>II', next_node, count)
self._records += 1
self._dirty = True
# Insert `entry' into the leaf node `node'
def _insert_leaf(self, path, node, entry):
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
insert_pos = None
insert_ndx = None
n = 0
while n < count:
pos = block.tell()
e = DSStoreEntry.read(block)
if e == entry:
insert_pos = pos
insert_ndx = n
block.seek(pos)
block.delete(e.byte_length())
count -= 1
self._records += 1
self._dirty = True
continue
elif insert_pos is None and e > entry:
insert_pos = pos
insert_ndx = n
n += 1
if insert_pos is None:
insert_pos = block.tell()
insert_ndx = count
remaining = self._page_size - block.tell()
if remaining < entry.byte_length():
pivot, new_right = self._split(node, entry)
if path:
self._insert_inner(path[:-1], path[-1], pivot, new_right)
else:
self._new_root(node, pivot, new_right)
else:
block.seek(insert_pos)
entry.write(block, True)
block.seek(0)
count += 1
block.write(b'>II', next_node, count)
self._records += 1
self._dirty = True
def insert(self, entry):
"""Insert ``entry`` (which should be a :class:`DSStoreEntry`)
into the B-Tree."""
path = []
node = self._rootnode
while True:
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
if next_node:
for n in range(count):
ptr = block.read(b'>I')[0]
e = DSStoreEntry.read(block)
if entry < e:
next_node = ptr
break
elif entry == e:
# If we find an existing entry the same, replace it
self._insert_inner(path, node, entry, None)
return
path.append(node)
node = next_node
else:
self._insert_leaf(path, node, entry)
return
# Return usage information for the specified `node'
def _block_usage(self, node):
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
for n in range(count):
if next_node:
ptr = block.read(b'>I')[0]
e = DSStoreEntry.read(block)
used = block.tell()
return (count, used)
# Splits entries across three blocks, returning two pivots
def _split3(self, blocks, entries, pointers, before, internal):
count = len(entries)
# Find the feasible splits
best_split = None
best_diff = None
total = before[count]
for n in range(1, count - 3):
left_size = 8 + before[n]
remaining = 16 + total - before[n + 1]
if left_size > self._page_size:
break
if remaining > 2 * self._page_size:
continue
for m in range(n + 2, count - 1):
mid_size = 8 + before[m] - before[n + 1]
right_size = 8 + total - before[m + 1]
if mid_size > self._page_size:
break
if right_size > self._page_size:
continue
diff = abs(left_size - mid_size) * abs(right_size - mid_size)
if best_split is None or diff < best_diff:
best_split = (n, m, count)
best_diff = diff
if best_split is None:
return None
# Write the nodes
prev_split = -1
for block, split in zip(blocks, best_split):
block.seek(0)
if internal:
next_node = pointers[split]
else:
next_node = 0
block.write(b'>II', next_node, split)
for n in range(prev_split + 1, split):
if internal:
block.write(b'>I', pointers[n])
entries[n].write(block)
block.zero_fill()
prev_split = split
return (entries[best_split[0]], entries[best_split[1]])
# Extract all of the entries from the specified list of `blocks',
# separating them by the specified `pivots'. Also computes the
# amount of space used before each entry.
def _extract(self, blocks, pivots):
pointers = []
entries = []
before = []
total = 0
ppivots = pivots + [None]
for b,p in zip(blocks, ppivots):
b.seek(0)
next_node, count = b.read(b'>II')
for n in range(count):
pos = b.tell()
if next_node:
ptr = b.read(b'>I')[0]
pointers.append(ptr)
e = DSStoreEntry.read(b)
entries.append(e)
before.append(total)
total += b.tell() - pos
if next_node:
pointers.append(next_node)
if p:
entries.append(p)
before.append(total)
total += p.byte_length()
if next_node:
total += 4
before.append(total)
return (entries, pointers, before)
# Rebalance the specified `node', whose path from the root is `path'.
def _rebalance(self, path, node):
# Can't rebalance the root
if not path:
return
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
with self._get_block(path[-1]) as parent:
# Find the left and right siblings and respective pivots
parent_next, parent_count = parent.read(b'>II')
left_pos = None
left_node = None
left_pivot = None
node_pos = None
right_pos = None
right_node = None
right_pivot = None
prev_e = prev_ptr = prev_pos = None
for n in range(parent_count):
pos = parent.tell()
ptr = parent.read(b'>I')[0]
e = DSStoreEntry.read(parent)
if ptr == node:
node_pos = pos
right_pivot = e
left_pos = prev_pos
left_pivot = prev_e
left_node = prev_ptr
elif prev_ptr == node:
right_node = ptr
right_pos = pos
break
prev_e = e
prev_ptr = ptr
prev_pos = pos
if parent_next == node:
node_pos = parent.tell()
left_pos = prev_pos
left_pivot = prev_e
left_node = prev_ptr
elif right_node is None:
right_node = parent_next
right_pos = parent.tell()
parent_used = parent.tell()
if left_node and right_node:
with self._get_block(left_node) as left, \
self._get_block(right_node) as right:
blocks = [left, block, right]
pivots = [left_pivot, right_pivot]
entries, pointers, before = self._extract(blocks, pivots)
# If there's a chance that we could use two pages instead
# of three, go for it
pivots = self._split2(blocks, entries, pointers,
before, bool(next_node))
if pivots is None:
ptrs = [left_node, node, right_node]
pivots = self._split3(blocks, entries, pointers,
before, bool(next_node))
else:
if pivots:
ptrs = [left_node, node]
else:
ptrs = [left_node]
self._store.release(node)
self._nodes -= 1
node = left_node
self._store.release(right_node)
self._nodes -= 1
self._dirty = True
# Remove the pivots from the parent
with self._get_block(path[-1]) as parent:
if right_node == parent_next:
parent.seek(left_pos)
parent.delete(right_pos - left_pos)
parent_next = left_node
else:
parent.seek(left_pos + 4)
parent.delete(right_pos - left_pos)
parent.seek(0)
parent_count -= 2
parent.write(b'>II', parent_next, parent_count)
self._records -= 2
# Replace with those in pivots
for e,rp in zip(pivots, ptrs[1:]):
self._insert_inner(path[:-1], path[-1], e, rp)
elif left_node:
with self._get_block(left_node) as left:
blocks = [left, block]
pivots = [left_pivot]
entries, pointers, before = self._extract(blocks, pivots)
pivots = self._split2(blocks, entries, pointers,
before, bool(next_node))
# Remove the pivot from the parent
with self._get_block(path[-1]) as parent:
if node == parent_next:
parent.seek(left_pos)
parent.delete(node_pos - left_pos)
parent_next = left_node
else:
parent.seek(left_pos + 4)
parent.delete(node_pos - left_pos)
parent.seek(0)
parent_count -= 1
parent.write(b'>II', parent_next, parent_count)
self._records -= 1
# Replace the pivot
if pivots:
self._insert_inner(path[:-1], path[-1], pivots[0], node)
elif right_node:
with self._get_block(right_node) as right:
blocks = [block, right]
pivots = [right_pivot]
entries, pointers, before = self._extract(blocks, pivots)
pivots = self._split2(blocks, entries, pointers,
before, bool(next_node))
# Remove the pivot from the parent
with self._get_block(path[-1]) as parent:
if right_node == parent_next:
parent.seek(pos)
parent.delete(right_pos - node_pos)
parent_next = node
else:
parent.seek(pos + 4)
parent.delete(right_pos - node_pos)
parent.seek(0)
parent_count -= 1
parent.write(b'>II', parent_next, parent_count)
self._records -= 1
# Replace the pivot
if pivots:
self._insert_inner(path[:-1], path[-1], pivots[0],
right_node)
if not path and not parent_count:
self._store.release(path[-1])
self._nodes -= 1
self._dirty = True
self._rootnode = node
else:
count, used = self._block_usage(path[-1])
if used < self._page_size // 2:
self._rebalance(path[:-1], path[-1])
# Delete from the leaf node `node'. `filename_lc' has already been
# lower-cased.
def _delete_leaf(self, node, filename_lc, code):
found = False
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
for n in range(count):
pos = block.tell()
e = DSStoreEntry.read(block)
if e.filename.lower() == filename_lc \
and (code is None or e.code == code):
block.seek(pos)
block.delete(e.byte_length())
found = True
# This does not affect the loop; THIS IS NOT A BUG
count -= 1
self._records -= 1
self._dirty = True
if found:
used = block.tell()
block.seek(0)
block.write(b'>II', next_node, count)
return used < self._page_size // 2
else:
return False
# Remove the largest entry from the subtree starting at `node' (with
# path from root `path'). Returns a tuple (rebalance, entry) where
# rebalance is either None if no rebalancing is required, or a
# (path, node) tuple giving the details of the node to rebalance.
def _take_largest(self, path, node):
path = list(path)
rebalance = None
while True:
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
if next_node:
path.append(node)
node = next_node
continue
for n in range(count):
pos = block.tell()
e = DSStoreEntry.read(block)
count -= 1
block.seek(0)
block.write(b'>II', next_node, count)
if pos < self._page_size // 2:
rebalance = (path, node)
break
return rebalance, e
# Delete an entry from an inner node, `node'
def _delete_inner(self, path, node, filename_lc, code):
rebalance = False
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
for n in range(count):
pos = block.tell()
ptr = block.read(b'>I')[0]
e = DSStoreEntry.read(block)
if e.filename.lower() == filename_lc \
and (code is None or e.code == code):
# Take the largest from the left subtree
rebalance, largest = self._take_largest(path, ptr)
# Delete this entry
if n == count - 1:
right_ptr = next_node
next_node = ptr
block.seek(pos)
else:
right_ptr = block.read(b'>I')[0]
block.seek(pos + 4)
block.delete(e.byte_length() + 4)
count -= 1
block.seek(0)
block.write(b'>II', next_node, count)
self._records -= 1
self._dirty = True
break
# Replace the pivot value
self._insert_inner(path, node, largest, right_ptr)
# Rebalance from the node we stole from
if rebalance:
self._rebalance(rebalance[0], rebalance[1])
return True
return False
def delete(self, filename, code):
"""Delete an item, identified by ``filename`` and ``code``
from the B-Tree."""
if isinstance(filename, DSStoreEntry):
code = filename.code
filename = filename.filename
# If we're deleting *every* node for "filename", we must recurse
if code is None:
###TODO: Fix this so we can do bulk deletes
raise ValueError('You must delete items individually. Sorry')
# Otherwise, we're deleting *one* specific node
filename_lc = filename.lower()
path = []
node = self._rootnode
while True:
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
if next_node:
for n in range(count):
ptr = block.read(b'>I')[0]
e = DSStoreEntry.read(block)
e_lc = e.filename.lower()
if filename_lc < e_lc \
or (filename_lc == e_lc and code < e.code):
next_node = ptr
break
elif filename_lc == e_lc and code == e.code:
self._delete_inner(path, node, filename_lc, code)
return
path.append(node)
node = next_node
else:
if self._delete_leaf(node, filename_lc, code):
self._rebalance(path, node)
return
# Find implementation
def _find(self, node, filename_lc, code=None):
with self._get_block(node) as block:
next_node, count = block.read(b'>II')
if next_node:
for n in range(count):
ptr = block.read(b'>I')[0]
e = DSStoreEntry.read(block)
if filename_lc < e.filename.lower():
for e in self._find(ptr, filename_lc, code):
yield e
return
elif filename_lc == e.filename.lower():
if code is None or (code and code < e.code):
for e in self._find(ptr, filename_lc, code):
yield e
if code is None or code == e.code:
yield e
elif code < e.code:
return
for e in self._find(next_node, filename_lc, code):
yield e
else:
for n in range(count):
e = DSStoreEntry.read(block)
if filename_lc == e.filename.lower():
if code is None or code == e.code:
yield e
elif code < e.code:
return
def find(self, filename, code=None):
"""Returns a generator that will iterate over matching entries in
the B-Tree."""
if isinstance(filename, DSStoreEntry):
code = filename.code
filename = filename.filename
filename_lc = filename.lower()
return self._find(self._rootnode, filename_lc, code)
def __len__(self):
return self._records
def __iter__(self):
return self._traverse(self._rootnode)
class Partial(object):
"""This is used to implement indexing."""
def __init__(self, store, filename):
self._store = store
self._filename = filename
def __getitem__(self, code):
if code is None:
raise KeyError('no such key - [%s][None]' % self._filename)
try:
item = next(self._store.find(self._filename, code))
except StopIteration:
raise KeyError('no such key - [%s][%s]' % (self._filename,
code))
if not isinstance(item.type, (str, unicode)):
return item.value
return (item.type, item.value)
def __setitem__(self, code, value):
if code is None:
raise KeyError('bad key - [%s][None]' % self._filename)
codec = codecs.get(code, None)
if codec:
entry_type = codec
entry_value = value
else:
entry_type = value[0]
entry_value = value[1]
self._store.insert(DSStoreEntry(self._filename, code,
entry_type, entry_value))
def __delitem__(self, code):
if code is None:
raise KeyError('no such key - [%s][None]' % self._filename)
self._store.delete(self._filename, code)
def __iter__(self):
for item in self._store.find(self._filename):
yield item
def __getitem__(self, filename):
return self.Partial(self, filename)
| agpl-3.0 |
pchaigno/grr | lib/rdfvalues/structs_test.py | 5 | 16288 | #!/usr/bin/env python
# -*- mode: python; encoding: utf-8 -*-
"""Test RDFStruct implementations."""
from google.protobuf import descriptor_pool
from google.protobuf import message_factory
from grr.lib import flags
from grr.lib import rdfvalue
from grr.lib import test_lib
from grr.lib import type_info
from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfvalues import flows as rdf_flows
from grr.lib.rdfvalues import paths as rdf_paths
from grr.lib.rdfvalues import structs
from grr.lib.rdfvalues import test_base
# pylint: mode=test
class TestStruct(structs.RDFProtoStruct):
"""A test struct object."""
type_description = type_info.TypeDescriptorSet(
type_info.ProtoString(name="foobar", field_number=1, default="string",
description="A string value"),
type_info.ProtoUnsignedInteger(name="int", field_number=2, default=5,
description="An integer value"),
type_info.ProtoList(type_info.ProtoString(
name="repeated", field_number=3,
description="A repeated string value")),
# We can serialize an arbitrary RDFValue. This will be serialized into a
# binary string and parsed on demand.
type_info.ProtoRDFValue(name="urn", field_number=6,
default=rdfvalue.RDFURN("www.google.com"),
rdf_type="RDFURN",
description="An arbitrary RDFValue field."),
type_info.ProtoEnum(name="type", field_number=7,
enum_name="Type",
enum=dict(FIRST=1, SECOND=2, THIRD=3),
default=3, description="An enum field"),
type_info.ProtoFloat(name="float", field_number=8,
description="A float number", default=1.1),
)
# In order to define a recursive structure we must add it manually after the
# class definition.
TestStruct.AddDescriptor(
type_info.ProtoEmbedded(
name="nested", field_number=4,
nested=TestStruct),
)
TestStruct.AddDescriptor(
type_info.ProtoList(type_info.ProtoEmbedded(
name="repeat_nested", field_number=5,
nested=TestStruct)),
)
class PartialTest1(structs.RDFProtoStruct):
"""This is a protobuf with fewer fields than TestStruct."""
type_description = type_info.TypeDescriptorSet(
type_info.ProtoUnsignedInteger(name="int", field_number=2),
)
class DynamicTypeTest(structs.RDFProtoStruct):
"""A protobuf with dynamic types."""
type_description = type_info.TypeDescriptorSet(
type_info.ProtoString(
name="type", field_number=1,
# By default return the TestStruct proto.
default="TestStruct",
description="A string value"),
type_info.ProtoDynamicEmbedded(
name="dynamic",
# The callback here returns the type specified by the type member.
dynamic_cb=lambda x: structs.RDFProtoStruct.classes.get(x.type),
field_number=2,
description="A dynamic value based on another field."),
type_info.ProtoEmbedded(name="nested", field_number=3,
nested=rdf_client.User)
)
class LateBindingTest(structs.RDFProtoStruct):
type_description = type_info.TypeDescriptorSet(
# A nested protobuf referring to an undefined type.
type_info.ProtoEmbedded(name="nested", field_number=1,
nested="UndefinedYet"),
type_info.ProtoRDFValue(name="rdfvalue", field_number=6,
rdf_type="UndefinedRDFValue",
description="An undefined RDFValue field."),
# A repeated late bound field.
type_info.ProtoList(
type_info.ProtoRDFValue(name="repeated", field_number=7,
rdf_type="UndefinedRDFValue2",
description="An undefined RDFValue field.")),
)
class RDFStructsTest(test_base.RDFValueTestCase):
"""Test the RDFStruct implementation."""
rdfvalue_class = TestStruct
def GenerateSample(self, number=1):
return self.rdfvalue_class(int=number, foobar="foo%s" % number,
urn="www.example.com",
float=2.3 + number)
def testDynamicType(self):
test_pb = DynamicTypeTest()
# We can not assign arbitrary values to the dynamic field.
self.assertRaises(ValueError, setattr, test_pb, "dynamic", "hello")
# Can assign a nested field.
test_pb.dynamic.foobar = "Hello"
self.assertTrue(isinstance(test_pb.dynamic, TestStruct))
def testProtoFileDescriptorIsGeneratedForDynamicType(self):
test_pb_file_descriptor, deps = DynamicTypeTest.EmitProtoFileDescriptor(
"grr_export")
pool = descriptor_pool.DescriptorPool()
for file_descriptor in [test_pb_file_descriptor] + deps:
pool.Add(file_descriptor)
proto_descriptor = pool.FindMessageTypeByName("grr_export.DynamicTypeTest")
factory = message_factory.MessageFactory()
proto_class = factory.GetPrototype(proto_descriptor)
# Now let's define an RDFProtoStruct for the dynamically generated
# proto_class.
new_dynamic_class = type("DynamicTypeTestReversed",
(structs.RDFProtoStruct,),
dict(protobuf=proto_class))
new_dynamic_instance = new_dynamic_class(
type="foo", nested=rdf_client.User(username="bar"))
self.assertEqual(new_dynamic_instance.type, "foo")
self.assertEqual(new_dynamic_instance.nested.username, "bar")
def testStructDefinition(self):
"""Ensure that errors in struct definitions are raised."""
# A descriptor without a field number should raise.
self.assertRaises(type_info.TypeValueError,
type_info.ProtoEmbedded, name="name")
# Adding a duplicate field number should raise.
self.assertRaises(
type_info.TypeValueError, TestStruct.AddDescriptor,
type_info.ProtoUnsignedInteger(name="int", field_number=2))
# Adding a descriptor which is not a Proto* descriptor is not allowed for
# Struct fields:
self.assertRaises(
type_info.TypeValueError, TestStruct.AddDescriptor,
type_info.String(name="int"))
def testRepeatedMember(self):
tested = TestStruct(int=5)
tested.foobar = "Hello"
tested.repeated.Append("Good")
tested.repeated.Append("Bye")
for i in range(10):
tested.repeat_nested.Append(foobar="Nest%s" % i)
data = tested.SerializeToString()
# Parse it again.
new_tested = TestStruct(data)
# Test the repeated field.
self.assertEqual(len(new_tested.repeat_nested), 10)
self.assertEqual(new_tested.repeat_nested[1].foobar, "Nest1")
# Check that slicing works.
sliced = new_tested.repeat_nested[3:5]
self.assertEqual(sliced.__class__, new_tested.repeat_nested.__class__)
self.assertEqual(sliced.type_descriptor,
new_tested.repeat_nested.type_descriptor)
self.assertEqual(len(sliced), 2)
self.assertEqual(sliced[0].foobar, "Nest3")
def testUnknownFields(self):
"""Test that unknown fields are preserved across decode/encode cycle."""
tested = TestStruct(foobar="hello", int=5)
tested.nested.foobar = "goodbye"
self.assertEqual(tested.foobar, "hello")
self.assertEqual(tested.nested.foobar, "goodbye")
data = tested.SerializeToString()
# Now unpack using a protobuf with less fields defined.
reduced_tested = PartialTest1(data)
self.assertEqual(reduced_tested.int, 5)
self.assertRaises(AttributeError, getattr, reduced_tested, "foobar")
# Re-Serialize using the simple protobuf.
data2 = reduced_tested.SerializeToString()
decoded_tested = TestStruct(data2)
# The foobar field should have been preserved, despite PartialTest1() not
# understanding it.
self.assertEqual(decoded_tested.foobar, "hello")
# Check that nested fields are also preserved.
self.assertEqual(decoded_tested.nested.foobar, "goodbye")
def testRDFStruct(self):
tested = TestStruct()
# cant set integers for string attributes.
self.assertRaises(type_info.TypeValueError, setattr,
tested, "foobar", 1)
# This is a string so a string assignment is good:
tested.foobar = "Hello"
self.assertEqual(tested.foobar, "Hello")
# This field must be another TestStruct instance..
self.assertRaises(ValueError, setattr, tested, "nested", "foo")
# Its ok to assign a compatible semantic protobuf.
tested.nested = TestStruct(foobar="nested_foo")
# Not OK to use the wrong semantic type.
self.assertRaises(
ValueError, setattr, tested, "nested", PartialTest1(int=1))
# Not OK to assign a serialized string - even if it is for the right type -
# since there is no type checking.
serialized = TestStruct(foobar="nested_foo").SerializeToString()
self.assertRaises(ValueError, setattr, tested, "nested", serialized)
# Nested accessors.
self.assertEqual(tested.nested.foobar, "nested_foo")
# Test repeated elements:
# Empty list is ok:
tested.repeated = []
self.assertEqual(tested.repeated, [])
tested.repeated = ["string"]
self.assertEqual(tested.repeated, ["string"])
self.assertRaises(type_info.TypeValueError, setattr, tested, "repeated",
[1, 2, 3])
# Coercing on assignment. This field is an RDFURN:
tested.urn = "www.example.com"
self.assertTrue(isinstance(tested.urn, rdfvalue.RDFURN))
self.assertEqual(tested.urn, rdfvalue.RDFURN("www.example.com"))
# Test enums.
self.assertEqual(tested.type, 3)
self.assertEqual(tested.type.name, "THIRD")
tested.type = "FIRST"
self.assertEqual(tested.type, 1)
# Non-valid types are rejected.
self.assertRaises(type_info.TypeValueError, setattr, tested, "type", "Foo")
# Strings of digits should be accepted.
tested.type = "2"
self.assertEqual(tested.type, 2)
# unicode strings should be treated the same way.
tested.type = u"2"
self.assertEqual(tested.type, 2)
# Out of range values are permitted and preserved through serialization.
tested.type = 4
self.assertEqual(tested.type, 4)
serialized_type = str(tested.type)
tested.type = 1
tested.type = serialized_type
self.assertEqual(tested.type, 4)
def testCacheInvalidation(self):
path = rdf_paths.PathSpec(path="/", pathtype=rdf_paths.PathSpec.PathType.OS)
for x in "01234":
path.last.Append(path=x, pathtype=rdf_paths.PathSpec.PathType.OS)
serialized = path.SerializeToString()
path = rdf_paths.PathSpec(serialized)
# At this point the wire format cache is fully populated (since the proto
# had been parsed). We change a deeply nested member.
path.last.path = "booo"
# When we serialize the modified proto we should get the new field
# serialized. If the cache is not properly invalidated, we will return the
# old result instead.
self.assertTrue("booo" in path.SerializeToString())
def testWireFormatAccess(self):
m = rdf_flows.SignedMessageList()
now = 1369308998000000
# An unset RDFDatetime with no defaults will be None.
self.assertEqual(m.timestamp, None)
# Set the wireformat to the integer equivalent.
m.SetPrimitive("timestamp", now)
self.assertTrue(isinstance(m.timestamp, rdfvalue.RDFDatetime))
self.assertEqual(m.timestamp, now)
rdf_now = rdfvalue.RDFDatetime().Now()
m.timestamp = rdf_now
self.assertEqual(m.GetPrimitive("timestamp"), int(rdf_now))
def testLateBinding(self):
# The LateBindingTest protobuf is not fully defined.
self.assertRaises(KeyError, LateBindingTest.type_infos.__getitem__,
"nested")
self.assertTrue("UndefinedYet" in rdfvalue._LATE_BINDING_STORE)
# We can still use this protobuf
tested = LateBindingTest()
# But it does not know about the field yet.
self.assertRaises(AttributeError, tested.Get, "nested")
self.assertRaises(AttributeError, LateBindingTest, nested=None)
# Now define the class. This should resolve the late bound fields and re-add
# them to their owner protobufs.
class UndefinedYet(structs.RDFProtoStruct):
type_description = type_info.TypeDescriptorSet(
type_info.ProtoString(name="foobar", field_number=1,
description="A string value"),
)
# The field is now resolved.
self.assertFalse("UndefinedYet" in rdfvalue._LATE_BINDING_STORE)
nested_field = LateBindingTest.type_infos["nested"]
self.assertEqual(nested_field.name, "nested")
# We can now use the protobuf as normal.
tested = LateBindingTest()
tested.nested.foobar = "foobar string"
self.assertTrue(isinstance(tested.nested, UndefinedYet))
def testRDFValueLateBinding(self):
# The LateBindingTest protobuf is not fully defined.
self.assertRaises(KeyError, LateBindingTest.type_infos.__getitem__,
"rdfvalue")
self.assertTrue("UndefinedRDFValue" in rdfvalue._LATE_BINDING_STORE)
# We can still use this protobuf
tested = LateBindingTest()
# But it does not know about the field yet.
self.assertRaises(AttributeError, tested.Get, "rdfvalue")
self.assertRaises(AttributeError, LateBindingTest, rdfvalue="foo")
# Now define the class. This should resolve the late bound fields and re-add
# them to their owner protobufs.
class UndefinedRDFValue(rdfvalue.RDFString):
pass
# The field is now resolved.
self.assertFalse("UndefinedRDFValue" in rdfvalue._LATE_BINDING_STORE)
rdfvalue_field = LateBindingTest.type_infos["rdfvalue"]
self.assertEqual(rdfvalue_field.name, "rdfvalue")
# We can now use the protobuf as normal.
tested = LateBindingTest(rdfvalue="foo")
self.assertEqual(type(tested.rdfvalue), UndefinedRDFValue)
def testRepeatedRDFValueLateBinding(self):
# The LateBindingTest protobuf is not fully defined.
self.assertRaises(KeyError, LateBindingTest.type_infos.__getitem__,
"repeated")
self.assertTrue("UndefinedRDFValue2" in rdfvalue._LATE_BINDING_STORE)
# We can still use this protobuf
tested = LateBindingTest()
# But it does not know about the field yet.
self.assertRaises(AttributeError, tested.Get, "repeated")
self.assertRaises(AttributeError, LateBindingTest, repeated=["foo"])
# Now define the class. This should resolve the late bound fields and re-add
# them to their owner protobufs.
class UndefinedRDFValue2(rdfvalue.RDFString):
pass
# The field is now resolved.
self.assertFalse("UndefinedRDFValue2" in rdfvalue._LATE_BINDING_STORE)
rdfvalue_field = LateBindingTest.type_infos["repeated"]
self.assertEqual(rdfvalue_field.name, "repeated")
# We can now use the protobuf as normal.
tested = LateBindingTest(repeated=["foo"])
self.assertEqual(len(tested.repeated), 1)
self.assertEqual(tested.repeated[0], "foo")
self.assertEqual(type(tested.repeated[0]), UndefinedRDFValue2)
def testRDFValueParsing(self):
stat = rdf_client.StatEntry.protobuf(st_mode=16877)
data = stat.SerializeToString()
result = rdf_client.StatEntry(data)
self.assertTrue(isinstance(result.st_mode, rdf_client.StatMode))
def testDefaults(self):
"""Accessing a field which does not exist returns a default."""
# An empty protobuf.
tested = TestStruct()
# Simple strings.
self.assertFalse(tested.HasField("foobar"))
self.assertEqual(tested.foobar, "string")
self.assertFalse(tested.HasField("foobar"))
# RDFValues.
self.assertFalse(tested.HasField("urn"))
self.assertEqual(tested.urn, "www.google.com")
self.assertFalse(tested.HasField("urn"))
# Nested fields: Accessing a nested field will create the nested protobuf.
self.assertFalse(tested.HasField("nested"))
self.assertEqual(tested.nested.urn, "www.google.com")
self.assertTrue(tested.HasField("nested"))
self.assertFalse(tested.nested.HasField("urn"))
def main(argv):
test_lib.GrrTestProgram(argv=argv)
if __name__ == "__main__":
flags.StartMain(main)
| apache-2.0 |
AmaanC/saxo | plugins/schema.py | 3 | 1233 | # http://inamidst.com/saxo/
# Created by Sean B. Palmer
import saxo
@saxo.setup
def instances(irc):
if not "saxo_instances" in irc.db:
irc.db["saxo_instances"].create(
("pid", int))
@saxo.setup
def periodic(irc):
sqlite3_schema = [(0, 'name', 'TEXT', 0, None, 1),
(1, 'period', 'INTEGER', 0, None, 0),
(2, 'recent', 'INTEGER', 0, None, 0),
(3, 'command', 'BLOB', 0, None, 0),
(4, 'args', 'BLOB', 0, None, 0)]
if "saxo_periodic" in irc.db:
schema = list(irc.db["saxo_periodic"].schema())
if schema != sqlite3_schema:
del irc.db["saxo_periodic"]
if "saxo_periodic" not in irc.db:
irc.db["saxo_periodic"].create(("name", "TEXT PRIMARY KEY"),
("period", int),
("recent", int),
("command", bytes),
("args", bytes))
@saxo.setup
def schedule(irc):
if not "saxo_schedule" in irc.db:
irc.db["saxo_schedule"].create(
("unixtime", int),
("command", bytes),
("args", bytes))
| apache-2.0 |
meabsence/python-for-android | python-modules/pybluez/examples/bluezchat/bluezchat.py | 47 | 5998 | #!/usr/bin/python
""" A simple graphical chat client to demonstrate the use of pybluez.
Opens a l2cap socket and listens on PSM 0x1001
Provides the ability to scan for nearby bluetooth devices and establish chat
sessions with them.
"""
import os
import sys
import time
import gtk
import gobject
import gtk.glade
import bluetooth
GLADEFILE="bluezchat.glade"
# *****************
def alert(text, buttons=gtk.BUTTONS_NONE, type=gtk.MESSAGE_INFO):
md = gtk.MessageDialog(buttons=buttons, type=type)
md.label.set_text(text)
md.run()
md.destroy()
class BluezChatGui:
def __init__(self):
self.main_window_xml = gtk.glade.XML(GLADEFILE, "bluezchat_window")
# connect our signal handlers
dic = { "on_quit_button_clicked" : self.quit_button_clicked,
"on_send_button_clicked" : self.send_button_clicked,
"on_chat_button_clicked" : self.chat_button_clicked,
"on_scan_button_clicked" : self.scan_button_clicked,
"on_devices_tv_cursor_changed" : self.devices_tv_cursor_changed
}
self.main_window_xml.signal_autoconnect(dic)
# prepare the floor listbox
self.devices_tv = self.main_window_xml.get_widget("devices_tv")
self.discovered = gtk.ListStore(gobject.TYPE_STRING,
gobject.TYPE_STRING)
self.devices_tv.set_model(self.discovered)
renderer = gtk.CellRendererText()
column1=gtk.TreeViewColumn("addr", renderer, text=0)
column2=gtk.TreeViewColumn("name", renderer, text=1)
self.devices_tv.append_column(column1)
self.devices_tv.append_column(column2)
self.quit_button = self.main_window_xml.get_widget("quit_button")
self.scan_button = self.main_window_xml.get_widget("scan_button")
self.chat_button = self.main_window_xml.get_widget("chat_button")
self.send_button = self.main_window_xml.get_widget("send_button")
self.main_text = self.main_window_xml.get_widget("main_text")
self.text_buffer = self.main_text.get_buffer()
self.input_tb = self.main_window_xml.get_widget("input_tb")
self.listed_devs = []
self.chat_button.set_sensitive(False)
self.peers = {}
self.sources = {}
self.addresses = {}
# the listening sockets
self.server_sock = None
# --- gui signal handlers
def quit_button_clicked(self, widget):
gtk.main_quit()
def scan_button_clicked(self, widget):
self.quit_button.set_sensitive(False)
self.scan_button.set_sensitive(False)
# self.chat_button.set_sensitive(False)
self.discovered.clear()
for addr, name in bluetooth.discover_devices (lookup_names = True):
self.discovered.append ((addr, name))
self.quit_button.set_sensitive(True)
self.scan_button.set_sensitive(True)
# self.chat_button.set_sensitive(True)
def send_button_clicked(self, widget):
text = self.input_tb.get_text()
if len(text) == 0: return
for addr, sock in self.peers.items():
sock.send(text)
self.input_tb.set_text("")
self.add_text("\nme - %s" % text)
def chat_button_clicked(self, widget):
(model, iter) = self.devices_tv.get_selection().get_selected()
if iter is not None:
addr = model.get_value(iter, 0)
if addr not in self.peers:
self.add_text("\nconnecting to %s" % addr)
self.connect(addr)
else:
self.add_text("\nAlready connected to %s!" % addr)
def devices_tv_cursor_changed(self, widget):
(model, iter) = self.devices_tv.get_selection().get_selected()
if iter is not None:
self.chat_button.set_sensitive(True)
else:
self.chat_button.set_sensitive(False)
# --- network events
def incoming_connection(self, source, condition):
sock, info = self.server_sock.accept()
address, psm = info
self.add_text("\naccepted connection from %s" % str(address))
# add new connection to list of peers
self.peers[address] = sock
self.addresses[sock] = address
source = gobject.io_add_watch (sock, gobject.IO_IN, self.data_ready)
self.sources[address] = source
return True
def data_ready(self, sock, condition):
address = self.addresses[sock]
data = sock.recv(1024)
if len(data) == 0:
self.add_text("\nlost connection with %s" % address)
gobject.source_remove(self.sources[address])
del self.sources[address]
del self.peers[address]
del self.addresses[sock]
sock.close()
else:
self.add_text("\n%s - %s" % (address, str(data)))
return True
# --- other stuff
def cleanup(self):
self.hci_sock.close()
def connect(self, addr):
sock = bluetooth.BluetoothSocket (bluetooth.L2CAP)
try:
sock.connect((addr, 0x1001))
except bluez.error, e:
self.add_text("\n%s" % str(e))
sock.close()
return
self.peers[addr] = sock
source = gobject.io_add_watch (sock, gobject.IO_IN, self.data_ready)
self.sources[addr] = source
self.addresses[sock] = addr
def add_text(self, text):
self.text_buffer.insert(self.text_buffer.get_end_iter(), text)
def start_server(self):
self.server_sock = bluetooth.BluetoothSocket (bluetooth.L2CAP)
self.server_sock.bind(("",0x1001))
self.server_sock.listen(1)
gobject.io_add_watch(self.server_sock,
gobject.IO_IN, self.incoming_connection)
def run(self):
self.text_buffer.insert(self.text_buffer.get_end_iter(), "loading..")
self.start_server()
gtk.main()
if __name__ == "__main__":
gui = BluezChatGui()
gui.run()
| apache-2.0 |
renegelinas/mi-instrument | mi/instrument/mclane/ras/ppsdn/test/test_driver.py | 8 | 27669 | """
@package mi.instrument.mclane.pps.ooicore.test.test_driver
@file marine-integrations/mi/instrument/mclane/pps/ooicore/test/test_driver.py
@author Dan Mergens
@brief Test cases for ppsdn driver
USAGE:
Make tests verbose and provide stdout
* From the IDK
$ bin/test_driver
$ bin/test_driver -u [-t testname]
$ bin/test_driver -i [-t testname]
$ bin/test_driver -q [-t testname]
"""
__author__ = 'Dan Mergens'
__license__ = 'Apache 2.0'
import unittest
import time
import gevent
from mock import Mock
from nose.plugins.attrib import attr
from mi.core.log import get_logger
from mi.core.instrument.instrument_driver import DriverConfigKey, DriverProtocolState
from mi.core.time_tools import timegm_to_float
log = get_logger()
# MI imports.
from mi.idk.unit_test import \
InstrumentDriverTestCase, \
InstrumentDriverUnitTestCase, \
InstrumentDriverIntegrationTestCase, \
InstrumentDriverQualificationTestCase, \
DriverTestMixin, \
ParameterTestConfigKey, \
AgentCapabilityType
from mi.core.instrument.chunker import StringChunker
from mi.instrument.mclane.driver import \
ProtocolState, \
ProtocolEvent, \
Capability, \
Prompt, \
NEWLINE, \
McLaneSampleDataParticleKey
from mi.instrument.mclane.ras.ppsdn.driver import \
InstrumentDriver, \
DataParticleType, \
Command, \
Parameter, \
Protocol, \
PPSDNSampleDataParticle
from mi.core.exceptions import SampleException
# from interface.objects import AgentCommand
from mi.core.direct_access_server import DirectAccessTypes
from mi.core.instrument.instrument_driver import ResourceAgentState, ResourceAgentEvent
# Globals
raw_stream_received = False
parsed_stream_received = False
ACQUIRE_TIMEOUT = 45 * 60 + 50
CLEAR_TIMEOUT = 110
###
# Driver parameters for the tests
###
InstrumentDriverTestCase.initialize(
driver_module='mi.instrument.mclane.ras.ppsdn.driver',
driver_class="InstrumentDriver",
instrument_agent_resource_id='DQPJJX',
instrument_agent_name='mclane_ras_ppsdn',
instrument_agent_packet_config=DataParticleType(),
driver_startup_config={DriverConfigKey.PARAMETERS: {
Parameter.CLEAR_VOLUME: 10,
Parameter.FILL_VOLUME: 10,
Parameter.FLUSH_VOLUME: 10,
}},
)
#################################### RULES ####################################
# #
# Common capabilities in the base class #
# #
# Instrument specific stuff in the derived class #
# #
# Generator spits out either stubs or comments describing test this here, #
# test that there. #
# #
# Qualification tests are driven through the instrument_agent #
# #
###############################################################################
###
# Driver constant definitions
###
###############################################################################
# DATA PARTICLE TEST MIXIN #
# Defines a set of assert methods used for data particle verification #
# #
# In python mixin classes are classes designed such that they wouldn't be #
# able to stand on their own, but are inherited by other classes generally #
# using multiple inheritance. #
# #
# This class defines a configuration structure for testing and common assert #
# methods for validating data particles.
###############################################################################
class UtilMixin(DriverTestMixin):
"""
Mixin class used for storing data particle constants and common data assertion methods.
"""
# Create some short names for the parameter test config
TYPE = ParameterTestConfigKey.TYPE
READONLY = ParameterTestConfigKey.READONLY
STARTUP = ParameterTestConfigKey.STARTUP
DA = ParameterTestConfigKey.DIRECT_ACCESS
VALUE = ParameterTestConfigKey.VALUE
REQUIRED = ParameterTestConfigKey.REQUIRED
DEFAULT = ParameterTestConfigKey.DEFAULT
STATES = ParameterTestConfigKey.STATES
# battery voltage request response - TODO not implemented
PPSDN_BATTERY_DATA = "Battery: 30.1V [Alkaline, 18V minimum]" + NEWLINE
# bag capacity response - TODO not implemented
PPSDN_CAPACITY_DATA = "Capacity: Maxon 250mL" + NEWLINE
PPSDN_VERSION_DATA = \
"Version:" + NEWLINE + \
NEWLINE + \
"McLane Research Laboratories, Inc." + NEWLINE + \
"CF2 Adaptive Water Transfer System" + NEWLINE + \
"Version 2.02 of Jun 7 2013 18:17" + NEWLINE + \
" Configured for: Maxon 250ml pump" + NEWLINE
# response from collect sample meta command (from FORWARD or REVERSE command)
PPSDN_SAMPLE_DATA1 = "Status 00 | 75 100 25 4 | 1.5 90.7 .907* 1 031514 001727 | 29.9 0" + NEWLINE
PPSDN_SAMPLE_DATA2 = "Status 00 | 75 100 25 4 | 3.2 101.2 101.2* 2 031514 001728 | 29.9 0" + NEWLINE
PPSDN_SAMPLE_DATA3 = "Result 00 | 75 100 25 4 | 77.2 98.5 99.1 47 031514 001813 | 29.8 1" + NEWLINE
_driver_capabilities = {
# capabilities defined in the IOS
Capability.DISCOVER: {STATES: [ProtocolState.UNKNOWN]},
Capability.CLOCK_SYNC: {STATES: [ProtocolState.COMMAND]},
}
###
# Parameter and Type Definitions
###
_driver_parameters = {
Parameter.FLUSH_VOLUME: {TYPE: int, READONLY: True, DA: False, STARTUP: True, VALUE: 150, REQUIRED: True},
Parameter.FLUSH_FLOWRATE: {TYPE: int, READONLY: True, DA: False, STARTUP: True, VALUE: 100, REQUIRED: True},
Parameter.FLUSH_MINFLOW: {TYPE: int, READONLY: True, DA: False, STARTUP: True, VALUE: 75, REQUIRED: True},
Parameter.FILL_VOLUME: {TYPE: int, READONLY: True, DA: False, STARTUP: True, VALUE: 4000, REQUIRED: True},
Parameter.FILL_FLOWRATE: {TYPE: int, READONLY: True, DA: False, STARTUP: True, VALUE: 100, REQUIRED: True},
Parameter.FILL_MINFLOW: {TYPE: int, READONLY: True, DA: False, STARTUP: True, VALUE: 75, REQUIRED: True},
Parameter.CLEAR_VOLUME: {TYPE: int, READONLY: True, DA: False, STARTUP: True, VALUE: 100, REQUIRED: True},
Parameter.CLEAR_FLOWRATE: {TYPE: int, READONLY: True, DA: False, STARTUP: True, VALUE: 100, REQUIRED: True},
Parameter.CLEAR_MINFLOW: {TYPE: int, READONLY: True, DA: False, STARTUP: True, VALUE: 75, REQUIRED: True}}
###
# Data Particle Parameters
###
_sample_parameters = {
McLaneSampleDataParticleKey.PORT: {'type': int, 'value': 0},
McLaneSampleDataParticleKey.VOLUME_COMMANDED: {'type': int, 'value': 75},
McLaneSampleDataParticleKey.FLOW_RATE_COMMANDED: {'type': int, 'value': 100},
McLaneSampleDataParticleKey.MIN_FLOW_COMMANDED: {'type': int, 'value': 25},
McLaneSampleDataParticleKey.TIME_LIMIT: {'type': int, 'value': 4},
McLaneSampleDataParticleKey.VOLUME_ACTUAL: {'type': float, 'value': 1.5},
McLaneSampleDataParticleKey.FLOW_RATE_ACTUAL: {'type': float, 'value': 90.7},
McLaneSampleDataParticleKey.MIN_FLOW_ACTUAL: {'type': float, 'value': 0.907},
McLaneSampleDataParticleKey.TIMER: {'type': int, 'value': 1},
McLaneSampleDataParticleKey.TIME: {'type': unicode, 'value': '031514 001727'},
McLaneSampleDataParticleKey.BATTERY: {'type': float, 'value': 29.9},
McLaneSampleDataParticleKey.CODE: {'type': int, 'value': 0},
}
###
# Driver Parameter Methods
###
def assert_driver_parameters(self, current_parameters, verify_values=False):
"""
Verify that all driver parameters are correct and potentially verify values.
@param current_parameters: driver parameters read from the driver instance
@param verify_values: should we verify values against definition?
"""
self.assert_parameters(current_parameters, self._driver_parameters, verify_values)
###
# Data Particle Parameters Methods
###
def assert_data_particle_sample(self, data_particle, verify_values=False):
"""
Verify an PPSDN sample data particle
@param data_particle: OPTAAA_SampleDataParticle data particle
@param verify_values: bool, should we verify parameter values
"""
self.assert_data_particle_header(data_particle, DataParticleType.PPSDN_PARSED)
self.assert_data_particle_parameters(data_particle, self._sample_parameters, verify_values)
# TODO - need to define status particle values
def assert_data_particle_status(self, data_particle, verify_values=False):
"""
Verify a PPSDN pump status data particle
@param data_particle: PPSDN_StatusDataParticle data particle
@param verify_values: bool, should we verify parameter values
"""
# self.assert_data_particle_header(data_particle, DataParticleType.PPSDN_STATUS)
# self.assert_data_particle_parameters(data_particle, self._status_parameters, verify_values)
def assert_time_synched(self, pps_time, tolerance=5):
"""
Verify the retrieved time is within acceptable tolerance
"""
pps_time = time.strptime(pps_time + 'UTC', '%m/%d/%y %H:%M:%S %Z')
current_time = time.gmtime()
diff = timegm_to_float(current_time) - timegm_to_float(pps_time)
log.info('clock synched within %d seconds', diff)
# verify that the time matches to within tolerance seconds
self.assertLessEqual(diff, tolerance)
###############################################################################
# UNIT TESTS #
# Unit tests test the method calls and parameters using Mock. #
# #
# These tests are especially useful for testing parsers and other data #
# handling. The tests generally focus on small segments of code, like a #
# single function call, but more complex code using Mock objects. However #
# if you find yourself mocking too much maybe it is better as an #
# integration test. #
# #
# Unit tests do not start up external processes like the port agent or #
# driver process. #
###############################################################################
@attr('UNIT', group='mi')
class TestUNIT(InstrumentDriverUnitTestCase, UtilMixin):
def setUp(self):
InstrumentDriverUnitTestCase.setUp(self)
print '----- unit test -----'
#@unittest.skip('not completed yet')
def test_driver_enums(self):
"""
Verify that all driver enumeration has no duplicate values that might cause confusion. Also
do a little extra validation for the Capabilites
"""
self.assert_enum_has_no_duplicates(DataParticleType())
self.assert_enum_has_no_duplicates(ProtocolState())
self.assert_enum_has_no_duplicates(ProtocolEvent())
self.assert_enum_has_no_duplicates(Parameter())
self.assert_enum_has_no_duplicates(Command())
# Test capabilities for duplicates, then verify that capabilities is a subset of protocol events
self.assert_enum_has_no_duplicates(Capability())
self.assert_enum_complete(Capability(), ProtocolEvent())
def test_chunker(self):
"""
Test the chunker and verify the particles created.
"""
chunker = StringChunker(Protocol.sieve_function)
self.assert_chunker_sample(chunker, self.PPSDN_SAMPLE_DATA1)
self.assert_chunker_sample_with_noise(chunker, self.PPSDN_SAMPLE_DATA1)
self.assert_chunker_fragmented_sample(chunker, self.PPSDN_SAMPLE_DATA1)
self.assert_chunker_combined_sample(chunker, self.PPSDN_SAMPLE_DATA1)
self.assert_chunker_sample(chunker, self.PPSDN_SAMPLE_DATA2)
self.assert_chunker_sample_with_noise(chunker, self.PPSDN_SAMPLE_DATA2)
self.assert_chunker_fragmented_sample(chunker, self.PPSDN_SAMPLE_DATA2)
self.assert_chunker_combined_sample(chunker, self.PPSDN_SAMPLE_DATA2)
self.assert_chunker_sample(chunker, self.PPSDN_SAMPLE_DATA3)
self.assert_chunker_sample_with_noise(chunker, self.PPSDN_SAMPLE_DATA3)
self.assert_chunker_fragmented_sample(chunker, self.PPSDN_SAMPLE_DATA3)
self.assert_chunker_combined_sample(chunker, self.PPSDN_SAMPLE_DATA3)
def test_corrupt_data_sample(self):
# garbage is not okay
particle = PPSDNSampleDataParticle(self.PPSDN_SAMPLE_DATA1.replace('00', 'foo'),
port_timestamp=3558720820.531179)
with self.assertRaises(SampleException):
particle.generate()
def test_got_data(self):
"""
Verify sample data passed through the got data method produces the correct data particles
"""
# Create and initialize the instrument driver with a mock port agent
driver = InstrumentDriver(self._got_data_event_callback)
self.assert_initialize_driver(driver, initial_protocol_state=ProtocolState.FILL)
self.assert_raw_particle_published(driver, True)
# validating data particles are published
self.assert_particle_published(driver, self.PPSDN_SAMPLE_DATA1, self.assert_data_particle_sample, True)
# validate that a duplicate sample is not published - TODO
#self.assert_particle_not_published(driver, self.RASFL_SAMPLE_DATA1, self.assert_data_particle_sample, True)
# validate that a new sample is published
self.assert_particle_published(driver, self.PPSDN_SAMPLE_DATA2, self.assert_data_particle_sample, False)
def test_protocol_filter_capabilities(self):
"""
This tests driver filter_capabilities.
Iterate through available capabilities, and verify that they can pass successfully through the filter.
Test silly made up capabilities to verify they are blocked by filter.
"""
mock_callback = Mock(spec="UNKNOWN WHAT SHOULD GO HERE FOR evt_callback")
protocol = Protocol(Prompt, NEWLINE, mock_callback)
driver_capabilities = Capability().list()
test_capabilities = Capability().list()
# Add a bogus capability that will be filtered out.
test_capabilities.append("BOGUS_CAPABILITY")
# Verify "BOGUS_CAPABILITY was filtered out
self.assertEquals(sorted(driver_capabilities),
sorted(protocol._filter_capabilities(test_capabilities)))
def test_capabilities(self):
"""
Verify the FSM reports capabilities as expected. All states defined in this dict must
also be defined in the protocol FSM.
"""
capabilities = {
ProtocolState.UNKNOWN: [
ProtocolEvent.DISCOVER,
],
ProtocolState.COMMAND: [
ProtocolEvent.GET,
ProtocolEvent.SET,
ProtocolEvent.INIT_PARAMS,
ProtocolEvent.START_DIRECT,
ProtocolEvent.ACQUIRE_SAMPLE,
ProtocolEvent.CLEAR,
ProtocolEvent.CLOCK_SYNC,
],
ProtocolState.FLUSH: [
ProtocolEvent.FLUSH,
ProtocolEvent.PUMP_STATUS,
ProtocolEvent.INSTRUMENT_FAILURE,
],
ProtocolState.FILL: [
ProtocolEvent.FILL,
ProtocolEvent.PUMP_STATUS,
ProtocolEvent.INSTRUMENT_FAILURE,
],
ProtocolState.CLEAR: [
ProtocolEvent.CLEAR,
ProtocolEvent.PUMP_STATUS,
ProtocolEvent.INSTRUMENT_FAILURE,
],
ProtocolState.RECOVERY: [
],
ProtocolState.DIRECT_ACCESS: [
ProtocolEvent.STOP_DIRECT,
ProtocolEvent.EXECUTE_DIRECT,
],
}
driver = InstrumentDriver(self._got_data_event_callback)
self.assert_capabilities(driver, capabilities)
#@unittest.skip('not completed yet')
def test_driver_schema(self):
"""
get the driver schema and verify it is configured properly
"""
driver = InstrumentDriver(self._got_data_event_callback)
self.assert_driver_schema(driver, self._driver_parameters, self._driver_capabilities)
###############################################################################
# INTEGRATION TESTS #
# Integration test test the direct driver / instrument interaction #
# but making direct calls via zeromq. #
# - Common Integration tests test the driver through the instrument agent #
# and common for all drivers (minimum requirement for ION ingestion) #
###############################################################################
@attr('INT', group='mi')
class TestINT(InstrumentDriverIntegrationTestCase, UtilMixin):
def setUp(self):
InstrumentDriverIntegrationTestCase.setUp(self)
def assert_async_particle_not_generated(self, particle_type, timeout=10):
end_time = time.time() + timeout
while end_time > time.time():
if len(self.get_sample_events(particle_type)) > 0:
self.fail("assert_async_particle_not_generated: a particle of type %s was published" % particle_type)
time.sleep(.3)
def test_parameters(self):
"""
Test driver parameters and verify their type. Startup parameters also verify the parameter
value. This test confirms that parameters are being read/converted properly and that
the startup has been applied.
"""
self.assert_initialize_driver()
reply = self.driver_client.cmd_dvr('get_resource', Parameter.ALL)
log.debug('Startup parameters: %s', reply)
self.assert_driver_parameters(reply)
# self.assert_get(Parameter.FLUSH_VOLUME, value=100)
self.assert_get(Parameter.FLUSH_VOLUME, value=10)
self.assert_get(Parameter.FLUSH_FLOWRATE, value=100)
self.assert_get(Parameter.FLUSH_MINFLOW, value=75)
# self.assert_get(Parameter.FILL_VOLUME, value=4000)
self.assert_get(Parameter.FILL_VOLUME, value=10)
self.assert_get(Parameter.FILL_FLOWRATE, value=100)
self.assert_get(Parameter.FILL_MINFLOW, value=75)
# self.assert_get(Parameter.CLEAR_VOLUME, value=100)
self.assert_get(Parameter.CLEAR_VOLUME, value=10)
self.assert_get(Parameter.CLEAR_FLOWRATE, value=100)
self.assert_get(Parameter.CLEAR_MINFLOW, value=75)
# Verify that readonly/immutable parameters cannot be set (throw exception)
self.assert_set_exception(Parameter.FLUSH_VOLUME)
self.assert_set_exception(Parameter.FLUSH_FLOWRATE)
self.assert_set_exception(Parameter.FLUSH_MINFLOW)
self.assert_set_exception(Parameter.FILL_VOLUME)
self.assert_set_exception(Parameter.FILL_FLOWRATE)
self.assert_set_exception(Parameter.FILL_MINFLOW)
self.assert_set_exception(Parameter.CLEAR_VOLUME)
self.assert_set_exception(Parameter.CLEAR_FLOWRATE)
self.assert_set_exception(Parameter.CLEAR_MINFLOW)
def test_execute_clock_sync_command_mode(self):
"""
Verify we can synchronize the instrument internal clock in command mode
"""
self.assert_initialize_driver(ProtocolState.COMMAND)
reply = self.driver_client.cmd_dvr('execute_resource', ProtocolEvent.CLOCK_SYNC)
pps_time = reply[1]['time']
self.assert_time_synched(pps_time)
def test_acquire_sample(self):
"""
Test that we can generate sample particle with command
"""
self.assert_initialize_driver()
self.driver_client.cmd_dvr('execute_resource', ProtocolEvent.ACQUIRE_SAMPLE, driver_timeout=ACQUIRE_TIMEOUT)
self.assert_state_change(ProtocolState.FLUSH, ACQUIRE_TIMEOUT)
self.assert_state_change(ProtocolState.FILL, ACQUIRE_TIMEOUT)
self.assert_state_change(ProtocolState.CLEAR, ACQUIRE_TIMEOUT)
self.assert_state_change(ProtocolState.COMMAND, ACQUIRE_TIMEOUT)
self.assert_async_particle_generation(DataParticleType.PPSDN_PARSED, Mock(), 7)
def test_clear(self):
"""
Test user clear command
"""
self.assert_initialize_driver()
self.driver_client.cmd_dvr('execute_resource', ProtocolEvent.CLEAR)
self.assert_state_change(ProtocolState.CLEAR, CLEAR_TIMEOUT)
self.assert_state_change(ProtocolState.COMMAND, CLEAR_TIMEOUT)
@unittest.skip('not completed yet')
def test_obstructed_flush(self):
"""
Test condition when obstruction limits flow rate during initial flush
"""
# TODO
@unittest.skip('not completed yet')
def test_obstructed_fill(self):
"""
Test condition when obstruction occurs during collection of sample
"""
# TODO
################################################################################
# QUALIFICATION TESTS #
# Device specific qualification tests are for doing final testing of ion #
# integration. They generally aren't used for instrument debugging and should #
# be tackled after all unit and integration tests are complete #
################################################################################
@attr('QUAL', group='mi')
class TestQUAL(InstrumentDriverQualificationTestCase, UtilMixin):
def setUp(self):
InstrumentDriverQualificationTestCase.setUp(self)
def test_discover(self):
"""
Overridden because instrument does not have autosample mode and driver will always go into command mode
during the discover process after a restart.
"""
self.assert_enter_command_mode()
# Now reset and try to discover. This will stop the driver and cause it to re-discover which
# will always go back to command for this instrument
self.assert_reset()
self.assert_discover(ResourceAgentState.COMMAND)
def test_reset(self):
"""
Verify the agent can be reset
"""
self.assert_enter_command_mode()
self.assert_reset()
self.assert_enter_command_mode()
self.assert_direct_access_start_telnet(inactivity_timeout=60, session_timeout=60)
self.assert_state_change(ResourceAgentState.DIRECT_ACCESS, DriverProtocolState.DIRECT_ACCESS, 30)
self.assert_reset()
def test_direct_access_telnet_mode(self):
"""
@brief This test automatically tests that the Instrument Driver properly supports direct access to the physical
instrument. (telnet mode)
"""
self.assert_enter_command_mode()
# go into direct access
self.assert_direct_access_start_telnet(timeout=600)
self.tcp_client.send_data("port\r\n")
if not self.tcp_client.expect("Port: 00\r\n"):
self.fail("test_direct_access_telnet_mode: did not get expected response")
self.assert_direct_access_stop_telnet()
@unittest.skip('Only enabled and used for manual testing of vendor SW')
def test_direct_access_telnet_mode_manual(self):
"""
@brief This test manually tests that the Instrument Driver properly supports direct access to the physical
instrument. (virtual serial port mode)
"""
self.assert_enter_command_mode()
# go direct access
cmd = AgentCommand(command=ResourceAgentEvent.GO_DIRECT_ACCESS,
kwargs={'session_type': DirectAccessTypes.vsp,
'session_timeout': 600,
'inactivity_timeout': 600})
retval = self.instrument_agent_client.execute_agent(cmd, timeout=600)
log.warn("go_direct_access retval=" + str(retval.result))
state = self.instrument_agent_client.get_agent_state()
self.assertEqual(state, ResourceAgentState.DIRECT_ACCESS)
print("test_direct_access_telnet_mode: waiting 120 seconds for manual testing")
gevent.sleep(120)
cmd = AgentCommand(command=ResourceAgentEvent.GO_COMMAND)
self.instrument_agent_client.execute_agent(cmd)
state = self.instrument_agent_client.get_agent_state()
self.assertEqual(state, ResourceAgentState.COMMAND)
def test_get_capabilities(self):
"""
@brief Walk through all driver protocol states and verify capabilities
returned by get_current_capabilities
"""
self.assert_enter_command_mode()
##################
# Command Mode
##################
capabilities = {
AgentCapabilityType.AGENT_COMMAND: self._common_agent_commands(ResourceAgentState.COMMAND),
AgentCapabilityType.AGENT_PARAMETER: self._common_agent_parameters(),
AgentCapabilityType.RESOURCE_COMMAND: [
ProtocolEvent.ACQUIRE_SAMPLE,
ProtocolEvent.CLEAR,
ProtocolEvent.CLOCK_SYNC,
ProtocolEvent.GET,
ProtocolEvent.SET,
],
AgentCapabilityType.RESOURCE_INTERFACE: None,
AgentCapabilityType.RESOURCE_PARAMETER: self._driver_parameters.keys()
}
self.assert_capabilities(capabilities)
##################
# Streaming Mode - no autosample for RAS
##################
##################
# DA Mode
##################
capabilities[AgentCapabilityType.AGENT_COMMAND] = self._common_agent_commands(ResourceAgentState.DIRECT_ACCESS)
capabilities[AgentCapabilityType.RESOURCE_COMMAND] = self._common_da_resource_commands()
self.assert_direct_access_start_telnet()
self.assert_capabilities(capabilities)
self.assert_direct_access_stop_telnet()
#######################
# Uninitialized Mode
#######################
capabilities[AgentCapabilityType.AGENT_COMMAND] = self._common_agent_commands(ResourceAgentState.UNINITIALIZED)
capabilities[AgentCapabilityType.RESOURCE_COMMAND] = []
capabilities[AgentCapabilityType.RESOURCE_INTERFACE] = []
capabilities[AgentCapabilityType.RESOURCE_PARAMETER] = []
self.assert_reset()
self.assert_capabilities(capabilities)
def test_execute_clock_sync(self):
"""
Verify we can synchronize the instrument internal clock
"""
self.assert_enter_command_mode()
reply = self.assert_execute_resource(ProtocolEvent.CLOCK_SYNC)
pps_time = reply.result['time']
self.assert_time_synched(pps_time)
| bsd-2-clause |
waytai/odoo | openerp/service/server.py | 91 | 37483 | #-----------------------------------------------------------
# Threaded, Gevent and Prefork Servers
#-----------------------------------------------------------
import datetime
import errno
import logging
import os
import os.path
import platform
import random
import select
import signal
import socket
import subprocess
import sys
import threading
import time
import unittest2
import werkzeug.serving
if os.name == 'posix':
# Unix only for workers
import fcntl
import resource
import psutil
else:
# Windows shim
signal.SIGHUP = -1
# Optional process names for workers
try:
from setproctitle import setproctitle
except ImportError:
setproctitle = lambda x: None
import openerp
from openerp.modules.registry import RegistryManager
from openerp.release import nt_service_name
import openerp.tools.config as config
from openerp.tools import stripped_sys_argv, dumpstacks, log_ormcache_stats
_logger = logging.getLogger(__name__)
SLEEP_INTERVAL = 60 # 1 min
def memory_info(process):
""" psutil < 2.0 does not have memory_info, >= 3.0 does not have
get_memory_info """
return (getattr(process, 'memory_info', None) or process.get_memory_info)()
#----------------------------------------------------------
# Werkzeug WSGI servers patched
#----------------------------------------------------------
class LoggingBaseWSGIServerMixIn(object):
def handle_error(self, request, client_address):
t, e, _ = sys.exc_info()
if t == socket.error and e.errno == errno.EPIPE:
# broken pipe, ignore error
return
_logger.exception('Exception happened during processing of request from %s', client_address)
class BaseWSGIServerNoBind(LoggingBaseWSGIServerMixIn, werkzeug.serving.BaseWSGIServer):
""" werkzeug Base WSGI Server patched to skip socket binding. PreforkServer
use this class, sets the socket and calls the process_request() manually
"""
def __init__(self, app):
werkzeug.serving.BaseWSGIServer.__init__(self, "1", "1", app)
def server_bind(self):
# we dont bind beause we use the listen socket of PreforkServer#socket
# instead we close the socket
if self.socket:
self.socket.close()
def server_activate(self):
# dont listen as we use PreforkServer#socket
pass
class RequestHandler(werkzeug.serving.WSGIRequestHandler):
def setup(self):
# flag the current thread as handling a http request
super(RequestHandler, self).setup()
me = threading.currentThread()
me.name = 'openerp.service.http.request.%s' % (me.ident,)
# _reexec() should set LISTEN_* to avoid connection refused during reload time. It
# should also work with systemd socket activation. This is currently untested
# and not yet used.
class ThreadedWSGIServerReloadable(LoggingBaseWSGIServerMixIn, werkzeug.serving.ThreadedWSGIServer):
""" werkzeug Threaded WSGI Server patched to allow reusing a listen socket
given by the environement, this is used by autoreload to keep the listen
socket open when a reload happens.
"""
def __init__(self, host, port, app):
super(ThreadedWSGIServerReloadable, self).__init__(host, port, app,
handler=RequestHandler)
def server_bind(self):
envfd = os.environ.get('LISTEN_FDS')
if envfd and os.environ.get('LISTEN_PID') == str(os.getpid()):
self.reload_socket = True
self.socket = socket.fromfd(int(envfd), socket.AF_INET, socket.SOCK_STREAM)
# should we os.close(int(envfd)) ? it seem python duplicate the fd.
else:
self.reload_socket = False
super(ThreadedWSGIServerReloadable, self).server_bind()
def server_activate(self):
if not self.reload_socket:
super(ThreadedWSGIServerReloadable, self).server_activate()
#----------------------------------------------------------
# AutoReload watcher
#----------------------------------------------------------
class AutoReload(object):
def __init__(self, server):
self.server = server
self.files = {}
self.modules = {}
import pyinotify
class EventHandler(pyinotify.ProcessEvent):
def __init__(self, autoreload):
self.autoreload = autoreload
def process_IN_CREATE(self, event):
_logger.debug('File created: %s', event.pathname)
self.autoreload.files[event.pathname] = 1
def process_IN_MODIFY(self, event):
_logger.debug('File modified: %s', event.pathname)
self.autoreload.files[event.pathname] = 1
self.wm = pyinotify.WatchManager()
self.handler = EventHandler(self)
self.notifier = pyinotify.Notifier(self.wm, self.handler, timeout=0)
mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE # IN_MOVED_FROM, IN_MOVED_TO ?
for path in openerp.modules.module.ad_paths:
_logger.info('Watching addons folder %s', path)
self.wm.add_watch(path, mask, rec=True)
def process_data(self, files):
xml_files = [i for i in files if i.endswith('.xml')]
for i in xml_files:
for path in openerp.modules.module.ad_paths:
if i.startswith(path):
# find out wich addons path the file belongs to
# and extract it's module name
right = i[len(path) + 1:].split('/')
if len(right) < 2:
continue
module = right[0]
self.modules[module] = 1
if self.modules:
_logger.info('autoreload: xml change detected, autoreload activated')
restart()
def process_python(self, files):
# process python changes
py_files = [i for i in files if i.endswith('.py')]
py_errors = []
# TODO keep python errors until they are ok
if py_files:
for i in py_files:
try:
source = open(i, 'rb').read() + '\n'
compile(source, i, 'exec')
except SyntaxError:
py_errors.append(i)
if py_errors:
_logger.info('autoreload: python code change detected, errors found')
for i in py_errors:
_logger.info('autoreload: SyntaxError %s', i)
else:
_logger.info('autoreload: python code updated, autoreload activated')
restart()
def check_thread(self):
# Check if some files have been touched in the addons path.
# If true, check if the touched file belongs to an installed module
# in any of the database used in the registry manager.
while 1:
while self.notifier.check_events(1000):
self.notifier.read_events()
self.notifier.process_events()
l = self.files.keys()
self.files.clear()
self.process_data(l)
self.process_python(l)
def run(self):
t = threading.Thread(target=self.check_thread)
t.setDaemon(True)
t.start()
_logger.info('AutoReload watcher running')
#----------------------------------------------------------
# Servers: Threaded, Gevented and Prefork
#----------------------------------------------------------
class CommonServer(object):
def __init__(self, app):
# TODO Change the xmlrpc_* options to http_*
self.app = app
# config
self.interface = config['xmlrpc_interface'] or '0.0.0.0'
self.port = config['xmlrpc_port']
# runtime
self.pid = os.getpid()
def close_socket(self, sock):
""" Closes a socket instance cleanly
:param sock: the network socket to close
:type sock: socket.socket
"""
try:
sock.shutdown(socket.SHUT_RDWR)
except socket.error, e:
if e.errno == errno.EBADF:
# Werkzeug > 0.9.6 closes the socket itself (see commit
# https://github.com/mitsuhiko/werkzeug/commit/4d8ca089)
return
# On OSX, socket shutdowns both sides if any side closes it
# causing an error 57 'Socket is not connected' on shutdown
# of the other side (or something), see
# http://bugs.python.org/issue4397
# note: stdlib fixed test, not behavior
if e.errno != errno.ENOTCONN or platform.system() not in ['Darwin', 'Windows']:
raise
sock.close()
class ThreadedServer(CommonServer):
def __init__(self, app):
super(ThreadedServer, self).__init__(app)
self.main_thread_id = threading.currentThread().ident
# Variable keeping track of the number of calls to the signal handler defined
# below. This variable is monitored by ``quit_on_signals()``.
self.quit_signals_received = 0
#self.socket = None
self.httpd = None
def signal_handler(self, sig, frame):
if sig in [signal.SIGINT, signal.SIGTERM]:
# shutdown on kill -INT or -TERM
self.quit_signals_received += 1
if self.quit_signals_received > 1:
# logging.shutdown was already called at this point.
sys.stderr.write("Forced shutdown.\n")
os._exit(0)
elif sig == signal.SIGHUP:
# restart on kill -HUP
openerp.phoenix = True
self.quit_signals_received += 1
def cron_thread(self, number):
while True:
time.sleep(SLEEP_INTERVAL + number) # Steve Reich timing style
registries = openerp.modules.registry.RegistryManager.registries
_logger.debug('cron%d polling for jobs', number)
for db_name, registry in registries.iteritems():
while registry.ready:
acquired = openerp.addons.base.ir.ir_cron.ir_cron._acquire_job(db_name)
if not acquired:
break
def cron_spawn(self):
""" Start the above runner function in a daemon thread.
The thread is a typical daemon thread: it will never quit and must be
terminated when the main process exits - with no consequence (the processing
threads it spawns are not marked daemon).
"""
# Force call to strptime just before starting the cron thread
# to prevent time.strptime AttributeError within the thread.
# See: http://bugs.python.org/issue7980
datetime.datetime.strptime('2012-01-01', '%Y-%m-%d')
for i in range(openerp.tools.config['max_cron_threads']):
def target():
self.cron_thread(i)
t = threading.Thread(target=target, name="openerp.service.cron.cron%d" % i)
t.setDaemon(True)
t.start()
_logger.debug("cron%d started!" % i)
def http_thread(self):
def app(e, s):
return self.app(e, s)
self.httpd = ThreadedWSGIServerReloadable(self.interface, self.port, app)
self.httpd.serve_forever()
def http_spawn(self):
t = threading.Thread(target=self.http_thread, name="openerp.service.httpd")
t.setDaemon(True)
t.start()
_logger.info('HTTP service (werkzeug) running on %s:%s', self.interface, self.port)
def start(self, stop=False):
_logger.debug("Setting signal handlers")
if os.name == 'posix':
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
signal.signal(signal.SIGCHLD, self.signal_handler)
signal.signal(signal.SIGHUP, self.signal_handler)
signal.signal(signal.SIGQUIT, dumpstacks)
signal.signal(signal.SIGUSR1, log_ormcache_stats)
elif os.name == 'nt':
import win32api
win32api.SetConsoleCtrlHandler(lambda sig: self.signal_handler(sig, None), 1)
test_mode = config['test_enable'] or config['test_file']
if test_mode or (config['xmlrpc'] and not stop):
# some tests need the http deamon to be available...
self.http_spawn()
if not stop:
# only relevant if we are not in "--stop-after-init" mode
self.cron_spawn()
def stop(self):
""" Shutdown the WSGI server. Wait for non deamon threads.
"""
_logger.info("Initiating shutdown")
_logger.info("Hit CTRL-C again or send a second signal to force the shutdown.")
if self.httpd:
self.httpd.shutdown()
self.close_socket(self.httpd.socket)
# Manually join() all threads before calling sys.exit() to allow a second signal
# to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
# threading.Thread.join() should not mask signals (at least in python 2.5).
me = threading.currentThread()
_logger.debug('current thread: %r', me)
for thread in threading.enumerate():
_logger.debug('process %r (%r)', thread, thread.isDaemon())
if thread != me and not thread.isDaemon() and thread.ident != self.main_thread_id:
while thread.isAlive():
_logger.debug('join and sleep')
# Need a busyloop here as thread.join() masks signals
# and would prevent the forced shutdown.
thread.join(0.05)
time.sleep(0.05)
_logger.debug('--')
openerp.modules.registry.RegistryManager.delete_all()
logging.shutdown()
def run(self, preload=None, stop=False):
""" Start the http server and the cron thread then wait for a signal.
The first SIGINT or SIGTERM signal will initiate a graceful shutdown while
a second one if any will force an immediate exit.
"""
self.start(stop=stop)
rc = preload_registries(preload)
if stop:
self.stop()
return rc
# Wait for a first signal to be handled. (time.sleep will be interrupted
# by the signal handler.) The try/except is for the win32 case.
try:
while self.quit_signals_received == 0:
time.sleep(60)
except KeyboardInterrupt:
pass
self.stop()
def reload(self):
os.kill(self.pid, signal.SIGHUP)
class GeventServer(CommonServer):
def __init__(self, app):
super(GeventServer, self).__init__(app)
self.port = config['longpolling_port']
self.httpd = None
def watch_parent(self, beat=4):
import gevent
ppid = os.getppid()
while True:
if ppid != os.getppid():
pid = os.getpid()
_logger.info("LongPolling (%s) Parent changed", pid)
# suicide !!
os.kill(pid, signal.SIGTERM)
return
gevent.sleep(beat)
def start(self):
import gevent
from gevent.wsgi import WSGIServer
if os.name == 'posix':
signal.signal(signal.SIGQUIT, dumpstacks)
signal.signal(signal.SIGUSR1, log_ormcache_stats)
gevent.spawn(self.watch_parent)
self.httpd = WSGIServer((self.interface, self.port), self.app)
_logger.info('Evented Service (longpolling) running on %s:%s', self.interface, self.port)
try:
self.httpd.serve_forever()
except:
_logger.exception("Evented Service (longpolling): uncaught error during main loop")
raise
def stop(self):
import gevent
self.httpd.stop()
gevent.shutdown()
def run(self, preload, stop):
self.start()
self.stop()
class PreforkServer(CommonServer):
""" Multiprocessing inspired by (g)unicorn.
PreforkServer (aka Multicorn) currently uses accept(2) as dispatching
method between workers but we plan to replace it by a more intelligent
dispatcher to will parse the first HTTP request line.
"""
def __init__(self, app):
# config
self.address = (config['xmlrpc_interface'] or '0.0.0.0', config['xmlrpc_port'])
self.population = config['workers']
self.timeout = config['limit_time_real']
self.limit_request = config['limit_request']
# working vars
self.beat = 4
self.app = app
self.pid = os.getpid()
self.socket = None
self.workers_http = {}
self.workers_cron = {}
self.workers = {}
self.generation = 0
self.queue = []
self.long_polling_pid = None
def pipe_new(self):
pipe = os.pipe()
for fd in pipe:
# non_blocking
flags = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
# close_on_exec
flags = fcntl.fcntl(fd, fcntl.F_GETFD) | fcntl.FD_CLOEXEC
fcntl.fcntl(fd, fcntl.F_SETFD, flags)
return pipe
def pipe_ping(self, pipe):
try:
os.write(pipe[1], '.')
except IOError, e:
if e.errno not in [errno.EAGAIN, errno.EINTR]:
raise
def signal_handler(self, sig, frame):
if len(self.queue) < 5 or sig == signal.SIGCHLD:
self.queue.append(sig)
self.pipe_ping(self.pipe)
else:
_logger.warn("Dropping signal: %s", sig)
def worker_spawn(self, klass, workers_registry):
self.generation += 1
worker = klass(self)
pid = os.fork()
if pid != 0:
worker.pid = pid
self.workers[pid] = worker
workers_registry[pid] = worker
return worker
else:
worker.run()
sys.exit(0)
def long_polling_spawn(self):
nargs = stripped_sys_argv()
cmd = nargs[0]
cmd = os.path.join(os.path.dirname(cmd), "openerp-gevent")
nargs[0] = cmd
popen = subprocess.Popen([sys.executable] + nargs)
self.long_polling_pid = popen.pid
def worker_pop(self, pid):
if pid == self.long_polling_pid:
self.long_polling_pid = None
if pid in self.workers:
_logger.debug("Worker (%s) unregistered", pid)
try:
self.workers_http.pop(pid, None)
self.workers_cron.pop(pid, None)
u = self.workers.pop(pid)
u.close()
except OSError:
return
def worker_kill(self, pid, sig):
try:
os.kill(pid, sig)
except OSError, e:
if e.errno == errno.ESRCH:
self.worker_pop(pid)
def process_signals(self):
while len(self.queue):
sig = self.queue.pop(0)
if sig in [signal.SIGINT, signal.SIGTERM]:
raise KeyboardInterrupt
elif sig == signal.SIGHUP:
# restart on kill -HUP
openerp.phoenix = True
raise KeyboardInterrupt
elif sig == signal.SIGQUIT:
# dump stacks on kill -3
self.dumpstacks()
elif sig == signal.SIGUSR1:
# log ormcache stats on kill -SIGUSR1
log_ormcache_stats()
elif sig == signal.SIGTTIN:
# increase number of workers
self.population += 1
elif sig == signal.SIGTTOU:
# decrease number of workers
self.population -= 1
def process_zombie(self):
# reap dead workers
while 1:
try:
wpid, status = os.waitpid(-1, os.WNOHANG)
if not wpid:
break
if (status >> 8) == 3:
msg = "Critial worker error (%s)"
_logger.critical(msg, wpid)
raise Exception(msg % wpid)
self.worker_pop(wpid)
except OSError, e:
if e.errno == errno.ECHILD:
break
raise
def process_timeout(self):
now = time.time()
for (pid, worker) in self.workers.items():
if worker.watchdog_timeout is not None and \
(now - worker.watchdog_time) >= worker.watchdog_timeout:
_logger.error("Worker (%s) timeout", pid)
self.worker_kill(pid, signal.SIGKILL)
def process_spawn(self):
if config['xmlrpc']:
while len(self.workers_http) < self.population:
self.worker_spawn(WorkerHTTP, self.workers_http)
if not self.long_polling_pid:
self.long_polling_spawn()
while len(self.workers_cron) < config['max_cron_threads']:
self.worker_spawn(WorkerCron, self.workers_cron)
def sleep(self):
try:
# map of fd -> worker
fds = dict([(w.watchdog_pipe[0], w) for k, w in self.workers.items()])
fd_in = fds.keys() + [self.pipe[0]]
# check for ping or internal wakeups
ready = select.select(fd_in, [], [], self.beat)
# update worker watchdogs
for fd in ready[0]:
if fd in fds:
fds[fd].watchdog_time = time.time()
try:
# empty pipe
while os.read(fd, 1):
pass
except OSError, e:
if e.errno not in [errno.EAGAIN]:
raise
except select.error, e:
if e[0] not in [errno.EINTR]:
raise
def start(self):
# wakeup pipe, python doesnt throw EINTR when a syscall is interrupted
# by a signal simulating a pseudo SA_RESTART. We write to a pipe in the
# signal handler to overcome this behaviour
self.pipe = self.pipe_new()
# set signal handlers
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
signal.signal(signal.SIGHUP, self.signal_handler)
signal.signal(signal.SIGCHLD, self.signal_handler)
signal.signal(signal.SIGTTIN, self.signal_handler)
signal.signal(signal.SIGTTOU, self.signal_handler)
signal.signal(signal.SIGQUIT, dumpstacks)
signal.signal(signal.SIGUSR1, log_ormcache_stats)
# listen to socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setblocking(0)
self.socket.bind(self.address)
self.socket.listen(8 * self.population)
def stop(self, graceful=True):
if self.long_polling_pid is not None:
# FIXME make longpolling process handle SIGTERM correctly
self.worker_kill(self.long_polling_pid, signal.SIGKILL)
self.long_polling_pid = None
if graceful:
_logger.info("Stopping gracefully")
limit = time.time() + self.timeout
for pid in self.workers.keys():
self.worker_kill(pid, signal.SIGINT)
while self.workers and time.time() < limit:
try:
self.process_signals()
except KeyboardInterrupt:
_logger.info("Forced shutdown.")
break
self.process_zombie()
time.sleep(0.1)
else:
_logger.info("Stopping forcefully")
for pid in self.workers.keys():
self.worker_kill(pid, signal.SIGTERM)
self.socket.close()
def run(self, preload, stop):
self.start()
rc = preload_registries(preload)
if stop:
self.stop()
return rc
# Empty the cursor pool, we dont want them to be shared among forked workers.
openerp.sql_db.close_all()
_logger.debug("Multiprocess starting")
while 1:
try:
#_logger.debug("Multiprocess beat (%s)",time.time())
self.process_signals()
self.process_zombie()
self.process_timeout()
self.process_spawn()
self.sleep()
except KeyboardInterrupt:
_logger.debug("Multiprocess clean stop")
self.stop()
break
except Exception, e:
_logger.exception(e)
self.stop(False)
return -1
class Worker(object):
""" Workers """
def __init__(self, multi):
self.multi = multi
self.watchdog_time = time.time()
self.watchdog_pipe = multi.pipe_new()
# Can be set to None if no watchdog is desired.
self.watchdog_timeout = multi.timeout
self.ppid = os.getpid()
self.pid = None
self.alive = True
# should we rename into lifetime ?
self.request_max = multi.limit_request
self.request_count = 0
def setproctitle(self, title=""):
setproctitle('openerp: %s %s %s' % (self.__class__.__name__, self.pid, title))
def close(self):
os.close(self.watchdog_pipe[0])
os.close(self.watchdog_pipe[1])
def signal_handler(self, sig, frame):
self.alive = False
def sleep(self):
try:
select.select([self.multi.socket], [], [], self.multi.beat)
except select.error, e:
if e[0] not in [errno.EINTR]:
raise
def process_limit(self):
# If our parent changed sucide
if self.ppid != os.getppid():
_logger.info("Worker (%s) Parent changed", self.pid)
self.alive = False
# check for lifetime
if self.request_count >= self.request_max:
_logger.info("Worker (%d) max request (%s) reached.", self.pid, self.request_count)
self.alive = False
# Reset the worker if it consumes too much memory (e.g. caused by a memory leak).
rss, vms = memory_info(psutil.Process(os.getpid()))
if vms > config['limit_memory_soft']:
_logger.info('Worker (%d) virtual memory limit (%s) reached.', self.pid, vms)
self.alive = False # Commit suicide after the request.
# VMS and RLIMIT_AS are the same thing: virtual memory, a.k.a. address space
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
resource.setrlimit(resource.RLIMIT_AS, (config['limit_memory_hard'], hard))
# SIGXCPU (exceeded CPU time) signal handler will raise an exception.
r = resource.getrusage(resource.RUSAGE_SELF)
cpu_time = r.ru_utime + r.ru_stime
def time_expired(n, stack):
_logger.info('Worker (%d) CPU time limit (%s) reached.', self.pid, config['limit_time_cpu'])
# We dont suicide in such case
raise Exception('CPU time limit exceeded.')
signal.signal(signal.SIGXCPU, time_expired)
soft, hard = resource.getrlimit(resource.RLIMIT_CPU)
resource.setrlimit(resource.RLIMIT_CPU, (cpu_time + config['limit_time_cpu'], hard))
def process_work(self):
pass
def start(self):
self.pid = os.getpid()
self.setproctitle()
_logger.info("Worker %s (%s) alive", self.__class__.__name__, self.pid)
# Reseed the random number generator
random.seed()
# Prevent fd inherientence close_on_exec
flags = fcntl.fcntl(self.multi.socket, fcntl.F_GETFD) | fcntl.FD_CLOEXEC
fcntl.fcntl(self.multi.socket, fcntl.F_SETFD, flags)
# reset blocking status
self.multi.socket.setblocking(0)
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, signal.SIG_DFL)
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
def stop(self):
pass
def run(self):
try:
self.start()
while self.alive:
self.process_limit()
self.multi.pipe_ping(self.watchdog_pipe)
self.sleep()
self.process_work()
_logger.info("Worker (%s) exiting. request_count: %s, registry count: %s.",
self.pid, self.request_count,
len(openerp.modules.registry.RegistryManager.registries))
self.stop()
except Exception:
_logger.exception("Worker (%s) Exception occured, exiting..." % self.pid)
# should we use 3 to abort everything ?
sys.exit(1)
class WorkerHTTP(Worker):
""" HTTP Request workers """
def process_request(self, client, addr):
client.setblocking(1)
client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# Prevent fd inherientence close_on_exec
flags = fcntl.fcntl(client, fcntl.F_GETFD) | fcntl.FD_CLOEXEC
fcntl.fcntl(client, fcntl.F_SETFD, flags)
# do request using BaseWSGIServerNoBind monkey patched with socket
self.server.socket = client
# tolerate broken pipe when the http client closes the socket before
# receiving the full reply
try:
self.server.process_request(client, addr)
except IOError, e:
if e.errno != errno.EPIPE:
raise
self.request_count += 1
def process_work(self):
try:
client, addr = self.multi.socket.accept()
self.process_request(client, addr)
except socket.error, e:
if e[0] not in (errno.EAGAIN, errno.ECONNABORTED):
raise
def start(self):
Worker.start(self)
self.server = BaseWSGIServerNoBind(self.multi.app)
class WorkerCron(Worker):
""" Cron workers """
def __init__(self, multi):
super(WorkerCron, self).__init__(multi)
# process_work() below process a single database per call.
# The variable db_index is keeping track of the next database to
# process.
self.db_index = 0
def sleep(self):
# Really sleep once all the databases have been processed.
if self.db_index == 0:
interval = SLEEP_INTERVAL + self.pid % 10 # chorus effect
time.sleep(interval)
def _db_list(self):
if config['db_name']:
db_names = config['db_name'].split(',')
else:
db_names = openerp.service.db.exp_list(True)
return db_names
def process_work(self):
rpc_request = logging.getLogger('openerp.netsvc.rpc.request')
rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
_logger.debug("WorkerCron (%s) polling for jobs", self.pid)
db_names = self._db_list()
if len(db_names):
self.db_index = (self.db_index + 1) % len(db_names)
db_name = db_names[self.db_index]
self.setproctitle(db_name)
if rpc_request_flag:
start_time = time.time()
start_rss, start_vms = memory_info(psutil.Process(os.getpid()))
import openerp.addons.base as base
base.ir.ir_cron.ir_cron._acquire_job(db_name)
openerp.modules.registry.RegistryManager.delete(db_name)
# dont keep cursors in multi database mode
if len(db_names) > 1:
openerp.sql_db.close_db(db_name)
if rpc_request_flag:
run_time = time.time() - start_time
end_rss, end_vms = memory_info(psutil.Process(os.getpid()))
vms_diff = (end_vms - start_vms) / 1024
logline = '%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % \
(db_name, run_time, start_vms / 1024, end_vms / 1024, vms_diff)
_logger.debug("WorkerCron (%s) %s", self.pid, logline)
self.request_count += 1
if self.request_count >= self.request_max and self.request_max < len(db_names):
_logger.error("There are more dabatases to process than allowed "
"by the `limit_request` configuration variable: %s more.",
len(db_names) - self.request_max)
else:
self.db_index = 0
def start(self):
os.nice(10) # mommy always told me to be nice with others...
Worker.start(self)
self.multi.socket.close()
#----------------------------------------------------------
# start/stop public api
#----------------------------------------------------------
server = None
def load_server_wide_modules():
for m in openerp.conf.server_wide_modules:
try:
openerp.modules.module.load_openerp_module(m)
except Exception:
msg = ''
if m == 'web':
msg = """
The `web` module is provided by the addons found in the `openerp-web` project.
Maybe you forgot to add those addons in your addons_path configuration."""
_logger.exception('Failed to load server-wide module `%s`.%s', m, msg)
def _reexec(updated_modules=None):
"""reexecute openerp-server process with (nearly) the same arguments"""
if openerp.tools.osutil.is_running_as_nt_service():
subprocess.call('net stop {0} && net start {0}'.format(nt_service_name), shell=True)
exe = os.path.basename(sys.executable)
args = stripped_sys_argv()
args += ["-u", ','.join(updated_modules)]
if not args or args[0] != exe:
args.insert(0, exe)
os.execv(sys.executable, args)
def load_test_file_yml(registry, test_file):
with registry.cursor() as cr:
openerp.tools.convert_yaml_import(cr, 'base', file(test_file), 'test', {}, 'init')
if config['test_commit']:
_logger.info('test %s has been commited', test_file)
cr.commit()
else:
_logger.info('test %s has been rollbacked', test_file)
cr.rollback()
def load_test_file_py(registry, test_file):
# Locate python module based on its filename and run the tests
test_path, _ = os.path.splitext(os.path.abspath(test_file))
for mod_name, mod_mod in sys.modules.items():
if mod_mod:
mod_path, _ = os.path.splitext(getattr(mod_mod, '__file__', ''))
if test_path == mod_path:
suite = unittest2.TestSuite()
for t in unittest2.TestLoader().loadTestsFromModule(mod_mod):
suite.addTest(t)
_logger.log(logging.INFO, 'running tests %s.', mod_mod.__name__)
stream = openerp.modules.module.TestStream()
result = unittest2.TextTestRunner(verbosity=2, stream=stream).run(suite)
success = result.wasSuccessful()
if hasattr(registry._assertion_report,'report_result'):
registry._assertion_report.report_result(success)
if not success:
_logger.error('%s: at least one error occurred in a test', test_file)
def preload_registries(dbnames):
""" Preload a registries, possibly run a test file."""
# TODO: move all config checks to args dont check tools.config here
config = openerp.tools.config
test_file = config['test_file']
dbnames = dbnames or []
rc = 0
for dbname in dbnames:
try:
update_module = config['init'] or config['update']
registry = RegistryManager.new(dbname, update_module=update_module)
# run test_file if provided
if test_file:
_logger.info('loading test file %s', test_file)
with openerp.api.Environment.manage():
if test_file.endswith('yml'):
load_test_file_yml(registry, test_file)
elif test_file.endswith('py'):
load_test_file_py(registry, test_file)
if registry._assertion_report.failures:
rc += 1
except Exception:
_logger.critical('Failed to initialize database `%s`.', dbname, exc_info=True)
return -1
return rc
def start(preload=None, stop=False):
""" Start the openerp http server and cron processor.
"""
global server
load_server_wide_modules()
if openerp.evented:
server = GeventServer(openerp.service.wsgi_server.application)
elif config['workers']:
server = PreforkServer(openerp.service.wsgi_server.application)
else:
server = ThreadedServer(openerp.service.wsgi_server.application)
if config['auto_reload']:
autoreload = AutoReload(server)
autoreload.run()
rc = server.run(preload, stop)
# like the legend of the phoenix, all ends with beginnings
if getattr(openerp, 'phoenix', False):
modules = []
if config['auto_reload']:
modules = autoreload.modules.keys()
_reexec(modules)
return rc if rc else 0
def restart():
""" Restart the server
"""
if os.name == 'nt':
# run in a thread to let the current thread return response to the caller.
threading.Thread(target=_reexec).start()
else:
os.kill(server.pid, signal.SIGHUP)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
colehertz/Stripe-Tester | venv/lib/python3.5/site-packages/pip-7.1.0-py3.5.egg/pip/_vendor/requests/packages/chardet/charsetgroupprober.py | 2929 | 3791 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# 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 St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from . import constants
import sys
from .charsetprober import CharSetProber
class CharSetGroupProber(CharSetProber):
def __init__(self):
CharSetProber.__init__(self)
self._mActiveNum = 0
self._mProbers = []
self._mBestGuessProber = None
def reset(self):
CharSetProber.reset(self)
self._mActiveNum = 0
for prober in self._mProbers:
if prober:
prober.reset()
prober.active = True
self._mActiveNum += 1
self._mBestGuessProber = None
def get_charset_name(self):
if not self._mBestGuessProber:
self.get_confidence()
if not self._mBestGuessProber:
return None
# self._mBestGuessProber = self._mProbers[0]
return self._mBestGuessProber.get_charset_name()
def feed(self, aBuf):
for prober in self._mProbers:
if not prober:
continue
if not prober.active:
continue
st = prober.feed(aBuf)
if not st:
continue
if st == constants.eFoundIt:
self._mBestGuessProber = prober
return self.get_state()
elif st == constants.eNotMe:
prober.active = False
self._mActiveNum -= 1
if self._mActiveNum <= 0:
self._mState = constants.eNotMe
return self.get_state()
return self.get_state()
def get_confidence(self):
st = self.get_state()
if st == constants.eFoundIt:
return 0.99
elif st == constants.eNotMe:
return 0.01
bestConf = 0.0
self._mBestGuessProber = None
for prober in self._mProbers:
if not prober:
continue
if not prober.active:
if constants._debug:
sys.stderr.write(prober.get_charset_name()
+ ' not active\n')
continue
cf = prober.get_confidence()
if constants._debug:
sys.stderr.write('%s confidence = %s\n' %
(prober.get_charset_name(), cf))
if bestConf < cf:
bestConf = cf
self._mBestGuessProber = prober
if not self._mBestGuessProber:
return 0.0
return bestConf
# else:
# self._mBestGuessProber = self._mProbers[0]
# return self._mBestGuessProber.get_confidence()
| mit |
srm912/servo | tests/wpt/css-tests/css-text-decor-3_dev/html/reference/support/generate-text-emphasis-position-property-tests.py | 841 | 3343 | #!/usr/bin/env python
# - * - coding: UTF-8 - * -
"""
This script generates tests text-emphasis-position-property-001 ~ 006
which cover all possible values of text-emphasis-position property with
all combination of three main writing modes and two orientations. Only
test files are generated by this script. It also outputs a list of all
tests it generated in the format of Mozilla reftest.list to the stdout.
"""
from __future__ import unicode_literals
import itertools
TEST_FILE = 'text-emphasis-position-property-{:03}{}.html'
REF_FILE = 'text-emphasis-position-property-{:03}-ref.html'
TEST_TEMPLATE = '''<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Test: text-emphasis-position: {value}, {title}</title>
<link rel="author" title="Xidorn Quan" href="https://www.upsuper.org">
<link rel="author" title="Mozilla" href="https://www.mozilla.org">
<link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#text-emphasis-position-property">
<meta name="assert" content="'text-emphasis-position: {value}' with 'writing-mode: {wm}' puts emphasis marks {position} the text.">
<link rel="match" href="text-emphasis-position-property-{index:03}-ref.html">
<p>Pass if the emphasis marks are {position} the text below:</p>
<div style="line-height: 5; text-emphasis: circle; writing-mode: {wm}; text-orientation: {orient}; text-emphasis-position: {value}">試験テスト</div>
'''
SUFFIXES = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
WRITING_MODES = ["horizontal-tb", "vertical-rl", "vertical-lr"]
POSITION_HORIZONTAL = ["over", "under"]
POSITION_VERTICAL = ["right", "left"]
REF_MAP_MIXED = { "over": 1, "under": 2, "right": 3, "left": 4 }
REF_MAP_SIDEWAYS = { "right": 5, "left": 6 }
POSITION_TEXT = { "over": "over", "under": "under",
"right": "to the right of", "left": "to the left of" }
suffixes = [iter(SUFFIXES) for i in range(6)]
reftest_items = []
def write_file(filename, content):
with open(filename, 'wb') as f:
f.write(content.encode('UTF-8'))
def write_test_file(idx, suffix, wm, orient, value, position):
filename = TEST_FILE.format(idx, suffix)
write_file(filename, TEST_TEMPLATE.format(
value=value, wm=wm, orient=orient, index=idx, position=position,
title=(wm if orient == "mixed" else "{}, {}".format(wm, orient))))
reftest_items.append("== {} {}".format(filename, REF_FILE.format(idx)))
def write_test_files(wm, orient, pos1, pos2):
idx = (REF_MAP_MIXED if orient == "mixed" else REF_MAP_SIDEWAYS)[pos1]
position = POSITION_TEXT[pos1]
suffix = suffixes[idx - 1]
write_test_file(idx, next(suffix), wm, orient, pos1 + " " + pos2, position)
write_test_file(idx, next(suffix), wm, orient, pos2 + " " + pos1, position)
for wm in WRITING_MODES:
if wm == "horizontal-tb":
effective_pos = POSITION_HORIZONTAL
ineffective_pos = POSITION_VERTICAL
else:
effective_pos = POSITION_VERTICAL
ineffective_pos = POSITION_HORIZONTAL
for pos1, pos2 in itertools.product(effective_pos, ineffective_pos):
write_test_files(wm, "mixed", pos1, pos2)
if wm != "horizontal-tb":
write_test_files(wm, "sideways", pos1, pos2)
print("# START tests from {}".format(__file__))
reftest_items.sort()
for item in reftest_items:
print(item)
print("# END tests from {}".format(__file__))
| mpl-2.0 |
junhuac/MQUIC | src/build/android/pylib/base/base_setup.py | 12 | 2587 | # Copyright (c) 2014 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.
"""Base script for doing test setup."""
import logging
import os
from pylib import constants
from pylib import valgrind_tools
from pylib.constants import host_paths
from pylib.utils import isolator
def GenerateDepsDirUsingIsolate(suite_name, isolate_file_path,
isolate_file_paths, deps_exclusion_list):
"""Generate the dependency dir for the test suite using isolate.
Args:
suite_name: Name of the test suite (e.g. base_unittests).
isolate_file_path: .isolate file path to use. If there is a default .isolate
file path for the suite_name, this will override it.
isolate_file_paths: Dictionary with the default .isolate file paths for
the test suites.
deps_exclusion_list: A list of files that are listed as dependencies in the
.isolate files but should not be pushed to the device.
Returns:
The Isolator instance used to remap the dependencies, or None.
"""
if isolate_file_path:
if os.path.isabs(isolate_file_path):
isolate_abs_path = isolate_file_path
else:
isolate_abs_path = os.path.join(host_paths.DIR_SOURCE_ROOT,
isolate_file_path)
else:
isolate_rel_path = isolate_file_paths.get(suite_name)
if not isolate_rel_path:
logging.info('Did not find an isolate file for the test suite.')
return
isolate_abs_path = os.path.join(host_paths.DIR_SOURCE_ROOT,
isolate_rel_path)
isolated_abs_path = os.path.join(
constants.GetOutDirectory(), '%s.isolated' % suite_name)
assert os.path.exists(isolate_abs_path), 'Cannot find %s' % isolate_abs_path
i = isolator.Isolator()
i.Clear()
i.Remap(isolate_abs_path, isolated_abs_path)
# We're relying on the fact that timestamps are preserved
# by the remap command (hardlinked). Otherwise, all the data
# will be pushed to the device once we move to using time diff
# instead of md5sum. Perform a sanity check here.
i.VerifyHardlinks()
i.PurgeExcluded(deps_exclusion_list)
i.MoveOutputDeps()
return i
def PushDataDeps(device, host_dir, device_dir, test_options):
valgrind_tools.PushFilesForTool(test_options.tool, device)
if os.path.exists(host_dir):
device.PushChangedFiles([(host_dir, device_dir)],
delete_device_stale=test_options.delete_stale_data)
| mit |
NetApp/manila | manila/tests/conf_fixture.py | 1 | 2619 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
import os
from oslo_policy import opts
from manila.common import config
CONF = config.CONF
def set_defaults(conf):
_safe_set_of_opts(conf, 'verbose', True)
_safe_set_of_opts(conf, 'state_path', os.path.abspath(
os.path.join(os.path.dirname(__file__),
'..',
'..')))
_safe_set_of_opts(conf, 'connection', "sqlite://", group='database')
_safe_set_of_opts(conf, 'sqlite_synchronous', False)
_POLICY_PATH = os.path.abspath(os.path.join(CONF.state_path,
'manila/tests/policy.json'))
opts.set_defaults(conf, policy_file=_POLICY_PATH)
_safe_set_of_opts(conf, 'share_export_ip', '0.0.0.0')
_safe_set_of_opts(conf, 'service_instance_user', 'fake_user')
_API_PASTE_PATH = os.path.abspath(os.path.join(CONF.state_path,
'etc/manila/api-paste.ini'))
_safe_set_of_opts(conf, 'api_paste_config', _API_PASTE_PATH)
_safe_set_of_opts(conf, 'share_driver',
'manila.tests.fake_driver.FakeShareDriver')
_safe_set_of_opts(conf, 'auth_strategy', 'noauth')
_safe_set_of_opts(conf, 'zfs_share_export_ip', '1.1.1.1')
_safe_set_of_opts(conf, 'zfs_service_ip', '2.2.2.2')
_safe_set_of_opts(conf, 'zfs_zpool_list', ['foo', 'bar'])
_safe_set_of_opts(conf, 'zfs_share_helpers', 'NFS=foo.bar.Helper')
_safe_set_of_opts(conf, 'zfs_replica_snapshot_prefix', 'foo_prefix_')
_safe_set_of_opts(conf, 'hitachi_hsp_host', '172.24.47.190')
_safe_set_of_opts(conf, 'hitachi_hsp_username', 'hsp_user')
_safe_set_of_opts(conf, 'hitachi_hsp_password', 'hsp_password')
def _safe_set_of_opts(conf, *args, **kwargs):
try:
conf.set_default(*args, **kwargs)
except config.cfg.NoSuchOptError:
# Assumed that opt is not imported and not used
pass
| apache-2.0 |
brockwhittaker/zulip | zerver/views/home.py | 2 | 11798 | from typing import Any, List, Dict, Optional, Text
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse, HttpRequest
from django.shortcuts import redirect, render
from django.utils import translation
from django.utils.cache import patch_cache_control
from six.moves import zip_longest, zip, range
from zerver.decorator import zulip_login_required, process_client
from zerver.forms import ToSForm
from zerver.lib.realm_icon import realm_icon_url
from zerver.models import Message, UserProfile, Stream, Subscription, Huddle, \
Recipient, Realm, UserMessage, DefaultStream, RealmEmoji, RealmDomain, \
RealmFilter, PreregistrationUser, UserActivity, \
UserPresence, get_stream_recipient, name_changes_disabled, email_to_username, \
get_realm_domains
from zerver.lib.events import do_events_register
from zerver.lib.actions import update_user_presence, do_change_tos_version, \
do_update_pointer, realm_user_count
from zerver.lib.avatar import avatar_url
from zerver.lib.i18n import get_language_list, get_language_name, \
get_language_list_for_templates
from zerver.lib.push_notifications import num_push_devices_for_user
from zerver.lib.streams import access_stream_by_name
from zerver.lib.subdomains import get_subdomain
from zerver.lib.utils import statsd
import calendar
import datetime
import logging
import os
import re
import simplejson
import time
@zulip_login_required
def accounts_accept_terms(request):
# type: (HttpRequest) -> HttpResponse
if request.method == "POST":
form = ToSForm(request.POST)
if form.is_valid():
do_change_tos_version(request.user, settings.TOS_VERSION)
return redirect(home)
else:
form = ToSForm()
email = request.user.email
special_message_template = None
if request.user.tos_version is None and settings.FIRST_TIME_TOS_TEMPLATE is not None:
special_message_template = 'zerver/' + settings.FIRST_TIME_TOS_TEMPLATE
return render(
request,
'zerver/accounts_accept_terms.html',
context={'form': form,
'email': email,
'special_message_template': special_message_template},
)
def sent_time_in_epoch_seconds(user_message):
# type: (Optional[UserMessage]) -> Optional[float]
if user_message is None:
return None
# We have USE_TZ = True, so our datetime objects are timezone-aware.
# Return the epoch seconds in UTC.
return calendar.timegm(user_message.message.pub_date.utctimetuple())
def home(request):
# type: (HttpRequest) -> HttpResponse
if settings.DEVELOPMENT and os.path.exists('var/handlebars-templates/compile.error'):
response = render(request, 'zerver/handlebars_compilation_failed.html')
response.status_code = 500
return response
if not settings.ROOT_DOMAIN_LANDING_PAGE:
return home_real(request)
# If settings.ROOT_DOMAIN_LANDING_PAGE, sends the user the landing
# page, not the login form, on the root domain
subdomain = get_subdomain(request)
if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
return home_real(request)
return render(request, 'zerver/hello.html')
@zulip_login_required
def home_real(request):
# type: (HttpRequest) -> HttpResponse
# We need to modify the session object every two weeks or it will expire.
# This line makes reloading the page a sufficient action to keep the
# session alive.
request.session.modified = True
user_profile = request.user
# If a user hasn't signed the current Terms of Service, send them there
if settings.TERMS_OF_SERVICE is not None and settings.TOS_VERSION is not None and \
int(settings.TOS_VERSION.split('.')[0]) > user_profile.major_tos_version():
return accounts_accept_terms(request)
narrow = [] # type: List[List[Text]]
narrow_stream = None
narrow_topic = request.GET.get("topic")
if request.GET.get("stream"):
try:
narrow_stream_name = request.GET.get("stream")
(narrow_stream, ignored_rec, ignored_sub) = access_stream_by_name(
user_profile, narrow_stream_name)
narrow = [["stream", narrow_stream.name]]
except Exception:
logging.exception("Narrow parsing")
if narrow_stream is not None and narrow_topic is not None:
narrow.append(["topic", narrow_topic])
register_ret = do_events_register(user_profile, request.client,
apply_markdown=True, narrow=narrow)
user_has_messages = (register_ret['max_message_id'] != -1)
# Reset our don't-spam-users-with-email counter since the
# user has since logged in
if user_profile.last_reminder is not None:
user_profile.last_reminder = None
user_profile.save(update_fields=["last_reminder"])
# Brand new users get narrowed to PM with welcome-bot
needs_tutorial = user_profile.tutorial_status == UserProfile.TUTORIAL_WAITING
first_in_realm = realm_user_count(user_profile.realm) == 1
# If you are the only person in the realm and you didn't invite
# anyone, we'll continue to encourage you to do so on the frontend.
prompt_for_invites = first_in_realm and \
not PreregistrationUser.objects.filter(referred_by=user_profile).count()
if user_profile.pointer == -1 and user_has_messages:
# Put the new user's pointer at the bottom
#
# This improves performance, because we limit backfilling of messages
# before the pointer. It's also likely that someone joining an
# organization is interested in recent messages more than the very
# first messages on the system.
register_ret['pointer'] = register_ret['max_message_id']
user_profile.last_pointer_updater = request.session.session_key
if user_profile.pointer == -1:
latest_read = None
else:
try:
latest_read = UserMessage.objects.get(user_profile=user_profile,
message__id=user_profile.pointer)
except UserMessage.DoesNotExist:
# Don't completely fail if your saved pointer ID is invalid
logging.warning("%s has invalid pointer %s" % (user_profile.email, user_profile.pointer))
latest_read = None
# Set default language and make it persist
default_language = register_ret['default_language']
url_lang = '/{}'.format(request.LANGUAGE_CODE)
if not request.path.startswith(url_lang):
translation.activate(default_language)
request.session[translation.LANGUAGE_SESSION_KEY] = translation.get_language()
# Pass parameters to the client-side JavaScript code.
# These end up in a global JavaScript Object named 'page_params'.
page_params = dict(
# Server settings.
development_environment = settings.DEVELOPMENT,
debug_mode = settings.DEBUG,
test_suite = settings.TEST_SUITE,
poll_timeout = settings.POLL_TIMEOUT,
login_page = settings.HOME_NOT_LOGGED_IN,
root_domain_uri = settings.ROOT_DOMAIN_URI,
maxfilesize = settings.MAX_FILE_UPLOAD_SIZE,
max_avatar_file_size = settings.MAX_AVATAR_FILE_SIZE,
server_generation = settings.SERVER_GENERATION,
use_websockets = settings.USE_WEBSOCKETS,
save_stacktraces = settings.SAVE_FRONTEND_STACKTRACES,
server_inline_image_preview = settings.INLINE_IMAGE_PREVIEW,
server_inline_url_embed_preview = settings.INLINE_URL_EMBED_PREVIEW,
password_min_length = settings.PASSWORD_MIN_LENGTH,
password_min_guesses = settings.PASSWORD_MIN_GUESSES,
# Misc. extra data.
have_initial_messages = user_has_messages,
initial_servertime = time.time(), # Used for calculating relative presence age
default_language_name = get_language_name(register_ret['default_language']),
language_list_dbl_col = get_language_list_for_templates(register_ret['default_language']),
language_list = get_language_list(),
needs_tutorial = needs_tutorial,
first_in_realm = first_in_realm,
prompt_for_invites = prompt_for_invites,
furthest_read_time = sent_time_in_epoch_seconds(latest_read),
has_mobile_devices = num_push_devices_for_user(user_profile) > 0,
)
undesired_register_ret_fields = [
'streams',
]
for field_name in set(register_ret.keys()) - set(undesired_register_ret_fields):
page_params[field_name] = register_ret[field_name]
if narrow_stream is not None:
# In narrow_stream context, initial pointer is just latest message
recipient = get_stream_recipient(narrow_stream.id)
try:
initial_pointer = Message.objects.filter(recipient=recipient).order_by('id').reverse()[0].id
except IndexError:
initial_pointer = -1
page_params["narrow_stream"] = narrow_stream.name
if narrow_topic is not None:
page_params["narrow_topic"] = narrow_topic
page_params["narrow"] = [dict(operator=term[0], operand=term[1]) for term in narrow]
page_params["max_message_id"] = initial_pointer
page_params["pointer"] = initial_pointer
page_params["have_initial_messages"] = (initial_pointer != -1)
page_params["enable_desktop_notifications"] = False
statsd.incr('views.home')
show_invites = True
# Some realms only allow admins to invite users
if user_profile.realm.invite_by_admins_only and not user_profile.is_realm_admin:
show_invites = False
request._log_data['extra'] = "[%s]" % (register_ret["queue_id"],)
response = render(request, 'zerver/index.html',
context={'user_profile': user_profile,
'page_params': simplejson.encoder.JSONEncoderForHTML().encode(page_params),
'nofontface': is_buggy_ua(request.META.get("HTTP_USER_AGENT", "Unspecified")),
'avatar_url': avatar_url(user_profile),
'show_debug':
settings.DEBUG and ('show_debug' in request.GET),
'pipeline': settings.PIPELINE_ENABLED,
'show_invites': show_invites,
'is_admin': user_profile.is_realm_admin,
'show_webathena': user_profile.realm.webathena_enabled,
'enable_feedback': settings.ENABLE_FEEDBACK,
'embedded': narrow_stream is not None,
},)
patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
return response
@zulip_login_required
def desktop_home(request):
# type: (HttpRequest) -> HttpResponse
return HttpResponseRedirect(reverse('zerver.views.home.home'))
def apps_view(request, _):
# type: (HttpRequest, Text) -> HttpResponse
if settings.ZILENCER_ENABLED:
return render(request, 'zerver/apps.html')
return HttpResponseRedirect('https://zulipchat.com/apps/', status=301)
def is_buggy_ua(agent):
# type: (str) -> bool
"""Discrimiate CSS served to clients based on User Agent
Due to QTBUG-3467, @font-face is not supported in QtWebKit.
This may get fixed in the future, but for right now we can
just serve the more conservative CSS to all our desktop apps.
"""
return ("Zulip Desktop/" in agent or "ZulipDesktop/" in agent) and \
"Mac" not in agent
| apache-2.0 |
silentbob73/kitsune | kitsune/journal/models.py | 19 | 1307 | from datetime import datetime
from django.db import models
RECORD_INFO = u'info'
RECORD_ERROR = u'error'
class RecordManager(models.Manager):
def log(self, level, src, msg, **kwargs):
msg = msg.format(**kwargs).encode('utf-8')
return Record.objects.create(level=RECORD_INFO, src=src, msg=msg)
def info(self, src, msg, **kwargs):
self.log(RECORD_INFO, src, msg, **kwargs)
def error(self, src, msg, **kwargs):
self.log(RECORD_ERROR, src, msg, **kwargs)
class Record(models.Model):
"""Defines an audit record for something that happened in translations"""
TYPE_CHOICES = [
(RECORD_INFO, RECORD_INFO),
(RECORD_ERROR, RECORD_ERROR),
]
# The log level of this message (e.g. "info", "error", ...)
level = models.CharField(choices=TYPE_CHOICES, max_length=20)
# What component was running (e.g. "sumo.ratelimit", "questions.aaq")
src = models.CharField(max_length=50)
# The message details. (e.g. "user bob hit the ratelimit for questions.ask")
msg = models.CharField(max_length=255)
# When this log entry was created
created = models.DateTimeField(default=datetime.now)
objects = RecordManager()
def __unicode__(self):
return u'<Record {self.src} {self.msg}>'.format(self=self)
| bsd-3-clause |
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/PIL/GbrImagePlugin.py | 4 | 2754 | #
# The Python Imaging Library
#
# load a GIMP brush file
#
# History:
# 96-03-14 fl Created
# 16-01-08 es Version 2
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1996.
# Copyright (c) Eric Soroos 2016.
#
# See the README file for information on usage and redistribution.
#
#
# See https://github.com/GNOME/gimp/blob/master/devel-docs/gbr.txt for
# format documentation.
#
# This code Interprets version 1 and 2 .gbr files.
# Version 1 files are obsolete, and should not be used for new
# brushes.
# Version 2 files are saved by GIMP v2.8 (at least)
# Version 3 files have a format specifier of 18 for 16bit floats in
# the color depth field. This is currently unsupported by Pillow.
from . import Image, ImageFile
from ._binary import i32be as i32
def _accept(prefix):
return len(prefix) >= 8 and \
i32(prefix[:4]) >= 20 and i32(prefix[4:8]) in (1, 2)
##
# Image plugin for the GIMP brush format.
class GbrImageFile(ImageFile.ImageFile):
format = "GBR"
format_description = "GIMP brush file"
def _open(self):
header_size = i32(self.fp.read(4))
version = i32(self.fp.read(4))
if header_size < 20:
raise SyntaxError("not a GIMP brush")
if version not in (1, 2):
raise SyntaxError("Unsupported GIMP brush version: %s" % version)
width = i32(self.fp.read(4))
height = i32(self.fp.read(4))
color_depth = i32(self.fp.read(4))
if width <= 0 or height <= 0:
raise SyntaxError("not a GIMP brush")
if color_depth not in (1, 4):
raise SyntaxError(
"Unsupported GIMP brush color depth: %s" % color_depth)
if version == 1:
comment_length = header_size-20
else:
comment_length = header_size-28
magic_number = self.fp.read(4)
if magic_number != b'GIMP':
raise SyntaxError("not a GIMP brush, bad magic number")
self.info['spacing'] = i32(self.fp.read(4))
comment = self.fp.read(comment_length)[:-1]
if color_depth == 1:
self.mode = "L"
else:
self.mode = 'RGBA'
self._size = width, height
self.info["comment"] = comment
# Image might not be small
Image._decompression_bomb_check(self.size)
# Data is an uncompressed block of w * h * bytes/pixel
self._data_size = width * height * color_depth
def load(self):
self.im = Image.core.new(self.mode, self.size)
self.frombytes(self.fp.read(self._data_size))
#
# registry
Image.register_open(GbrImageFile.format, GbrImageFile, _accept)
Image.register_extension(GbrImageFile.format, ".gbr")
| gpl-3.0 |
jendap/tensorflow | tensorflow/python/ops/ragged/ragged_concat_ops.py | 8 | 11810 | # Copyright 2018 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.
# ==============================================================================
"""Concat and stack operations for RaggedTensors."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops.ragged import ragged_array_ops
from tensorflow.python.ops.ragged import ragged_conversion_ops
from tensorflow.python.ops.ragged import ragged_gather_ops
from tensorflow.python.ops.ragged import ragged_tensor
from tensorflow.python.ops.ragged import ragged_util
def concat(values, axis, name=None):
"""Concatenates potentially ragged tensors along one dimension.
Given a list of tensors with the same rank `K` (`K >= axis`), returns a
rank-`K` `RaggedTensor` `result` such that `result[i0...iaxis]` is the
concatenation of `[rt[i0...iaxis] for rt in values]`.
Args:
values: A list of potentially ragged tensors. May not be empty. All
`values` must have the same rank and the same dtype; but unlike
`tf.concat`, they can have arbitrary shapes.
axis: A python integer, indicating the dimension along which to concatenate.
(Note: Unlike `tf.concat`, the `axis` parameter must be statically known.)
Negative values are supported only if the rank of at least one
`values` value is statically known.
name: A name prefix for the returned tensor (optional).
Returns:
A `RaggedTensor` with rank `K`.
`result.ragged_rank=max(axis, max(rt.ragged_rank for rt in values]))`.
Raises:
ValueError: If `values` is empty, if `axis` is out of bounds or if
the input tensors have different ranks.
#### Example:
```python
>>> t1 = tf.ragged.constant([[1, 2], [3, 4, 5]])
>>> t2 = tf.ragged.constant([[6], [7, 8, 9]])
>>> ragged.concat([t1, t2], axis=0)
[[1, 2], [3, 4, 5], [6], [7, 8, 9]]
>>> ragged.concat([t1, t2], axis=1)
[[1, 2, 6], [3, 4, 5, 7, 8, 9]]
```
"""
if not isinstance(values, (list, tuple)):
values = [values]
with ops.name_scope(name, 'RaggedConcat', values):
return _ragged_stack_concat_helper(values, axis, stack_values=False)
def stack(values, axis=0, name=None):
"""Stacks potentially ragged tensors along one dimension.
Given a list of tensors with the same rank `K` (`K >= axis`), returns a
rank-`K+1` `RaggedTensor` `result` such that `result[i0...iaxis]` is the
list `[rt[i0...iaxis] for rt in values]`.
Args:
values: A list of potentially ragged tensors. May not be empty. All
`values` must have the same rank and the same dtype; but unlike
`tf.concat`, they can have arbitrary shapes.
axis: A python integer, indicating the dimension along which to stack.
(Note: Unlike `tf.stack`, the `axis` parameter must be statically known.)
Negative values are supported only if the rank of at least one
`values` value is statically known.
name: A name prefix for the returned tensor (optional).
Returns:
A `RaggedTensor` with rank `K+1`.
`result.ragged_rank=max(axis, max(rt.ragged_rank for rt in values]))`.
Raises:
ValueError: If `values` is empty, if `axis` is out of bounds or if
the input tensors have different ranks.
#### Example:
```python
>>> t1 = tf.ragged.constant([[1, 2], [3, 4, 5]])
>>> t2 = tf.ragged.constant([[6], [7, 8, 9]])
>>> ragged.stack([t1, t2], axis=0)
[[[1, 2], [3, 4, 5]], [[6], [7, 9, 0]]]
>>> ragged.stack([t1, t2], axis=1)
[[[1, 2], [6]], [[3, 4, 5], [7, 8, 9]]]
```
"""
if not isinstance(values, (list, tuple)):
values = [values]
with ops.name_scope(name, 'RaggedConcat', values):
return _ragged_stack_concat_helper(values, axis, stack_values=True)
def _ragged_stack_concat_helper(rt_inputs, axis, stack_values):
"""Helper function to concatenate or stack ragged tensors.
Args:
rt_inputs: A list of RaggedTensors or Tensors to combine.
axis: The axis along which to concatenate or stack.
stack_values: A boolean -- if true, then stack values; otherwise,
concatenate them.
Returns:
A RaggedTensor.
Raises:
ValueError: If rt_inputs is empty, or if axis is out of range.
"""
# Validate parameters.
if not rt_inputs:
raise ValueError('rt_inputs may not be empty.')
# Convert input tensors.
rt_inputs = [
ragged_tensor.convert_to_tensor_or_ragged_tensor(
rt_input, name='rt_input') for rt_input in rt_inputs
]
# Special case: if there's only one input, then return it as-is.
if len(rt_inputs) == 1:
if stack_values:
return ragged_array_ops.expand_dims(rt_inputs[0], axis=axis)
else:
return rt_inputs[0]
# Check the rank (number of dimensions) of the input tensors.
ndims = None
for rt in rt_inputs:
if ndims is None:
ndims = rt.shape.ndims
else:
rt.shape.assert_has_rank(ndims)
out_ndims = ndims if (ndims is None or not stack_values) else ndims + 1
axis = ragged_util.get_positive_axis(axis, out_ndims)
# If all the inputs are Tensors, and we're combining the final dimension,
# then we can delegate to the tf.stack/tf.concat operation, and return a
# Tensor.
if all(not ragged_tensor.is_ragged(rt) for rt in rt_inputs):
if ndims is not None and (axis == out_ndims - 1 or axis == ndims - 1):
if stack_values:
return array_ops.stack(rt_inputs, axis)
else:
return array_ops.concat(rt_inputs, axis)
# Convert any Tensor inputs to RaggedTensors. This makes it
# possible to concatenate Tensors and RaggedTensors together.
for i in range(len(rt_inputs)):
if not ragged_tensor.is_ragged(rt_inputs[i]):
rt_inputs[i] = ragged_conversion_ops.from_tensor(
rt_inputs[i], ragged_rank=1)
# Convert the input tensors to all have the same ragged_rank.
ragged_rank = max(max(rt.ragged_rank for rt in rt_inputs), 1)
rt_inputs = [_increase_ragged_rank_to(rt, ragged_rank) for rt in rt_inputs]
if axis == 0:
return _ragged_stack_concat_axis_0(rt_inputs, stack_values)
elif axis == 1:
return _ragged_stack_concat_axis_1(rt_inputs, stack_values)
else: # axis > 1: recurse.
values = [rt.values for rt in rt_inputs]
splits = [[rt_input.row_splits] for rt_input in rt_inputs]
with ops.control_dependencies(ragged_util.assert_splits_match(splits)):
return ragged_tensor.RaggedTensor.from_row_splits(
_ragged_stack_concat_helper(values, axis - 1, stack_values),
splits[0][0])
def _ragged_stack_concat_axis_0(rt_inputs, stack_values):
"""Helper function to concatenate or stack ragged tensors along axis 0.
Args:
rt_inputs: A list of RaggedTensors, all with the same rank and ragged_rank.
stack_values: Boolean. If true, then stack values; otherwise, concatenate
them.
Returns:
A RaggedTensor.
"""
# Concatenate the inner values together.
flat_values = [rt.flat_values for rt in rt_inputs]
concatenated_flat_values = array_ops.concat(flat_values, axis=0)
# Concatenate the splits together for each ragged dimension (adjusting
# split offsets as necessary).
nested_splits = [rt.nested_row_splits for rt in rt_inputs]
ragged_rank = rt_inputs[0].ragged_rank
concatenated_nested_splits = [
_concat_ragged_splits([ns[dim]
for ns in nested_splits])
for dim in range(ragged_rank)
]
# If we are performing a stack operation, then add another splits.
if stack_values:
stack_lengths = array_ops.stack([rt.nrows() for rt in rt_inputs])
stack_splits = ragged_util.lengths_to_splits(stack_lengths)
concatenated_nested_splits.insert(0, stack_splits)
return ragged_tensor.RaggedTensor.from_nested_row_splits(
concatenated_flat_values, concatenated_nested_splits)
def _ragged_stack_concat_axis_1(rt_inputs, stack_values):
"""Helper function to concatenate or stack ragged tensors along axis 1.
Args:
rt_inputs: A list of RaggedTensors, all with the same rank and ragged_rank.
stack_values: Boolean. If true, then stack values; otherwise, concatenate
them.
Returns:
A RaggedTensor.
"""
num_inputs = len(rt_inputs)
rt_nrows = rt_inputs[0].nrows()
nrows_msg = 'Input tensors have incompatible shapes.'
nrows_checks = [
check_ops.assert_equal(rt.nrows(), rt_nrows, message=nrows_msg)
for rt in rt_inputs[1:]
]
with ops.control_dependencies(nrows_checks):
# Concatentate the inputs together to put them in a single ragged tensor.
concatenated_rt = _ragged_stack_concat_axis_0(rt_inputs, stack_values=False)
# Use ragged.gather to permute the rows of concatenated_rt. In particular,
# permuted_rt = [rt_inputs[0][0], ..., rt_inputs[N][0],
# rt_inputs[0][1], ..., rt_inputs[N][1],
# ...,
# rt_inputs[0][M], ..., rt_input[N][M]]
# where `N=num_inputs-1` and `M=rt_nrows-1`.
row_indices = math_ops.range(rt_nrows * num_inputs)
row_index_matrix = array_ops.reshape(row_indices, [num_inputs, -1])
transposed_row_index_matrix = array_ops.transpose(row_index_matrix)
row_permutation = array_ops.reshape(transposed_row_index_matrix, [-1])
permuted_rt = ragged_gather_ops.gather(concatenated_rt, row_permutation)
if stack_values:
# Add a new splits tensor to group together the values.
stack_splits = math_ops.range(0, rt_nrows * num_inputs + 1, num_inputs)
_copy_row_shape(rt_inputs, stack_splits)
return ragged_tensor.RaggedTensor.from_row_splits(permuted_rt,
stack_splits)
else:
# Merge together adjacent rows by dropping the row-split indices that
# separate them.
concat_splits = permuted_rt.row_splits[::num_inputs]
_copy_row_shape(rt_inputs, concat_splits)
return ragged_tensor.RaggedTensor.from_row_splits(permuted_rt.values,
concat_splits)
def _copy_row_shape(rt_inputs, splits):
"""Sets splits.shape to [rt[shape[0]+1] for each rt in rt_inputs."""
for rt in rt_inputs:
if rt.shape[0] is not None:
splits.set_shape(tensor_shape.TensorShape(rt.shape[0] + 1))
def _increase_ragged_rank_to(rt_input, ragged_rank):
"""Adds ragged dimensions to `rt_input` so it has the desired ragged rank."""
if ragged_rank > 0:
if not ragged_tensor.is_ragged(rt_input):
rt_input = ragged_conversion_ops.from_tensor(rt_input)
if rt_input.ragged_rank < ragged_rank:
rt_input = rt_input.with_values(
_increase_ragged_rank_to(rt_input.values, ragged_rank - 1))
return rt_input
def _concat_ragged_splits(splits_list):
"""Concatenates a list of RaggedTensor splits to form a single splits."""
pieces = [splits_list[0]]
splits_offset = splits_list[0][-1]
for splits in splits_list[1:]:
pieces.append(splits[1:] + splits_offset)
splits_offset += splits[-1]
return array_ops.concat(pieces, axis=0)
| apache-2.0 |
SDoc/py-sdoc | sdoc/sdoc2/node/ChapterNode.py | 1 | 1420 | from typing import Dict
from cleo.styles import OutputStyle
from sdoc.sdoc2.node.HeadingNode import HeadingNode
from sdoc.sdoc2.NodeStore import NodeStore
class ChapterNode(HeadingNode):
"""
SDoc2 node for chapters.
"""
# ------------------------------------------------------------------------------------------------------------------
def __init__(self, io: OutputStyle, options: Dict[str, str], argument: str):
"""
Object constructor.
:param OutputStyle io: The IO object.
:param dict[str,str] options: The options of this chapter.
:param str argument: The title of this chapter.
"""
super().__init__(io, 'chapter', options, argument)
# ------------------------------------------------------------------------------------------------------------------
def get_command(self) -> str:
"""
Returns the command of this node, i.e. chapter.
"""
return 'chapter'
# ------------------------------------------------------------------------------------------------------------------
def get_hierarchy_level(self, parent_hierarchy_level: int = -1) -> int:
"""
Returns 1.
"""
return 1
# ----------------------------------------------------------------------------------------------------------------------
NodeStore.register_inline_command('chapter', ChapterNode)
| mit |
mrquim/repository.mrquim | plugin.video.salts/js2py/constructors/jsuint8clampedarray.py | 20 | 2801 | # this is based on jsarray.py
from ..base import *
try:
import numpy
except:
pass
@Js
def Uint8ClampedArray():
TypedArray = (PyJsInt8Array,PyJsUint8Array,PyJsUint8ClampedArray,PyJsInt16Array,PyJsUint16Array,PyJsInt32Array,PyJsUint32Array,PyJsFloat32Array,PyJsFloat64Array)
a = arguments[0]
if isinstance(a, PyJsNumber): # length
length = a.to_uint32()
if length!=a.value:
raise MakeError('RangeError', 'Invalid array length')
temp = Js(numpy.full(length, 0, dtype=numpy.uint8), Clamped=True)
temp.put('length', a)
return temp
elif isinstance(a, PyJsString): # object (string)
temp = Js(numpy.array(list(a.value), dtype=numpy.uint8), Clamped=True)
temp.put('length', Js(len(list(a.value))))
return temp
elif isinstance(a, PyJsArray) or isinstance(a,TypedArray) or isinstance(a,PyJsArrayBuffer): # object (Array, TypedArray)
array = a.to_list()
array = [(int(item.value) if item.value != None else 0) for item in array]
temp = Js(numpy.array(array, dtype=numpy.uint8), Clamped=True)
temp.put('length', Js(len(array)))
return temp
elif isinstance(a,PyObjectWrapper): # object (ArrayBuffer, etc)
if len(arguments) > 1:
offset = int(arguments[1].value)
else:
offset = 0
if len(arguments) > 2:
length = int(arguments[2].value)
else:
length = int(len(a.obj)-offset)
array = numpy.frombuffer(a.obj, dtype=numpy.uint8, count=length, offset=offset)
temp = Js(array, Clamped=True)
temp.put('length', Js(length))
temp.buff = array
return temp
temp = Js(numpy.full(0, 0, dtype=numpy.uint8), Clamped=True)
temp.put('length', Js(0))
return temp
Uint8ClampedArray.create = Uint8ClampedArray
Uint8ClampedArray.own['length']['value'] = Js(3)
Uint8ClampedArray.define_own_property('prototype', {'value': Uint8ClampedArrayPrototype,
'enumerable': False,
'writable': False,
'configurable': False})
Uint8ClampedArrayPrototype.define_own_property('constructor', {'value': Uint8ClampedArray,
'enumerable': False,
'writable': True,
'configurable': True})
Uint8ClampedArrayPrototype.define_own_property('BYTES_PER_ELEMENT', {'value': Js(1),
'enumerable': False,
'writable': False,
'configurable': False})
| gpl-2.0 |
vaideesg/omsdk | omdrivers/types/iDRAC/BIOS.py | 1 | 46898 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#
# Copyright © 2017 Dell Inc. or its subsidiaries. All rights reserved.
# Dell, EMC, and other trademarks are trademarks of Dell Inc. or its
# subsidiaries. Other trademarks may be trademarks of their respective owners.
#
# 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/>.
#
# Authors: Vaideeswaran Ganesan
#
from omdrivers.enums.iDRAC.BIOS import *
from omsdk.typemgr.ClassType import ClassType
from omsdk.typemgr.ArrayType import ArrayType
from omsdk.typemgr.BuiltinTypes import *
import sys
import logging
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
logger = logging.getLogger(__name__)
class BIOS(ClassType):
def __init__(self, parent = None, loading_from_scp=False):
if PY2:
super(BIOS, self).__init__("Component", None, parent)
else:
super().__init__("Component", None, parent)
self.AcPwrRcvry = EnumTypeField(None,AcPwrRcvryTypes, parent=self)
self.AcPwrRcvryDelay = EnumTypeField(None,AcPwrRcvryDelayTypes, parent=self)
self.AcPwrRcvryUserDelay = IntField(None, parent=self)
self.AddrBasMir = EnumTypeField(None,AddrBasMirTypes, parent=self)
self.AesNi = StringField("", parent=self)
self.AssetTag = StringField("", parent=self)
self.AttemptFastBoot = EnumTypeField(None,AttemptFastBootTypes, parent=self)
self.AttemptFastBootCold = EnumTypeField(None,AttemptFastBootColdTypes, parent=self)
self.BatteryStatus = StringField("", parent=self)
self.BiosBootSeq = StringField("", parent=self, rebootRequired = True)
self.BiosUpdateControl = EnumTypeField(None,BiosUpdateControlTypes, parent=self)
self.BootMode = EnumTypeField(None,BootModeTypes, parent=self, rebootRequired = True)
self.BootSeq = StringField("", parent=self)
self.BootSeqRetry = EnumTypeField(None,BootSeqRetryTypes, parent=self)
self.BrowserDebugMode = EnumTypeField(None,BrowserDebugModeTypes, parent=self)
self.BrowserMode = EnumTypeField(None,BrowserModeTypes, parent=self)
self.BugChecking = EnumTypeField(None,BugCheckingTypes, parent=self)
self.CTOMasking = EnumTypeField(None,CTOMaskingTypes, parent=self)
self.CkeThrottling = EnumTypeField(None,CkeThrottlingTypes, parent=self)
self.ClpOutput = EnumTypeField(None,ClpOutputTypes, parent=self)
self.ClusterOnDie = EnumTypeField(None,ClusterOnDieTypes, parent=self)
self.CollaborativeCpuPerfCtrl = EnumTypeField(None,CollaborativeCpuPerfCtrlTypes, parent=self)
self.ConTermType = EnumTypeField(None,ConTermTypeTypes, parent=self)
self.ControlledTurbo = EnumTypeField(None,ControlledTurboTypes, parent=self)
self.ControlledTurboExtended = EnumTypeField(None,ControlledTurboExtendedTypes, parent=self)
self.CorePerfBoost = EnumTypeField(None,CorePerfBoostTypes, parent=self)
self.CorrEccSmi = EnumTypeField(None,CorrEccSmiTypes, parent=self)
self.CpuInterconnectBusLinkPower = EnumTypeField(None,CpuInterconnectBusLinkPowerTypes, parent=self)
self.CpuInterconnectBusSpeed = EnumTypeField(None,CpuInterconnectBusSpeedTypes, parent=self)
self.CurrentEmbVideoState = StringField("", parent=self)
self.CurrentLimit = IntField(None, parent=self)
self.CurrentMemOpModeState = StringField("", parent=self)
self.DataReuse = EnumTypeField(None,DataReuseTypes, parent=self)
self.DcuIpPrefetcher = EnumTypeField(None,DcuIpPrefetcherTypes, parent=self)
self.DcuStreamerPrefetcher = EnumTypeField(None,DcuStreamerPrefetcherTypes, parent=self)
self.DebugErrorLevel = StringField("", parent=self)
self.DellAutoDiscovery = EnumTypeField(None,DellAutoDiscoveryTypes, parent=self)
self.DellWyseP25BIOSAccess = EnumTypeField(None,DellWyseP25BIOSAccessTypes, parent=self)
self.DeviceUnhide = EnumTypeField(None,DeviceUnhideTypes, parent=self)
self.Dfx = EnumTypeField(None,DfxTypes, parent=self)
self.DirectMediaInterfaceSpeed = EnumTypeField(None,DirectMediaInterfaceSpeedTypes, parent=self)
self.DmaVirtualization = EnumTypeField(None,DmaVirtualizationTypes, parent=self)
self.DynamicCoreAllocation = EnumTypeField(None,DynamicCoreAllocationTypes, parent=self)
self.EmbNic1 = EnumTypeField(None,EmbNic1Types, parent=self)
self.EmbNic1Nic2 = EnumTypeField(None,EmbNic1Nic2Types, parent=self)
self.EmbNic2 = EnumTypeField(None,EmbNic2Types, parent=self)
self.EmbNic3 = EnumTypeField(None,EmbNic3Types, parent=self)
self.EmbNic3Nic4 = EnumTypeField(None,EmbNic3Nic4Types, parent=self)
self.EmbNic4 = EnumTypeField(None,EmbNic4Types, parent=self)
self.EmbNicPort1BootProto = EnumTypeField(None,EmbNicPort1BootProtoTypes, parent=self)
self.EmbNicPort2BootProto = EnumTypeField(None,EmbNicPort2BootProtoTypes, parent=self)
self.EmbNicPort3BootProto = EnumTypeField(None,EmbNicPort3BootProtoTypes, parent=self)
self.EmbNicPort4BootProto = EnumTypeField(None,EmbNicPort4BootProtoTypes, parent=self)
self.EmbSata = EnumTypeField(None,EmbSataTypes, parent=self)
self.EmbSataRSTeDebug = EnumTypeField(None,EmbSataRSTeDebugTypes, parent=self)
self.EmbSataShadow = EnumTypeField(None,EmbSataShadowTypes, parent=self)
self.EmbSataTestMode = EnumTypeField(None,EmbSataTestModeTypes, parent=self)
self.EmbVideo = EnumTypeField(None,EmbVideoTypes, parent=self)
self.EnergyEfficientTurbo = EnumTypeField(None,EnergyEfficientTurboTypes, parent=self)
self.EnergyPerformanceBias = EnumTypeField(None,EnergyPerformanceBiasTypes, parent=self)
self.ErrPrompt = EnumTypeField(None,ErrPromptTypes, parent=self)
self.ExtSerialConnector = EnumTypeField(None,ExtSerialConnectorTypes, parent=self)
self.FailSafeBaud = EnumTypeField(None,FailSafeBaudTypes, parent=self)
self.FanPwrPerf = EnumTypeField(None,FanPwrPerfTypes, parent=self)
self.ForceInt10 = EnumTypeField(None,ForceInt10Types, parent=self)
self.FrontLcd = EnumTypeField(None,FrontLcdTypes, parent=self)
self.GlobalSlotDriverDisable = EnumTypeField(None,GlobalSlotDriverDisableTypes, parent=self)
self.HddFailover = EnumTypeField(None,HddFailoverTypes, parent=self)
self.HddSeq = StringField("", parent=self, rebootRequired = True)
self.HttpDev1EnDis = EnumTypeField(HttpDev1EnDisTypes.Disabled,HttpDev1EnDisTypes, parent=self)
self.HttpDev1Interface = StringField("", parent=self)
self.HttpDev1Protocol = EnumTypeField(HttpDev1ProtocolTypes.IPv4,HttpDev1ProtocolTypes, parent=self)
self.HttpDev1Uri = StringField("", parent=self)
self.HttpDev1VlanEnDis = EnumTypeField(HttpDev1VlanEnDisTypes.Disabled,HttpDev1VlanEnDisTypes, parent=self)
self.HttpDev1VlanId = IntField(None, parent=self)
self.HttpDev1VlanPriority = IntField(None, parent=self)
self.HttpDev2EnDis = EnumTypeField(HttpDev2EnDisTypes.Disabled,HttpDev2EnDisTypes, parent=self)
self.HttpDev2Interface = StringField("", parent=self)
self.HttpDev2Protocol = EnumTypeField(HttpDev2ProtocolTypes.IPv4,HttpDev2ProtocolTypes, parent=self)
self.HttpDev2Uri = StringField("", parent=self)
self.HttpDev2VlanEnDis = EnumTypeField(HttpDev2VlanEnDisTypes.Disabled,HttpDev2VlanEnDisTypes, parent=self)
self.HttpDev2VlanId = IntField(None, parent=self)
self.HttpDev2VlanPriority = IntField(None, parent=self)
self.HttpDev3EnDis = EnumTypeField(HttpDev3EnDisTypes.Disabled,HttpDev3EnDisTypes, parent=self)
self.HttpDev3Interface = StringField("", parent=self)
self.HttpDev3Protocol = EnumTypeField(HttpDev3ProtocolTypes.IPv4,HttpDev3ProtocolTypes, parent=self)
self.HttpDev3Uri = StringField("", parent=self)
self.HttpDev3VlanEnDis = EnumTypeField(HttpDev3VlanEnDisTypes.Disabled,HttpDev3VlanEnDisTypes, parent=self)
self.HttpDev3VlanId = IntField(None, parent=self)
self.HttpDev3VlanPriority = IntField(None, parent=self)
self.HttpDev4EnDis = EnumTypeField(HttpDev4EnDisTypes.Disabled,HttpDev4EnDisTypes, parent=self)
self.HttpDev4Interface = StringField("", parent=self)
self.HttpDev4Protocol = EnumTypeField(HttpDev4ProtocolTypes.IPv4,HttpDev4ProtocolTypes, parent=self)
self.HttpDev4Uri = StringField("", parent=self)
self.HttpDev4VlanEnDis = EnumTypeField(HttpDev4VlanEnDisTypes.Disabled,HttpDev4VlanEnDisTypes, parent=self)
self.HttpDev4VlanId = IntField(None, parent=self)
self.HttpDev4VlanPriority = IntField(None, parent=self)
self.IdracDebugMode = EnumTypeField(None,IdracDebugModeTypes, parent=self)
self.IgnoreIdracCrReq = EnumTypeField(None,IgnoreIdracCrReqTypes, parent=self)
self.IioPcieGlobalSpeed = EnumTypeField(None,IioPcieGlobalSpeedTypes, parent=self)
self.InBandManageabilityInterface = EnumTypeField(None,InBandManageabilityInterfaceTypes, parent=self)
self.InSystemCharacterization = EnumTypeField(None,InSystemCharacterizationTypes, parent=self)
self.IntNic1Port1BootProto = EnumTypeField(None,IntNic1Port1BootProtoTypes, parent=self)
self.IntNic1Port2BootProto = EnumTypeField(None,IntNic1Port2BootProtoTypes, parent=self)
self.IntNic1Port3BootProto = EnumTypeField(None,IntNic1Port3BootProtoTypes, parent=self)
self.IntNic1Port4BootProto = EnumTypeField(None,IntNic1Port4BootProtoTypes, parent=self)
self.IntegratedNetwork1 = EnumTypeField(None,IntegratedNetwork1Types, parent=self)
self.IntegratedNetwork2 = EnumTypeField(None,IntegratedNetwork2Types, parent=self)
self.IntegratedRaid = EnumTypeField(None,IntegratedRaidTypes, parent=self)
self.IntegratedSas = EnumTypeField(None,IntegratedSasTypes, parent=self)
self.IntelTestEventIio = EnumTypeField(None,IntelTestEventIioTypes, parent=self)
self.IntelTxt = EnumTypeField(None,IntelTxtTypes, parent=self)
self.InteractivePassword24A = EnumTypeField(None,InteractivePassword24ATypes, parent=self)
self.InternalSdCard = EnumTypeField(None,InternalSdCardTypes, parent=self)
self.InternalSdCardPresence = EnumTypeField(None,InternalSdCardPresenceTypes, parent=self)
self.InternalSdCardPrimaryCard = EnumTypeField(None,InternalSdCardPrimaryCardTypes, parent=self)
self.InternalSdCardRedundancy = EnumTypeField(None,InternalSdCardRedundancyTypes, parent=self)
self.InternalUsb = EnumTypeField(None,InternalUsbTypes, parent=self)
self.InternalUsb1 = EnumTypeField(None,InternalUsb1Types, parent=self)
self.InternalUsb2 = EnumTypeField(None,InternalUsb2Types, parent=self)
self.IoNonPostedPrefetch = EnumTypeField(None,IoNonPostedPrefetchTypes, parent=self)
self.IoatEngine = EnumTypeField(None,IoatEngineTypes, parent=self)
self.IscsiDev1Con1Auth = EnumTypeField(None,IscsiDev1Con1AuthTypes, parent=self)
self.IscsiDev1Con1ChapName = StringField("", parent=self)
self.IscsiDev1Con1ChapSecret = StringField("", parent=self)
self.IscsiDev1Con1ChapType = EnumTypeField(None,IscsiDev1Con1ChapTypeTypes, parent=self)
self.IscsiDev1Con1DhcpEnDis = EnumTypeField(None,IscsiDev1Con1DhcpEnDisTypes, parent=self)
self.IscsiDev1Con1EnDis = EnumTypeField(None,IscsiDev1Con1EnDisTypes, parent=self)
self.IscsiDev1Con1Gateway = StringField("", parent=self)
self.IscsiDev1Con1Interface = StringField("", parent=self)
self.IscsiDev1Con1Ip = StringField("", parent=self)
self.IscsiDev1Con1IsId = StringField("", parent=self)
self.IscsiDev1Con1Lun = IntField(None, parent=self)
self.IscsiDev1Con1Mask = StringField("", parent=self)
self.IscsiDev1Con1Port = IntField(None, parent=self)
self.IscsiDev1Con1Protocol = EnumTypeField(None,IscsiDev1Con1ProtocolTypes, parent=self)
self.IscsiDev1Con1Retry = IntField(None, parent=self)
self.IscsiDev1Con1RevChapName = StringField("", parent=self)
self.IscsiDev1Con1RevChapSecret = StringField("", parent=self)
self.IscsiDev1Con1TargetIp = StringField("", parent=self)
self.IscsiDev1Con1TargetName = StringField("", parent=self)
self.IscsiDev1Con1TgtDhcpEnDis = EnumTypeField(None,IscsiDev1Con1TgtDhcpEnDisTypes, parent=self)
self.IscsiDev1Con1Timeout = IntField(None, parent=self)
self.IscsiDev1Con1VlanEnDis = EnumTypeField(None,IscsiDev1Con1VlanEnDisTypes, parent=self)
self.IscsiDev1Con1VlanId = IntField(None, parent=self)
self.IscsiDev1Con1VlanPriority = IntField(None, parent=self)
self.IscsiDev1Con2Auth = EnumTypeField(None,IscsiDev1Con2AuthTypes, parent=self)
self.IscsiDev1Con2ChapName = StringField("", parent=self)
self.IscsiDev1Con2ChapSecret = StringField("", parent=self)
self.IscsiDev1Con2ChapType = EnumTypeField(None,IscsiDev1Con2ChapTypeTypes, parent=self)
self.IscsiDev1Con2DhcpEnDis = EnumTypeField(None,IscsiDev1Con2DhcpEnDisTypes, parent=self)
self.IscsiDev1Con2EnDis = EnumTypeField(None,IscsiDev1Con2EnDisTypes, parent=self)
self.IscsiDev1Con2Gateway = StringField("", parent=self)
self.IscsiDev1Con2Interface = StringField("", parent=self)
self.IscsiDev1Con2Ip = StringField("", parent=self)
self.IscsiDev1Con2IsId = StringField("", parent=self)
self.IscsiDev1Con2Lun = IntField(None, parent=self)
self.IscsiDev1Con2Mask = StringField("", parent=self)
self.IscsiDev1Con2Port = IntField(None, parent=self)
self.IscsiDev1Con2Protocol = EnumTypeField(None,IscsiDev1Con2ProtocolTypes, parent=self)
self.IscsiDev1Con2Retry = IntField(None, parent=self)
self.IscsiDev1Con2RevChapName = StringField("", parent=self)
self.IscsiDev1Con2RevChapSecret = StringField("", parent=self)
self.IscsiDev1Con2TargetIp = StringField("", parent=self)
self.IscsiDev1Con2TargetName = StringField("", parent=self)
self.IscsiDev1Con2TgtDhcpEnDis = EnumTypeField(None,IscsiDev1Con2TgtDhcpEnDisTypes, parent=self)
self.IscsiDev1Con2Timeout = IntField(None, parent=self)
self.IscsiDev1Con2VlanEnDis = EnumTypeField(None,IscsiDev1Con2VlanEnDisTypes, parent=self)
self.IscsiDev1Con2VlanId = IntField(None, parent=self)
self.IscsiDev1Con2VlanPriority = IntField(None, parent=self)
self.IscsiDev1ConOrder = StringField("", parent=self)
self.IscsiDev1EnDis = EnumTypeField(None,IscsiDev1EnDisTypes, parent=self)
self.IscsiInitiatorName = StringField("", parent=self)
self.JunoPmEnable = EnumTypeField(None,JunoPmEnableTypes, parent=self)
self.L1Prefetcher = StringField("", parent=self)
self.L2Prefetcher = StringField("", parent=self)
self.LinkDowntrainReporting = EnumTypeField(None,LinkDowntrainReportingTypes, parent=self)
self.LogicalProc = EnumTypeField(None,LogicalProcTypes, parent=self)
self.MRCSerialDbgOut = EnumTypeField(None,MRCSerialDbgOutTypes, parent=self)
self.MeFailureRecoveryEnable = EnumTypeField(None,MeFailureRecoveryEnableTypes, parent=self)
self.MeUmaEnable = EnumTypeField(None,MeUmaEnableTypes, parent=self)
self.MemDynamicPwr = EnumTypeField(None,MemDynamicPwrTypes, parent=self)
self.MemFrequency = EnumTypeField(None,MemFrequencyTypes, parent=self)
self.MemHotThrottlingMode = EnumTypeField(None,MemHotThrottlingModeTypes, parent=self)
self.MemLowPower = EnumTypeField(None,MemLowPowerTypes, parent=self)
self.MemOpMode = EnumTypeField(None,MemOpModeTypes, parent=self)
self.MemOpVoltage = EnumTypeField(None,MemOpVoltageTypes, parent=self)
self.MemOptimizer = EnumTypeField(None,MemOptimizerTypes, parent=self)
self.MemPatrolScrub = EnumTypeField(None,MemPatrolScrubTypes, parent=self)
self.MemPwrMgmt = EnumTypeField(None,MemPwrMgmtTypes, parent=self)
self.MemPwrPerf = EnumTypeField(None,MemPwrPerfTypes, parent=self)
self.MemRefreshRate = EnumTypeField(None,MemRefreshRateTypes, parent=self)
self.MemTest = EnumTypeField(None,MemTestTypes, parent=self)
self.MemTestOnFastBoot = EnumTypeField(None,MemTestOnFastBootTypes, parent=self)
self.MemTestType = EnumTypeField(None,MemTestTypeTypes, parent=self)
self.MemThrottlingMode = EnumTypeField(MemThrottlingModeTypes.Cltt,MemThrottlingModeTypes, parent=self)
self.MemVolt = EnumTypeField(None,MemVoltTypes, parent=self)
self.MemoryFastBootCold = EnumTypeField(None,MemoryFastBootColdTypes, parent=self)
self.MemoryMappedIOH = EnumTypeField(MemoryMappedIOHTypes.Disabled,MemoryMappedIOHTypes, parent=self)
self.MemoryMultiThread = EnumTypeField(None,MemoryMultiThreadTypes, parent=self)
self.MemoryPerBitMargin = EnumTypeField(None,MemoryPerBitMarginTypes, parent=self)
self.MemoryRmt = EnumTypeField(None,MemoryRmtTypes, parent=self)
self.MemoryThrottlingMode = EnumTypeField(None,MemoryThrottlingModeTypes, parent=self)
self.MltRnkSpr = EnumTypeField(None,MltRnkSprTypes, parent=self)
self.MmioAbove4Gb = EnumTypeField(None,MmioAbove4GbTypes, parent=self)
self.MonitorMwait = EnumTypeField(None,MonitorMwaitTypes, parent=self)
self.MultiThreaded = EnumTypeField(None,MultiThreadedTypes, parent=self)
self.Ndc1PcieLink1 = EnumTypeField(None,Ndc1PcieLink1Types, parent=self)
self.Ndc1PcieLink2 = EnumTypeField(None,Ndc1PcieLink2Types, parent=self)
self.Ndc1PcieLink3 = EnumTypeField(None,Ndc1PcieLink3Types, parent=self)
self.NdcConfigurationSpeed = EnumTypeField(None,NdcConfigurationSpeedTypes, parent=self)
# readonly attribute
self.NewSetupPassword = StringField("", parent=self, modifyAllowed = False, deleteAllowed = False)
# readonly attribute
self.NewSysPassword = StringField("", parent=self, modifyAllowed = False, deleteAllowed = False)
self.NmiButton = EnumTypeField(None,NmiButtonTypes, parent=self)
self.NodeInterleave = EnumTypeField(None,NodeInterleaveTypes, parent=self)
self.NumLock = EnumTypeField(None,NumLockTypes, parent=self)
self.NvdimmFactoryDefault = EnumTypeField(None,NvdimmFactoryDefaultTypes, parent=self)
self.NvdimmFactoryDefault0 = EnumTypeField(None,NvdimmFactoryDefault0Types, parent=self)
self.NvdimmFactoryDefault1 = EnumTypeField(None,NvdimmFactoryDefault1Types, parent=self)
self.NvdimmFactoryDefault10 = EnumTypeField(None,NvdimmFactoryDefault10Types, parent=self)
self.NvdimmFactoryDefault11 = EnumTypeField(None,NvdimmFactoryDefault11Types, parent=self)
self.NvdimmFactoryDefault2 = EnumTypeField(None,NvdimmFactoryDefault2Types, parent=self)
self.NvdimmFactoryDefault3 = EnumTypeField(None,NvdimmFactoryDefault3Types, parent=self)
self.NvdimmFactoryDefault4 = EnumTypeField(None,NvdimmFactoryDefault4Types, parent=self)
self.NvdimmFactoryDefault5 = EnumTypeField(None,NvdimmFactoryDefault5Types, parent=self)
self.NvdimmFactoryDefault6 = EnumTypeField(None,NvdimmFactoryDefault6Types, parent=self)
self.NvdimmFactoryDefault7 = EnumTypeField(None,NvdimmFactoryDefault7Types, parent=self)
self.NvdimmFactoryDefault8 = EnumTypeField(None,NvdimmFactoryDefault8Types, parent=self)
self.NvdimmFactoryDefault9 = EnumTypeField(None,NvdimmFactoryDefault9Types, parent=self)
self.NvdimmFirmwareVer0 = StringField("", parent=self)
self.NvdimmFirmwareVer1 = StringField("", parent=self)
self.NvdimmFirmwareVer10 = StringField("", parent=self)
self.NvdimmFirmwareVer11 = StringField("", parent=self)
self.NvdimmFirmwareVer2 = StringField("", parent=self)
self.NvdimmFirmwareVer3 = StringField("", parent=self)
self.NvdimmFirmwareVer4 = StringField("", parent=self)
self.NvdimmFirmwareVer5 = StringField("", parent=self)
self.NvdimmFirmwareVer6 = StringField("", parent=self)
self.NvdimmFirmwareVer7 = StringField("", parent=self)
self.NvdimmFirmwareVer8 = StringField("", parent=self)
self.NvdimmFirmwareVer9 = StringField("", parent=self)
self.NvdimmFreq0 = StringField("", parent=self)
self.NvdimmFreq1 = StringField("", parent=self)
self.NvdimmFreq10 = StringField("", parent=self)
self.NvdimmFreq11 = StringField("", parent=self)
self.NvdimmFreq2 = StringField("", parent=self)
self.NvdimmFreq3 = StringField("", parent=self)
self.NvdimmFreq4 = StringField("", parent=self)
self.NvdimmFreq5 = StringField("", parent=self)
self.NvdimmFreq6 = StringField("", parent=self)
self.NvdimmFreq7 = StringField("", parent=self)
self.NvdimmFreq8 = StringField("", parent=self)
self.NvdimmFreq9 = StringField("", parent=self)
self.NvdimmInterleaveSupport = EnumTypeField(None,NvdimmInterleaveSupportTypes, parent=self)
self.NvdimmLocation0 = StringField("", parent=self)
self.NvdimmLocation1 = StringField("", parent=self)
self.NvdimmLocation10 = StringField("", parent=self)
self.NvdimmLocation11 = StringField("", parent=self)
self.NvdimmLocation2 = StringField("", parent=self)
self.NvdimmLocation3 = StringField("", parent=self)
self.NvdimmLocation4 = StringField("", parent=self)
self.NvdimmLocation5 = StringField("", parent=self)
self.NvdimmLocation6 = StringField("", parent=self)
self.NvdimmLocation7 = StringField("", parent=self)
self.NvdimmLocation8 = StringField("", parent=self)
self.NvdimmLocation9 = StringField("", parent=self)
self.NvdimmReadOnly = EnumTypeField(None,NvdimmReadOnlyTypes, parent=self)
self.NvdimmSerialNum0 = StringField("", parent=self)
self.NvdimmSerialNum1 = StringField("", parent=self)
self.NvdimmSerialNum10 = StringField("", parent=self)
self.NvdimmSerialNum11 = StringField("", parent=self)
self.NvdimmSerialNum2 = StringField("", parent=self)
self.NvdimmSerialNum3 = StringField("", parent=self)
self.NvdimmSerialNum4 = StringField("", parent=self)
self.NvdimmSerialNum5 = StringField("", parent=self)
self.NvdimmSerialNum6 = StringField("", parent=self)
self.NvdimmSerialNum7 = StringField("", parent=self)
self.NvdimmSerialNum8 = StringField("", parent=self)
self.NvdimmSerialNum9 = StringField("", parent=self)
self.NvdimmSize0 = StringField("", parent=self)
self.NvdimmSize1 = StringField("", parent=self)
self.NvdimmSize10 = StringField("", parent=self)
self.NvdimmSize11 = StringField("", parent=self)
self.NvdimmSize2 = StringField("", parent=self)
self.NvdimmSize3 = StringField("", parent=self)
self.NvdimmSize4 = StringField("", parent=self)
self.NvdimmSize5 = StringField("", parent=self)
self.NvdimmSize6 = StringField("", parent=self)
self.NvdimmSize7 = StringField("", parent=self)
self.NvdimmSize8 = StringField("", parent=self)
self.NvdimmSize9 = StringField("", parent=self)
self.NvmeMode = EnumTypeField(None,NvmeModeTypes, parent=self)
# readonly attribute
self.OldSetupPassword = StringField("", parent=self, modifyAllowed = False, deleteAllowed = False)
# readonly attribute
self.OldSysPassword = StringField("", parent=self, modifyAllowed = False, deleteAllowed = False)
self.OneTimeBiosBootSeq = StringField("", parent=self)
self.OneTimeBootMode = EnumTypeField(None,OneTimeBootModeTypes, parent=self)
self.OneTimeBootModeSeq = StringField("", parent=self)
self.OneTimeBootSeqDev = EnumTypeField(None,OneTimeBootSeqDevTypes, parent=self)
self.OneTimeCustomBootStr = StringField("", parent=self)
self.OneTimeHddSeq = StringField("", parent=self)
self.OneTimeHddSeqDev = EnumTypeField(None,OneTimeHddSeqDevTypes, parent=self)
self.OneTimeUefiBootPath = StringField("", parent=self)
self.OneTimeUefiBootSeq = StringField("", parent=self)
self.OneTimeUefiBootSeqDev = EnumTypeField(None,OneTimeUefiBootSeqDevTypes, parent=self)
self.OppSrefEn = EnumTypeField(None,OppSrefEnTypes, parent=self)
self.OsWatchdogTimer = EnumTypeField(None,OsWatchdogTimerTypes, parent=self)
self.PCIeErrorInjection = EnumTypeField(None,PCIeErrorInjectionTypes, parent=self)
self.PCIeLiveErrorRecovery = EnumTypeField(None,PCIeLiveErrorRecoveryTypes, parent=self)
self.PPRErrInjectionTest = EnumTypeField(None,PPRErrInjectionTestTypes, parent=self)
self.PasswordStatus = EnumTypeField(None,PasswordStatusTypes, parent=self)
self.PcieAspmL1 = EnumTypeField(None,PcieAspmL1Types, parent=self)
self.PerfMonitorDevices = EnumTypeField(None,PerfMonitorDevicesTypes, parent=self)
self.PersistentMemoryMode = EnumTypeField(None,PersistentMemoryModeTypes, parent=self)
self.PersistentMemoryScrubbing = EnumTypeField(None,PersistentMemoryScrubbingTypes, parent=self)
self.PostPackageRepair = EnumTypeField(None,PostPackageRepairTypes, parent=self)
self.PowerCycleRequest = EnumTypeField(None,PowerCycleRequestTypes, parent=self)
self.PowerDelivery = EnumTypeField(None,PowerDeliveryTypes, parent=self)
self.PowerMgmt = EnumTypeField(None,PowerMgmtTypes, parent=self)
self.PowerSaver = EnumTypeField(None,PowerSaverTypes, parent=self)
self.Proc1Brand = StringField("", parent=self)
self.Proc1ControlledTurbo = EnumTypeField(None,Proc1ControlledTurboTypes, parent=self)
self.Proc1Cores = EnumTypeField(None,Proc1CoresTypes, parent=self)
self.Proc1Id = StringField("", parent=self)
self.Proc1L2Cache = StringField("", parent=self)
self.Proc1L3Cache = StringField("", parent=self)
self.Proc1Microcode = IntField(None, parent=self)
self.Proc1NumCores = IntField(None, parent=self)
self.Proc1TurboCoreNum = EnumTypeField(None,Proc1TurboCoreNumTypes, parent=self)
self.Proc2Brand = StringField("", parent=self)
self.Proc2ControlledTurbo = EnumTypeField(None,Proc2ControlledTurboTypes, parent=self)
self.Proc2Cores = EnumTypeField(None,Proc2CoresTypes, parent=self)
self.Proc2Id = StringField("", parent=self)
self.Proc2L2Cache = StringField("", parent=self)
self.Proc2L3Cache = StringField("", parent=self)
self.Proc2Microcode = IntField(None, parent=self)
self.Proc2NumCores = IntField(None, parent=self)
self.Proc2TurboCoreNum = EnumTypeField(None,Proc2TurboCoreNumTypes, parent=self)
self.Proc3Brand = StringField("", parent=self)
self.Proc3ControlledTurbo = EnumTypeField(None,Proc3ControlledTurboTypes, parent=self)
self.Proc3Cores = EnumTypeField(None,Proc3CoresTypes, parent=self)
self.Proc3Id = StringField("", parent=self)
self.Proc3L2Cache = StringField("", parent=self)
self.Proc3L3Cache = StringField("", parent=self)
self.Proc3Microcode = IntField(None, parent=self)
self.Proc3NumCores = IntField(None, parent=self)
self.Proc3TurboCoreNum = EnumTypeField(None,Proc3TurboCoreNumTypes, parent=self)
self.Proc4Brand = StringField("", parent=self)
self.Proc4ControlledTurbo = EnumTypeField(None,Proc4ControlledTurboTypes, parent=self)
self.Proc4Cores = EnumTypeField(None,Proc4CoresTypes, parent=self)
self.Proc4Id = StringField("", parent=self)
self.Proc4L2Cache = StringField("", parent=self)
self.Proc4L3Cache = StringField("", parent=self)
self.Proc4Microcode = IntField(None, parent=self)
self.Proc4NumCores = IntField(None, parent=self)
self.Proc4TurboCoreNum = EnumTypeField(None,Proc4TurboCoreNumTypes, parent=self)
self.Proc64bit = StringField("", parent=self)
self.ProcATS = EnumTypeField(None,ProcATSTypes, parent=self)
self.ProcAdjCacheLine = EnumTypeField(None,ProcAdjCacheLineTypes, parent=self)
self.ProcBusSpeed = StringField("", parent=self)
self.ProcC1E = EnumTypeField(None,ProcC1ETypes, parent=self)
self.ProcCStates = EnumTypeField(None,ProcCStatesTypes, parent=self)
self.ProcConfigTdp = EnumTypeField(None,ProcConfigTdpTypes, parent=self)
self.ProcCoreSpeed = StringField("", parent=self)
self.ProcCores = EnumTypeField(None,ProcCoresTypes, parent=self)
self.ProcDpatProDebug = EnumTypeField(None,ProcDpatProDebugTypes, parent=self)
self.ProcDramPrefetcher = EnumTypeField(None,ProcDramPrefetcherTypes, parent=self)
self.ProcEmbMemCacheSize = StringField("", parent=self)
self.ProcEmbMemMode = EnumTypeField(ProcEmbMemModeTypes.Cache,ProcEmbMemModeTypes, parent=self)
self.ProcEmbMemSystemSize = StringField("", parent=self)
self.ProcEmbMemTotalSize = StringField("", parent=self)
self.ProcExecuteDisable = EnumTypeField(None,ProcExecuteDisableTypes, parent=self)
self.ProcHpcMode = EnumTypeField(None,ProcHpcModeTypes, parent=self)
self.ProcHtAssist = EnumTypeField(None,ProcHtAssistTypes, parent=self)
self.ProcHwPrefetcher = EnumTypeField(None,ProcHwPrefetcherTypes, parent=self)
self.ProcHyperTransport = EnumTypeField(None,ProcHyperTransportTypes, parent=self)
self.ProcMtrrPatDebug = EnumTypeField(None,ProcMtrrPatDebugTypes, parent=self)
self.ProcPwrPerf = EnumTypeField(None,ProcPwrPerfTypes, parent=self)
self.ProcSoftwarePrefetcher = EnumTypeField(None,ProcSoftwarePrefetcherTypes, parent=self)
self.ProcTurboMode = EnumTypeField(None,ProcTurboModeTypes, parent=self)
self.ProcVirtualization = EnumTypeField(None,ProcVirtualizationTypes, parent=self)
self.ProcX2Apic = EnumTypeField(None,ProcX2ApicTypes, parent=self)
self.PwrButton = EnumTypeField(None,PwrButtonTypes, parent=self)
self.PxeDev1EnDis = EnumTypeField(None,PxeDev1EnDisTypes, parent=self)
self.PxeDev1Interface = StringField("", parent=self)
self.PxeDev1Protocol = EnumTypeField(None,PxeDev1ProtocolTypes, parent=self)
self.PxeDev1VlanEnDis = EnumTypeField(None,PxeDev1VlanEnDisTypes, parent=self)
self.PxeDev1VlanId = IntField(None, parent=self)
self.PxeDev1VlanPriority = IntField(None, parent=self)
self.PxeDev2EnDis = EnumTypeField(None,PxeDev2EnDisTypes, parent=self)
self.PxeDev2Interface = StringField("", parent=self)
self.PxeDev2Protocol = EnumTypeField(None,PxeDev2ProtocolTypes, parent=self)
self.PxeDev2VlanEnDis = EnumTypeField(None,PxeDev2VlanEnDisTypes, parent=self)
self.PxeDev2VlanId = IntField(None, parent=self)
self.PxeDev2VlanPriority = IntField(None, parent=self)
self.PxeDev3EnDis = EnumTypeField(None,PxeDev3EnDisTypes, parent=self)
self.PxeDev3Interface = StringField("", parent=self)
self.PxeDev3Protocol = EnumTypeField(None,PxeDev3ProtocolTypes, parent=self)
self.PxeDev3VlanEnDis = EnumTypeField(None,PxeDev3VlanEnDisTypes, parent=self)
self.PxeDev3VlanId = IntField(None, parent=self)
self.PxeDev3VlanPriority = IntField(None, parent=self)
self.PxeDev4EnDis = EnumTypeField(None,PxeDev4EnDisTypes, parent=self)
self.PxeDev4Interface = StringField("", parent=self)
self.PxeDev4Protocol = EnumTypeField(None,PxeDev4ProtocolTypes, parent=self)
self.PxeDev4VlanEnDis = EnumTypeField(None,PxeDev4VlanEnDisTypes, parent=self)
self.PxeDev4VlanId = IntField(None, parent=self)
self.PxeDev4VlanPriority = IntField(None, parent=self)
self.QpiBandwidthPriority = EnumTypeField(None,QpiBandwidthPriorityTypes, parent=self)
self.QpiSpeed = EnumTypeField(None,QpiSpeedTypes, parent=self)
self.RebootTestCount = IntField(None, parent=self)
self.RebootTestMode = EnumTypeField(None,RebootTestModeTypes, parent=self)
self.RebootTestPoint = EnumTypeField(None,RebootTestPointTypes, parent=self)
self.RedirAfterBoot = EnumTypeField(None,RedirAfterBootTypes, parent=self)
self.RedundantMem = EnumTypeField(None,RedundantMemTypes, parent=self)
self.RedundantMemCfgValid = EnumTypeField(None,RedundantMemCfgValidTypes, parent=self)
self.RedundantMemInUse = EnumTypeField(None,RedundantMemInUseTypes, parent=self)
self.RedundantOsBoot = EnumTypeField(None,RedundantOsBootTypes, parent=self)
self.RedundantOsLocation = EnumTypeField(None,RedundantOsLocationTypes, parent=self)
self.RedundantOsState = EnumTypeField(None,RedundantOsStateTypes, parent=self)
self.ReportKbdErr = EnumTypeField(None,ReportKbdErrTypes, parent=self)
self.RipsPresence = EnumTypeField(None,RipsPresenceTypes, parent=self)
self.RtidSetting = EnumTypeField(None,RtidSettingTypes, parent=self)
self.S4SupportDebug = EnumTypeField(None,S4SupportDebugTypes, parent=self)
self.SHA256SetupPassword = StringField("", parent=self)
self.SHA256SetupPasswordSalt = StringField("", parent=self)
self.SHA256SystemPassword = StringField("", parent=self)
self.SHA256SystemPasswordSalt = StringField("", parent=self)
self.SNC = EnumTypeField(None,SNCTypes, parent=self)
self.SataPortA = EnumTypeField(None,SataPortATypes, parent=self)
self.SataPortACapacity = StringField("", parent=self)
self.SataPortADriveType = StringField("", parent=self)
self.SataPortAModel = StringField("", parent=self)
self.SataPortB = EnumTypeField(None,SataPortBTypes, parent=self)
self.SataPortBCapacity = StringField("", parent=self)
self.SataPortBDriveType = StringField("", parent=self)
self.SataPortBModel = StringField("", parent=self)
self.SataPortC = EnumTypeField(None,SataPortCTypes, parent=self)
self.SataPortCCapacity = StringField("", parent=self)
self.SataPortCDriveType = StringField("", parent=self)
self.SataPortCModel = StringField("", parent=self)
self.SataPortD = EnumTypeField(None,SataPortDTypes, parent=self)
self.SataPortDCapacity = StringField("", parent=self)
self.SataPortDDriveType = StringField("", parent=self)
self.SataPortDModel = StringField("", parent=self)
self.SataPortE = EnumTypeField(None,SataPortETypes, parent=self)
self.SataPortECapacity = StringField("", parent=self)
self.SataPortEDriveType = StringField("", parent=self)
self.SataPortEModel = StringField("", parent=self)
self.SataPortF = EnumTypeField(None,SataPortFTypes, parent=self)
self.SataPortFCapacity = StringField("", parent=self)
self.SataPortFDriveType = StringField("", parent=self)
self.SataPortFModel = StringField("", parent=self)
self.SataPortG = EnumTypeField(None,SataPortGTypes, parent=self)
self.SataPortGCapacity = StringField("", parent=self)
self.SataPortGDriveType = StringField("", parent=self)
self.SataPortGModel = StringField("", parent=self)
self.SataPortH = EnumTypeField(None,SataPortHTypes, parent=self)
self.SataPortHCapacity = StringField("", parent=self)
self.SataPortHDriveType = StringField("", parent=self)
self.SataPortHModel = StringField("", parent=self)
self.SataPortI = EnumTypeField(None,SataPortITypes, parent=self)
self.SataPortICapacity = EnumTypeField(None,SataPortICapacityTypes, parent=self)
self.SataPortIDriveType = EnumTypeField(None,SataPortIDriveTypeTypes, parent=self)
self.SataPortIModel = EnumTypeField(None,SataPortIModelTypes, parent=self)
self.SataPortJ = EnumTypeField(None,SataPortJTypes, parent=self)
self.SataPortJCapacity = EnumTypeField(None,SataPortJCapacityTypes, parent=self)
self.SataPortJDriveType = EnumTypeField(None,SataPortJDriveTypeTypes, parent=self)
self.SataPortJModel = EnumTypeField(None,SataPortJModelTypes, parent=self)
self.SataPortK = EnumTypeField(None,SataPortKTypes, parent=self)
self.SataPortKCapacity = StringField("", parent=self)
self.SataPortKDriveType = StringField("", parent=self)
self.SataPortKModel = StringField("", parent=self)
self.SataPortL = EnumTypeField(None,SataPortLTypes, parent=self)
self.SataPortLCapacity = StringField("", parent=self)
self.SataPortLDriveType = EnumTypeField(None,SataPortLDriveTypeTypes, parent=self)
self.SataPortLModel = StringField("", parent=self)
self.SataPortM = EnumTypeField(None,SataPortMTypes, parent=self)
self.SataPortMCapacity = StringField("", parent=self)
self.SataPortMDriveType = StringField("", parent=self)
self.SataPortMModel = EnumTypeField(None,SataPortMModelTypes, parent=self)
self.SataPortN = EnumTypeField(None,SataPortNTypes, parent=self)
self.SataPortNCapacity = StringField("", parent=self)
self.SataPortNDriveType = StringField("", parent=self)
self.SataPortNModel = EnumTypeField(SataPortNModelTypes.SATA_MODEL,SataPortNModelTypes, parent=self)
self.SccDebugEnabled = EnumTypeField(None,SccDebugEnabledTypes, parent=self)
self.SecureBoot = EnumTypeField(None,SecureBootTypes, parent=self)
self.SecureBootMode = EnumTypeField(SecureBootModeTypes.UserMode,SecureBootModeTypes, parent=self)
self.SecureBootPolicy = EnumTypeField(None,SecureBootPolicyTypes, parent=self)
self.SecurityFreezeLock = EnumTypeField(None,SecurityFreezeLockTypes, parent=self)
self.SerialComm = EnumTypeField(None,SerialCommTypes, parent=self)
self.SerialPortAddress = EnumTypeField(None,SerialPortAddressTypes, parent=self)
self.SetBootOrderFqdd1 = StringField("", parent=self)
self.SetBootOrderFqdd10 = StringField("", parent=self)
self.SetBootOrderFqdd11 = StringField("", parent=self)
self.SetBootOrderFqdd12 = StringField("", parent=self)
self.SetBootOrderFqdd13 = StringField("", parent=self)
self.SetBootOrderFqdd14 = StringField("", parent=self)
self.SetBootOrderFqdd15 = StringField("", parent=self)
self.SetBootOrderFqdd16 = StringField("", parent=self)
self.SetBootOrderFqdd2 = StringField("", parent=self)
self.SetBootOrderFqdd3 = StringField("", parent=self)
self.SetBootOrderFqdd4 = StringField("", parent=self)
self.SetBootOrderFqdd5 = StringField("", parent=self)
self.SetBootOrderFqdd6 = StringField("", parent=self)
self.SetBootOrderFqdd7 = StringField("", parent=self)
self.SetBootOrderFqdd8 = StringField("", parent=self)
self.SetBootOrderFqdd9 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd1 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd10 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd11 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd12 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd13 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd14 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd15 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd16 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd2 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd3 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd4 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd5 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd6 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd7 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd8 = StringField("", parent=self)
self.SetLegacyHddOrderFqdd9 = StringField("", parent=self)
self.SetupPassword = StringField("", parent=self)
self.SignedFirmwareUpdate = EnumTypeField(None,SignedFirmwareUpdateTypes, parent=self)
self.Slot1 = EnumTypeField(None,Slot1Types, parent=self)
self.Slot10 = EnumTypeField(None,Slot10Types, parent=self)
self.Slot10Bif = EnumTypeField(None,Slot10BifTypes, parent=self)
self.Slot11 = EnumTypeField(None,Slot11Types, parent=self)
self.Slot11Bif = EnumTypeField(None,Slot11BifTypes, parent=self)
self.Slot12 = EnumTypeField(None,Slot12Types, parent=self)
self.Slot12Bif = EnumTypeField(None,Slot12BifTypes, parent=self)
self.Slot13 = EnumTypeField(None,Slot13Types, parent=self)
self.Slot13Bif = EnumTypeField(None,Slot13BifTypes, parent=self)
self.Slot14Bif = EnumTypeField(None,Slot14BifTypes, parent=self)
self.Slot1Bif = EnumTypeField(None,Slot1BifTypes, parent=self)
self.Slot2 = EnumTypeField(None,Slot2Types, parent=self)
self.Slot2Bif = EnumTypeField(None,Slot2BifTypes, parent=self)
self.Slot3 = EnumTypeField(None,Slot3Types, parent=self)
self.Slot3Bif = EnumTypeField(None,Slot3BifTypes, parent=self)
self.Slot4 = EnumTypeField(None,Slot4Types, parent=self)
self.Slot4Bif = EnumTypeField(None,Slot4BifTypes, parent=self)
self.Slot5 = EnumTypeField(None,Slot5Types, parent=self)
self.Slot5Bif = EnumTypeField(None,Slot5BifTypes, parent=self)
self.Slot6 = EnumTypeField(None,Slot6Types, parent=self)
self.Slot6Bif = EnumTypeField(None,Slot6BifTypes, parent=self)
self.Slot7 = EnumTypeField(None,Slot7Types, parent=self)
self.Slot7Bif = EnumTypeField(None,Slot7BifTypes, parent=self)
self.Slot8 = EnumTypeField(None,Slot8Types, parent=self)
self.Slot8Bif = EnumTypeField(None,Slot8BifTypes, parent=self)
self.Slot9 = EnumTypeField(None,Slot9Types, parent=self)
self.Slot9Bif = EnumTypeField(None,Slot9BifTypes, parent=self)
self.SnoopFilter = EnumTypeField(None,SnoopFilterTypes, parent=self)
self.SnoopMode = EnumTypeField(None,SnoopModeTypes, parent=self)
self.SrefProgramming = EnumTypeField(None,SrefProgrammingTypes, parent=self)
self.SriovGlobalEnable = EnumTypeField(None,SriovGlobalEnableTypes, parent=self)
self.SubNumaCluster = EnumTypeField(None,SubNumaClusterTypes, parent=self)
self.SysMemSize = StringField("", parent=self)
self.SysMemSpeed = StringField("", parent=self)
self.SysMemType = StringField("", parent=self)
self.SysMemVolt = StringField("", parent=self)
self.SysMfrContactInfo = StringField("", parent=self)
self.SysMgmtNVByte1 = IntField(None, parent=self)
self.SysMgmtNVByte2 = IntField(None, parent=self)
self.SysPassword = StringField("", parent=self)
self.SysProfile = EnumTypeField(None,SysProfileTypes, parent=self)
self.SystemBiosVersion = StringField("", parent=self)
self.SystemCpldVersion = StringField("", parent=self)
self.SystemManufacturer = StringField("", parent=self)
self.SystemMeVersion = StringField("", parent=self)
self.SystemMemoryModel = EnumTypeField(SystemMemoryModelTypes.Quadrant,SystemMemoryModelTypes, parent=self)
self.SystemModelName = StringField("", parent=self)
self.SystemServiceTag = StringField("", parent=self)
self.SystemUefiShell = EnumTypeField(None,SystemUefiShellTypes, parent=self)
self.TXEQWA = EnumTypeField(None,TXEQWATypes, parent=self)
self.TcmActivation = EnumTypeField(None,TcmActivationTypes, parent=self)
self.TcmClear = EnumTypeField(None,TcmClearTypes, parent=self)
self.TcmSecurity = EnumTypeField(None,TcmSecurityTypes, parent=self)
self.Tpm2Algorithm = EnumTypeField(None,Tpm2AlgorithmTypes, parent=self)
self.Tpm2Hierarchy = EnumTypeField(None,Tpm2HierarchyTypes, parent=self)
self.TpmActivation = EnumTypeField(None,TpmActivationTypes, parent=self)
self.TpmBindingReset = EnumTypeField(None,TpmBindingResetTypes, parent=self)
self.TpmClear = EnumTypeField(None,TpmClearTypes, parent=self)
self.TpmCommand = EnumTypeField(None,TpmCommandTypes, parent=self)
self.TpmFirmware = StringField("", parent=self)
self.TpmInfo = StringField("", parent=self)
self.TpmPpiBypassClear = EnumTypeField(None,TpmPpiBypassClearTypes, parent=self)
self.TpmPpiBypassProvision = EnumTypeField(None,TpmPpiBypassProvisionTypes, parent=self)
self.TpmSecurity = EnumTypeField(None,TpmSecurityTypes, parent=self)
self.TpmStatus = StringField("", parent=self)
self.TraceHubDebug = EnumTypeField(None,TraceHubDebugTypes, parent=self)
self.UefiBootSeq = StringField("", parent=self)
self.UefiComplianceVersion = StringField("", parent=self)
self.UefiPxeIpVersion = EnumTypeField(None,UefiPxeIpVersionTypes, parent=self)
self.UefiVariableAccess = EnumTypeField(None,UefiVariableAccessTypes, parent=self)
self.UncoreFrequency = EnumTypeField(None,UncoreFrequencyTypes, parent=self)
self.UnusedPcieClk = EnumTypeField(None,UnusedPcieClkTypes, parent=self)
self.Usb3Setting = EnumTypeField(None,Usb3SettingTypes, parent=self)
self.UsbManagedPort = EnumTypeField(UsbManagedPortTypes.On,UsbManagedPortTypes, parent=self)
self.UsbPorts = EnumTypeField(None,UsbPortsTypes, parent=self)
self.UserLcdStr = StringField("", parent=self)
self.VideoMem = StringField("", parent=self)
self.WorkloadProfile = EnumTypeField(None,WorkloadProfileTypes, parent=self)
self.WriteCache = EnumTypeField(None,WriteCacheTypes, parent=self)
self.WriteDataCrc = EnumTypeField(None,WriteDataCrcTypes, parent=self)
self.eSataPort1 = EnumTypeField(None,eSataPort1Types, parent=self)
self.eSataPort1Capacity = StringField("", parent=self)
self.eSataPort1DriveType = StringField("", parent=self)
self.eSataPort1Model = StringField("", parent=self)
self.commit(loading_from_scp)
| gpl-3.0 |
freedesktop-unofficial-mirror/telepathy__telepathy-ring | tools/glib-interfaces-gen.py | 14 | 6210 | #!/usr/bin/python
from sys import argv, stdout, stderr
import xml.dom.minidom
from libglibcodegen import NS_TP, get_docstring, \
get_descendant_text, get_by_path
class Generator(object):
def __init__(self, prefix, implfile, declfile, dom):
self.prefix = prefix + '_'
assert declfile.endswith('.h')
docfile = declfile[:-2] + '-gtk-doc.h'
self.impls = open(implfile, 'w')
self.decls = open(declfile, 'w')
self.docs = open(docfile, 'w')
self.spec = get_by_path(dom, "spec")[0]
def h(self, code):
self.decls.write(code.encode('utf-8'))
def c(self, code):
self.impls.write(code.encode('utf-8'))
def d(self, code):
self.docs.write(code.encode('utf-8'))
def __call__(self):
for f in self.h, self.c:
self.do_header(f)
self.do_body()
# Header
def do_header(self, f):
f('/* Generated from: ')
f(get_descendant_text(get_by_path(self.spec, 'title')))
version = get_by_path(self.spec, "version")
if version:
f(' version ' + get_descendant_text(version))
f('\n\n')
for copyright in get_by_path(self.spec, 'copyright'):
f(get_descendant_text(copyright))
f('\n')
f('\n')
f(get_descendant_text(get_by_path(self.spec, 'license')))
f(get_descendant_text(get_by_path(self.spec, 'docstring')))
f("""
*/
""")
# Body
def do_body(self):
for iface in self.spec.getElementsByTagName('interface'):
self.do_iface(iface)
def do_iface(self, iface):
parent_name = get_by_path(iface, '../@name')
self.d("""\
/**
* %(IFACE_DEFINE)s:
*
* The interface name "%(name)s"
*/
""" % {'IFACE_DEFINE' : (self.prefix + 'IFACE_' + \
parent_name).upper().replace('/', ''),
'name' : iface.getAttribute('name')})
self.h("""
#define %(IFACE_DEFINE)s \\
"%(name)s"
""" % {'IFACE_DEFINE' : (self.prefix + 'IFACE_' + \
parent_name).upper().replace('/', ''),
'name' : iface.getAttribute('name')})
self.d("""
/**
* %(IFACE_QUARK_DEFINE)s:
*
* Expands to a call to a function that returns a quark for the interface \
name "%(name)s"
*/
""" % {'IFACE_QUARK_DEFINE' : (self.prefix + 'IFACE_QUARK_' + \
parent_name).upper().replace('/', ''),
'iface_quark_func' : (self.prefix + 'iface_quark_' + \
parent_name).lower().replace('/', ''),
'name' : iface.getAttribute('name')})
self.h("""
#define %(IFACE_QUARK_DEFINE)s \\
(%(iface_quark_func)s ())
GQuark %(iface_quark_func)s (void);
""" % {'IFACE_QUARK_DEFINE' : (self.prefix + 'IFACE_QUARK_' + \
parent_name).upper().replace('/', ''),
'iface_quark_func' : (self.prefix + 'iface_quark_' + \
parent_name).lower().replace('/', ''),
'name' : iface.getAttribute('name')})
self.c("""\
GQuark
%(iface_quark_func)s (void)
{
static GQuark quark = 0;
if (G_UNLIKELY (quark == 0))
{
quark = g_quark_from_static_string ("%(name)s");
}
return quark;
}
""" % {'iface_quark_func' : (self.prefix + 'iface_quark_' + \
parent_name).lower().replace('/', ''),
'name' : iface.getAttribute('name')})
for prop in iface.getElementsByTagNameNS(None, 'property'):
self.d("""
/**
* %(IFACE_PREFIX)s_%(PROP_UC)s:
*
* The fully-qualified property name "%(name)s.%(prop)s"
*/
""" % {'IFACE_PREFIX' : (self.prefix + 'PROP_' + \
parent_name).upper().replace('/', ''),
'PROP_UC': prop.getAttributeNS(NS_TP, "name-for-bindings").upper(),
'name' : iface.getAttribute('name'),
'prop' : prop.getAttribute('name'),
})
self.h("""
#define %(IFACE_PREFIX)s_%(PROP_UC)s \\
"%(name)s.%(prop)s"
""" % {'IFACE_PREFIX' : (self.prefix + 'PROP_' + \
parent_name).upper().replace('/', ''),
'PROP_UC': prop.getAttributeNS(NS_TP, "name-for-bindings").upper(),
'name' : iface.getAttribute('name'),
'prop' : prop.getAttribute('name'),
})
for prop in iface.getElementsByTagNameNS(NS_TP, 'contact-attribute'):
self.d("""
/**
* %(TOKEN_PREFIX)s_%(TOKEN_UC)s:
*
* The fully-qualified contact attribute token name "%(name)s/%(prop)s"
*/
""" % {'TOKEN_PREFIX' : (self.prefix + 'TOKEN_' + \
parent_name).upper().replace('/', ''),
'TOKEN_UC': prop.getAttributeNS(None, "name").upper().replace("-", "_").replace(".", "_"),
'name' : iface.getAttribute('name'),
'prop' : prop.getAttribute('name'),
})
self.h("""
#define %(TOKEN_PREFIX)s_%(TOKEN_UC)s \\
"%(name)s/%(prop)s"
""" % {'TOKEN_PREFIX' : (self.prefix + 'TOKEN_' + \
parent_name).upper().replace('/', ''),
'TOKEN_UC': prop.getAttributeNS(None, "name").upper().replace("-", "_").replace(".", "_"),
'name' : iface.getAttribute('name'),
'prop' : prop.getAttribute('name'),
})
for prop in iface.getElementsByTagNameNS(NS_TP, 'hct'):
if (prop.getAttribute('is-family') != "yes"):
self.d("""
/**
* %(TOKEN_PREFIX)s_%(TOKEN_UC)s:
*
* The fully-qualified capability token name "%(name)s/%(prop)s"
*/
""" % {'TOKEN_PREFIX' : (self.prefix + 'TOKEN_' + \
parent_name).upper().replace('/', ''),
'TOKEN_UC': prop.getAttributeNS(None, "name").upper().replace("-", "_").replace(".", "_"),
'name' : iface.getAttribute('name'),
'prop' : prop.getAttribute('name'),
})
self.h("""
#define %(TOKEN_PREFIX)s_%(TOKEN_UC)s \\
"%(name)s/%(prop)s"
""" % {'TOKEN_PREFIX' : (self.prefix + 'TOKEN_' + \
parent_name).upper().replace('/', ''),
'TOKEN_UC': prop.getAttributeNS(None, "name").upper().replace("-", "_").replace(".", "_"),
'name' : iface.getAttribute('name'),
'prop' : prop.getAttribute('name'),
})
if __name__ == '__main__':
argv = argv[1:]
Generator(argv[0], argv[1], argv[2], xml.dom.minidom.parse(argv[3]))()
| lgpl-2.1 |
syci/website-odoo | website_menu_by_user_status/models/website_menu.py | 27 | 1576 | # -*- encoding: utf-8 -*-
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2013 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# 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 logging
_logger = logging.getLogger(__name__)
from openerp import models, fields
from openerp.tools.translate import _
class WebsiteMenu(models.Model):
"""Improve website.menu with adding booleans that drive
if the menu is displayed when the user is logger or not.
"""
_inherit = 'website.menu'
user_logged = fields.Boolean(
string="User Logged",
default=True,
help=_("If checked, "
"the menu will be displayed when the user is logged.")
)
user_not_logged = fields.Boolean(
string="User Not Logged",
default=True,
help=_("If checked, "
"the menu will be displayed when the user is not logged.")
)
| agpl-3.0 |
dr-bigfatnoob/quirk | language/mutator.py | 1 | 3748 | from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
__author__ = "bigfatnoob"
import random
from collections import OrderedDict
import numpy as np
from utils.lib import O
from technix.tech_utils import Point, three_others, choice, StarPoint
def default():
"""
Default settings.
:return:
"""
return O(
f=0.75,
cr=0.3,
)
class Mutator(O):
def __init__(self, model, **settings):
self.model = model
self.settings = default().update(**settings)
O.__init__(self)
def mutate_random(self, point, population):
"""
Just another random point
:param point:
:param population:
:return:
"""
other = Point(self.model.generate())
other.evaluate(self.model)
while other in population or other == point:
other = Point(self.model.generate())
other.evaluate(self.model)
return other
def mutate_binary(self, point, population):
two, three, four = three_others(point, population)
random_key = choice(self.model.decisions.keys())
mutant_decisions = OrderedDict()
for key in self.model.decisions.keys():
r = random.random()
if r < self.settings.cr or key == random_key:
mutant_decisions[key] = random.choice([two.decisions[key], three.decisions[key], four.decisions[key]])
else:
mutant_decisions[key] = point.decisions[key]
return Point(mutant_decisions)
def generate(self, presets=None, size=10):
pop = []
presets = {} if presets is None else presets
while len(pop) < size:
solutions = OrderedDict()
model = self.model
if model.decision_map:
ref = {key: np.random.choice(vals) for key, vals in model.decision_map.items()}
for key, decision in model.decisions.items():
if decision.key in presets:
solutions[key] = decision.options[presets[decision.key]].id
else:
solutions[key] = decision.options[ref[decision.key]].id
else:
for key, decision in model.decisions.items():
if key in presets:
solutions[key] = decision.options[presets[key]].id
else:
solutions[key] = np.random.choice(decision.options.values()).id
pop.append(Point(solutions))
return pop
def decision_ranker(self, best, rest):
best_size = len(best)
rest_size = len(rest)
p_best = best_size / (best_size + rest_size)
p_rest = rest_size / (best_size + rest_size)
decisions = []
best_sols = [self.model.get_solution(sol.decisions) for sol in best]
rest_sols = [self.model.get_solution(sol.decisions) for sol in rest]
for d_id, values in self.model.get_decisions().items():
# Implement Ranks
best_scores = {v: 0 for v in values}
for point in best_sols:
# best_scores[self.model.nodes[point.decisions[d_id]].label] += 1
best_scores[point[d_id]] += 1
rest_scores = {v: 0 for v in values}
for point in rest_sols:
rest_scores[point[d_id]] += 1
for key in best_scores.keys():
l_best = best_scores[key] * p_best / len(best_sols)
l_rest = rest_scores[key] * p_rest / len(rest_sols)
sup = 0 if l_best == l_rest == 0 else l_best ** 2 / (l_best + l_rest)
decisions.append(StarPoint(support=sup,
value=key,
name=d_id))
decisions.sort(key=lambda x: x.support, reverse=True)
ranked, aux = [], set()
for dec in decisions:
if dec.name not in aux:
ranked.append(dec)
aux.add(dec.name)
assert len(ranked) == len(self.model.get_decisions()), "Mismatch after sorting support"
return ranked
| unlicense |
MounirMesselmeni/django | tests/multiple_database/tests.py | 30 | 94187 | from __future__ import unicode_literals
import datetime
import pickle
from operator import attrgetter
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.db import DEFAULT_DB_ALIAS, connections, router, transaction
from django.db.models import signals
from django.db.utils import ConnectionRouter
from django.test import SimpleTestCase, TestCase, override_settings
from django.utils.six import StringIO
from .models import Book, Person, Pet, Review, UserProfile
from .routers import AuthRouter, TestRouter, WriteRouter
class QueryTestCase(TestCase):
multi_db = True
def test_db_selection(self):
"Check that querysets will use the default database by default"
self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS)
self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS)
self.assertEqual(Book.objects.using('other').db, 'other')
self.assertEqual(Book.objects.db_manager('other').db, 'other')
self.assertEqual(Book.objects.db_manager('other').all().db, 'other')
def test_default_creation(self):
"Objects created on the default database don't leak onto other databases"
# Create a book on the default database using create()
Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
# Create a book on the default database using a save
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save()
# Check that book exists on the default database, but not on other database
try:
Book.objects.get(title="Pro Django")
Book.objects.using('default').get(title="Pro Django")
except Book.DoesNotExist:
self.fail('"Pro Django" should exist on default database')
self.assertRaises(
Book.DoesNotExist,
Book.objects.using('other').get,
title="Pro Django"
)
try:
Book.objects.get(title="Dive into Python")
Book.objects.using('default').get(title="Dive into Python")
except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on default database')
self.assertRaises(
Book.DoesNotExist,
Book.objects.using('other').get,
title="Dive into Python"
)
def test_other_creation(self):
"Objects created on another database don't leak onto the default database"
# Create a book on the second database
Book.objects.using('other').create(title="Pro Django",
published=datetime.date(2008, 12, 16))
# Create a book on the default database using a save
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save(using='other')
# Check that book exists on the default database, but not on other database
try:
Book.objects.using('other').get(title="Pro Django")
except Book.DoesNotExist:
self.fail('"Pro Django" should exist on other database')
self.assertRaises(
Book.DoesNotExist,
Book.objects.get,
title="Pro Django"
)
self.assertRaises(
Book.DoesNotExist,
Book.objects.using('default').get,
title="Pro Django"
)
try:
Book.objects.using('other').get(title="Dive into Python")
except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on other database')
self.assertRaises(
Book.DoesNotExist,
Book.objects.get,
title="Dive into Python"
)
self.assertRaises(
Book.DoesNotExist,
Book.objects.using('default').get,
title="Dive into Python"
)
def test_refresh(self):
dive = Book()
dive.title = "Dive into Python"
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save(using='other')
dive.published = datetime.date(2009, 5, 4)
dive.save(using='other')
dive2 = Book.objects.using('other').get()
dive2.title = "Dive into Python (on default)"
dive2.save(using='default')
dive.refresh_from_db()
self.assertEqual(dive.title, "Dive into Python")
dive.refresh_from_db(using='default')
self.assertEqual(dive.title, "Dive into Python (on default)")
self.assertEqual(dive._state.db, "default")
def test_basic_queries(self):
"Queries are constrained to a single database"
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4))
self.assertEqual(dive.title, "Dive into Python")
self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published=datetime.date(2009, 5, 4))
dive = Book.objects.using('other').get(title__icontains="dive")
self.assertEqual(dive.title, "Dive into Python")
self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__icontains="dive")
dive = Book.objects.using('other').get(title__iexact="dive INTO python")
self.assertEqual(dive.title, "Dive into Python")
self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__iexact="dive INTO python")
dive = Book.objects.using('other').get(published__year=2009)
self.assertEqual(dive.title, "Dive into Python")
self.assertEqual(dive.published, datetime.date(2009, 5, 4))
self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published__year=2009)
years = Book.objects.using('other').dates('published', 'year')
self.assertEqual([o.year for o in years], [2009])
years = Book.objects.using('default').dates('published', 'year')
self.assertEqual([o.year for o in years], [])
months = Book.objects.using('other').dates('published', 'month')
self.assertEqual([o.month for o in months], [5])
months = Book.objects.using('default').dates('published', 'month')
self.assertEqual([o.month for o in months], [])
def test_m2m_separation(self):
"M2M fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Save the author relations
pro.authors.set([marty])
dive.authors.set([mark])
# Inspect the m2m tables directly.
# There should be 1 entry in each database
self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
# Check that queries work across m2m joins
self.assertEqual(
list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
['Pro Django']
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
[]
)
self.assertEqual(
list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
[]
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
['Dive into Python']
)
# Reget the objects to clear caches
dive = Book.objects.using('other').get(title="Dive into Python")
mark = Person.objects.using('other').get(name="Mark Pilgrim")
# Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(list(dive.authors.all().values_list('name', flat=True)),
['Mark Pilgrim'])
self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)),
['Dive into Python'])
def test_m2m_forward_operations(self):
"M2M forward manipulations are all constrained to a single DB"
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Save the author relations
dive.authors.set([mark])
# Add a second author
john = Person.objects.using('other').create(name="John Smith")
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
[]
)
dive.authors.add(john)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
['Dive into Python']
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
['Dive into Python']
)
# Remove the second author
dive.authors.remove(john)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
['Dive into Python']
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
[]
)
# Clear all authors
dive.authors.clear()
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
[]
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
[]
)
# Create an author through the m2m interface
dive.authors.create(name='Jane Brown')
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
[]
)
self.assertEqual(
list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)),
['Dive into Python']
)
def test_m2m_reverse_operations(self):
"M2M reverse manipulations are all constrained to a single DB"
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Save the author relations
dive.authors.set([mark])
# Create a second book on the other database
grease = Book.objects.using('other').create(title="Greasemonkey Hacks",
published=datetime.date(2005, 11, 1))
# Add a books to the m2m
mark.book_set.add(grease)
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
['Mark Pilgrim']
)
self.assertEqual(
list(
Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)
),
['Mark Pilgrim']
)
# Remove a book from the m2m
mark.book_set.remove(grease)
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
['Mark Pilgrim']
)
self.assertEqual(
list(
Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)
),
[]
)
# Clear the books associated with mark
mark.book_set.clear()
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(
Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)
),
[]
)
# Create a book through the m2m interface
mark.book_set.create(title="Dive into HTML5", published=datetime.date(2020, 1, 1))
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)),
['Mark Pilgrim']
)
def test_m2m_cross_database_protection(self):
"Operations that involve sharing M2M objects across databases raise an error"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Set a foreign key set with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.edited.set([pro, dive])
# Add to an m2m with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.book_set.add(dive)
# Set a m2m with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.book_set.set([pro, dive])
# Add to a reverse m2m with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='other'):
dive.authors.add(marty)
# Set a reverse m2m with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='other'):
dive.authors.set([mark, marty])
def test_m2m_deletion(self):
"Cascaded deletions of m2m relations issue queries on the right database"
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
dive.authors.set([mark])
# Check the initial state
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
self.assertEqual(Person.objects.using('other').count(), 1)
self.assertEqual(Book.objects.using('other').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
# Delete the object on the other database
dive.delete(using='other')
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
# The person still exists ...
self.assertEqual(Person.objects.using('other').count(), 1)
# ... but the book has been deleted
self.assertEqual(Book.objects.using('other').count(), 0)
# ... and the relationship object has also been deleted.
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Now try deletion in the reverse direction. Set up the relation again
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
dive.authors.set([mark])
# Check the initial state
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
self.assertEqual(Person.objects.using('other').count(), 1)
self.assertEqual(Book.objects.using('other').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
# Delete the object on the other database
mark.delete(using='other')
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
# The person has been deleted ...
self.assertEqual(Person.objects.using('other').count(), 0)
# ... but the book still exists
self.assertEqual(Book.objects.using('other').count(), 1)
# ... and the relationship object has been deleted.
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
def test_foreign_key_separation(self):
"FK fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
george = Person.objects.create(name="George Vilches")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
chris = Person.objects.using('other').create(name="Chris Mills")
# Save the author's favorite books
pro.editor = george
pro.save()
dive.editor = chris
dive.save()
pro = Book.objects.using('default').get(title="Pro Django")
self.assertEqual(pro.editor.name, "George Vilches")
dive = Book.objects.using('other').get(title="Dive into Python")
self.assertEqual(dive.editor.name, "Chris Mills")
# Check that queries work across foreign key joins
self.assertEqual(
list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)),
['George Vilches']
)
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(
Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
[]
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
['Chris Mills']
)
# Reget the objects to clear caches
chris = Person.objects.using('other').get(name="Chris Mills")
dive = Book.objects.using('other').get(title="Dive into Python")
# Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(list(chris.edited.values_list('title', flat=True)),
['Dive into Python'])
def test_foreign_key_reverse_operations(self):
"FK reverse manipulations are all constrained to a single DB"
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
chris = Person.objects.using('other').create(name="Chris Mills")
# Save the author relations
dive.editor = chris
dive.save()
# Add a second book edited by chris
html5 = Book.objects.using('other').create(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[]
)
chris.edited.add(html5)
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
['Chris Mills']
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
['Chris Mills']
)
# Remove the second editor
chris.edited.remove(html5)
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
['Chris Mills']
)
# Clear all edited books
chris.edited.clear()
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
[]
)
# Create an author through the m2m interface
chris.edited.create(title='Dive into Water', published=datetime.date(2010, 3, 15))
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[]
)
self.assertEqual(
list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)),
['Chris Mills']
)
self.assertEqual(
list(
Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
),
[]
)
def test_foreign_key_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
# Set a foreign key with an object from a different database
with self.assertRaises(ValueError):
dive.editor = marty
# Set a foreign key set with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.edited.set([pro, dive])
# Add to a foreign key set with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='default'):
marty.edited.add(dive)
def test_foreign_key_deletion(self):
"Cascaded deletions of Foreign Key relations issue queries on the right database"
mark = Person.objects.using('other').create(name="Mark Pilgrim")
Pet.objects.using('other').create(name="Fido", owner=mark)
# Check the initial state
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Pet.objects.using('default').count(), 0)
self.assertEqual(Person.objects.using('other').count(), 1)
self.assertEqual(Pet.objects.using('other').count(), 1)
# Delete the person object, which will cascade onto the pet
mark.delete(using='other')
self.assertEqual(Person.objects.using('default').count(), 0)
self.assertEqual(Pet.objects.using('default').count(), 0)
# Both the pet and the person have been deleted from the right database
self.assertEqual(Person.objects.using('other').count(), 0)
self.assertEqual(Pet.objects.using('other').count(), 0)
def test_foreign_key_validation(self):
"ForeignKey.validate() uses the correct database"
mickey = Person.objects.using('other').create(name="Mickey")
pluto = Pet.objects.using('other').create(name="Pluto", owner=mickey)
self.assertIsNone(pluto.full_clean())
def test_o2o_separation(self):
"OneToOne fields are constrained to a single database"
# Create a user and profile on the default database
alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com')
alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
# Create a user and profile on the other database
bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')
# Retrieve related objects; queries should be database constrained
alice = User.objects.using('default').get(username="alice")
self.assertEqual(alice.userprofile.flavor, "chocolate")
bob = User.objects.using('other').get(username="bob")
self.assertEqual(bob.userprofile.flavor, "crunchy frog")
# Check that queries work across joins
self.assertEqual(
list(
User.objects.using('default')
.filter(userprofile__flavor='chocolate').values_list('username', flat=True)
),
['alice']
)
self.assertEqual(
list(
User.objects.using('other')
.filter(userprofile__flavor='chocolate').values_list('username', flat=True)
),
[]
)
self.assertEqual(
list(
User.objects.using('default')
.filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)
),
[]
)
self.assertEqual(
list(
User.objects.using('other')
.filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)
),
['bob']
)
# Reget the objects to clear caches
alice_profile = UserProfile.objects.using('default').get(flavor='chocolate')
bob_profile = UserProfile.objects.using('other').get(flavor='crunchy frog')
# Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(alice_profile.user.username, 'alice')
self.assertEqual(bob_profile.user.username, 'bob')
def test_o2o_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error"
# Create a user and profile on the default database
alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com')
# Create a user and profile on the other database
bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
# Set a one-to-one relation with an object from a different database
alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
with self.assertRaises(ValueError):
bob.userprofile = alice_profile
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')
new_bob_profile = UserProfile(flavor="spring surprise")
# assigning a profile requires an explicit pk as the object isn't saved
charlie = User(pk=51, username='charlie', email='charlie@example.com')
charlie.set_unusable_password()
# initially, no db assigned
self.assertEqual(new_bob_profile._state.db, None)
self.assertEqual(charlie._state.db, None)
# old object comes from 'other', so the new object is set to use 'other'...
new_bob_profile.user = bob
charlie.userprofile = bob_profile
self.assertEqual(new_bob_profile._state.db, 'other')
self.assertEqual(charlie._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)),
['bob'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog'])
# When saved (no using required), new objects goes to 'other'
charlie.save()
bob_profile.save()
new_bob_profile.save()
self.assertEqual(list(User.objects.using('default').values_list('username', flat=True)),
['alice'])
self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)),
['bob', 'charlie'])
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)),
['chocolate'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog', 'spring surprise'])
# This also works if you assign the O2O relation in the constructor
denise = User.objects.db_manager('other').create_user('denise', 'denise@example.com')
denise_profile = UserProfile(flavor="tofu", user=denise)
self.assertEqual(denise_profile._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)),
['chocolate'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog', 'spring surprise'])
# When saved, the new profile goes to 'other'
denise_profile.save()
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)),
['chocolate'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog', 'spring surprise', 'tofu'])
def test_generic_key_separation(self):
"Generic fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
review1 = Review.objects.create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
review1 = Review.objects.using('default').get(source="Python Monthly")
self.assertEqual(review1.content_object.title, "Pro Django")
review2 = Review.objects.using('other').get(source="Python Weekly")
self.assertEqual(review2.content_object.title, "Dive into Python")
# Reget the objects to clear caches
dive = Book.objects.using('other').get(title="Dive into Python")
# Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)),
['Python Weekly'])
def test_generic_key_reverse_operations(self):
"Generic reverse manipulations are all constrained to a single DB"
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
temp = Book.objects.using('other').create(title="Temp",
published=datetime.date(2009, 5, 4))
review1 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp)
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Weekly']
)
# Add a second review
dive.reviews.add(review2)
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Monthly', 'Python Weekly']
)
# Remove the second author
dive.reviews.remove(review1)
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Monthly']
)
# Clear all reviews
dive.reviews.clear()
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
# Create an author through the generic interface
dive.reviews.create(source='Python Daily')
self.assertEqual(
list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[]
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Daily']
)
def test_generic_key_cross_database_protection(self):
"Operations that involve sharing generic key objects across databases raise an error"
# Create a book and author on the default database
pro = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
review1 = Review.objects.create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
Review.objects.using('other').create(source="Python Weekly", content_object=dive)
# Set a foreign key with an object from a different database
with self.assertRaises(ValueError):
review1.content_object = dive
# Add to a foreign key set with an object from a different database
with self.assertRaises(ValueError):
with transaction.atomic(using='other'):
dive.reviews.add(review1)
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
review3 = Review(source="Python Daily")
# initially, no db assigned
self.assertEqual(review3._state.db, None)
# Dive comes from 'other', so review3 is set to use 'other'...
review3.content_object = dive
self.assertEqual(review3._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(
list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
['Python Monthly']
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Weekly']
)
# When saved, John goes to 'other'
review3.save()
self.assertEqual(
list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
['Python Monthly']
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Daily', 'Python Weekly']
)
def test_generic_key_deletion(self):
"Cascaded deletions of Generic Key relations issue queries on the right database"
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
Review.objects.using('other').create(source="Python Weekly", content_object=dive)
# Check the initial state
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Review.objects.using('default').count(), 0)
self.assertEqual(Book.objects.using('other').count(), 1)
self.assertEqual(Review.objects.using('other').count(), 1)
# Delete the Book object, which will cascade onto the pet
dive.delete(using='other')
self.assertEqual(Book.objects.using('default').count(), 0)
self.assertEqual(Review.objects.using('default').count(), 0)
# Both the pet and the person have been deleted from the right database
self.assertEqual(Book.objects.using('other').count(), 0)
self.assertEqual(Review.objects.using('other').count(), 0)
def test_ordering(self):
"get_next_by_XXX commands stick to a single database"
Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
learn = Book.objects.using('other').create(title="Learning Python",
published=datetime.date(2008, 7, 16))
self.assertEqual(learn.get_next_by_published().title, "Dive into Python")
self.assertEqual(dive.get_previous_by_published().title, "Learning Python")
def test_raw(self):
"test the raw() method across databases"
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
val = Book.objects.db_manager("other").raw('SELECT id FROM multiple_database_book')
self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
val = Book.objects.raw('SELECT id FROM multiple_database_book').using('other')
self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
def test_select_related(self):
"Database assignment is retained if an object is retrieved with select_related()"
# Create a book and author on the other database
mark = Person.objects.using('other').create(name="Mark Pilgrim")
Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4),
editor=mark)
# Retrieve the Person using select_related()
book = Book.objects.using('other').select_related('editor').get(title="Dive into Python")
# The editor instance should have a db state
self.assertEqual(book.editor._state.db, 'other')
def test_subquery(self):
"""Make sure as_sql works with subqueries and primary/replica."""
sub = Person.objects.using('other').filter(name='fff')
qs = Book.objects.filter(editor__in=sub)
# When you call __str__ on the query object, it doesn't know about using
# so it falls back to the default. If the subquery explicitly uses a
# different database, an error should be raised.
self.assertRaises(ValueError, str, qs.query)
# Evaluating the query shouldn't work, either
with self.assertRaises(ValueError):
for obj in qs:
pass
def test_related_manager(self):
"Related managers return managers, not querysets"
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# extra_arg is removed by the BookManager's implementation of
# create(); but the BookManager's implementation won't get called
# unless edited returns a Manager, not a queryset
mark.book_set.create(title="Dive into Python",
published=datetime.date(2009, 5, 4),
extra_arg=True)
mark.book_set.get_or_create(title="Dive into Python",
published=datetime.date(2009, 5, 4),
extra_arg=True)
mark.edited.create(title="Dive into Water",
published=datetime.date(2009, 5, 4),
extra_arg=True)
mark.edited.get_or_create(title="Dive into Water",
published=datetime.date(2009, 5, 4),
extra_arg=True)
class ConnectionRouterTestCase(SimpleTestCase):
@override_settings(DATABASE_ROUTERS=[
'multiple_database.tests.TestRouter',
'multiple_database.tests.WriteRouter'])
def test_router_init_default(self):
connection_router = ConnectionRouter()
self.assertListEqual([r.__class__.__name__ for r in connection_router.routers],
['TestRouter', 'WriteRouter'])
def test_router_init_arg(self):
connection_router = ConnectionRouter([
'multiple_database.tests.TestRouter',
'multiple_database.tests.WriteRouter'
])
self.assertListEqual([r.__class__.__name__ for r in connection_router.routers],
['TestRouter', 'WriteRouter'])
# Init with instances instead of strings
connection_router = ConnectionRouter([TestRouter(), WriteRouter()])
self.assertListEqual([r.__class__.__name__ for r in connection_router.routers],
['TestRouter', 'WriteRouter'])
# Make the 'other' database appear to be a replica of the 'default'
@override_settings(DATABASE_ROUTERS=[TestRouter()])
class RouterTestCase(TestCase):
multi_db = True
def test_db_selection(self):
"Check that querysets obey the router for db suggestions"
self.assertEqual(Book.objects.db, 'other')
self.assertEqual(Book.objects.all().db, 'other')
self.assertEqual(Book.objects.using('default').db, 'default')
self.assertEqual(Book.objects.db_manager('default').db, 'default')
self.assertEqual(Book.objects.db_manager('default').all().db, 'default')
def test_migrate_selection(self):
"Synchronization behavior is predictable"
self.assertTrue(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
self.assertTrue(router.allow_migrate_model('other', User))
self.assertTrue(router.allow_migrate_model('other', Book))
with override_settings(DATABASE_ROUTERS=[TestRouter(), AuthRouter()]):
# Add the auth router to the chain. TestRouter is a universal
# synchronizer, so it should have no effect.
self.assertTrue(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
self.assertTrue(router.allow_migrate_model('other', User))
self.assertTrue(router.allow_migrate_model('other', Book))
with override_settings(DATABASE_ROUTERS=[AuthRouter(), TestRouter()]):
# Now check what happens if the router order is reversed.
self.assertFalse(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
self.assertTrue(router.allow_migrate_model('other', User))
self.assertTrue(router.allow_migrate_model('other', Book))
def test_partial_router(self):
"A router can choose to implement a subset of methods"
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
# First check the baseline behavior.
self.assertEqual(router.db_for_read(User), 'other')
self.assertEqual(router.db_for_read(Book), 'other')
self.assertEqual(router.db_for_write(User), 'default')
self.assertEqual(router.db_for_write(Book), 'default')
self.assertTrue(router.allow_relation(dive, dive))
self.assertTrue(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
with override_settings(DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()]):
self.assertEqual(router.db_for_read(User), 'default')
self.assertEqual(router.db_for_read(Book), 'other')
self.assertEqual(router.db_for_write(User), 'writer')
self.assertEqual(router.db_for_write(Book), 'writer')
self.assertTrue(router.allow_relation(dive, dive))
self.assertFalse(router.allow_migrate_model('default', User))
self.assertTrue(router.allow_migrate_model('default', Book))
def test_database_routing(self):
marty = Person.objects.using('default').create(name="Marty Alchin")
pro = Book.objects.using('default').create(title="Pro Django",
published=datetime.date(2008, 12, 16),
editor=marty)
pro.authors.set([marty])
# Create a book and author on the other database
Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
# An update query will be routed to the default database
Book.objects.filter(title='Pro Django').update(pages=200)
with self.assertRaises(Book.DoesNotExist):
# By default, the get query will be directed to 'other'
Book.objects.get(title='Pro Django')
# But the same query issued explicitly at a database will work.
pro = Book.objects.using('default').get(title='Pro Django')
# Check that the update worked.
self.assertEqual(pro.pages, 200)
# An update query with an explicit using clause will be routed
# to the requested database.
Book.objects.using('other').filter(title='Dive into Python').update(pages=300)
self.assertEqual(Book.objects.get(title='Dive into Python').pages, 300)
# Related object queries stick to the same database
# as the original object, regardless of the router
self.assertEqual(list(pro.authors.values_list('name', flat=True)), ['Marty Alchin'])
self.assertEqual(pro.editor.name, 'Marty Alchin')
# get_or_create is a special case. The get needs to be targeted at
# the write database in order to avoid potential transaction
# consistency problems
book, created = Book.objects.get_or_create(title="Pro Django")
self.assertFalse(created)
book, created = Book.objects.get_or_create(title="Dive Into Python",
defaults={'published': datetime.date(2009, 5, 4)})
self.assertTrue(created)
# Check the head count of objects
self.assertEqual(Book.objects.using('default').count(), 2)
self.assertEqual(Book.objects.using('other').count(), 1)
# If a database isn't specified, the read database is used
self.assertEqual(Book.objects.count(), 1)
# A delete query will also be routed to the default database
Book.objects.filter(pages__gt=150).delete()
# The default database has lost the book.
self.assertEqual(Book.objects.using('default').count(), 1)
self.assertEqual(Book.objects.using('other').count(), 1)
def test_invalid_set_foreign_key_assignment(self):
marty = Person.objects.using('default').create(name="Marty Alchin")
dive = Book.objects.using('other').create(
title="Dive into Python",
published=datetime.date(2009, 5, 4),
)
# Set a foreign key set with an object from a different database
msg = "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the object first."
with self.assertRaisesMessage(ValueError, msg):
marty.edited.set([dive])
def test_foreign_key_cross_database_protection(self):
"Foreign keys can cross databases if they two databases have a common source"
# Create a book and author on the default database
pro = Book.objects.using('default').create(title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.using('default').create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Set a foreign key with an object from a different database
try:
dive.editor = marty
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Database assignments of original objects haven't changed...
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# ... but they will when the affected object is saved.
dive.save()
self.assertEqual(dive._state.db, 'default')
# ...and the source database now has a copy of any object saved
try:
Book.objects.using('default').get(title='Dive into Python').delete()
except Book.DoesNotExist:
self.fail('Source database should have a copy of saved object')
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using('other').get(title='Dive into Python')
self.assertEqual(dive._state.db, 'other')
# Set a foreign key set with an object from a different database
try:
marty.edited.set([pro, dive], bulk=False)
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Assignment implies a save, so database assignments of original objects have changed...
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'default')
self.assertEqual(mark._state.db, 'other')
# ...and the source database now has a copy of any object saved
try:
Book.objects.using('default').get(title='Dive into Python').delete()
except Book.DoesNotExist:
self.fail('Source database should have a copy of saved object')
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using('other').get(title='Dive into Python')
self.assertEqual(dive._state.db, 'other')
# Add to a foreign key set with an object from a different database
try:
marty.edited.add(dive, bulk=False)
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Add implies a save, so database assignments of original objects have changed...
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'default')
self.assertEqual(mark._state.db, 'other')
# ...and the source database now has a copy of any object saved
try:
Book.objects.using('default').get(title='Dive into Python').delete()
except Book.DoesNotExist:
self.fail('Source database should have a copy of saved object')
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using('other').get(title='Dive into Python')
# If you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
chris = Person(name="Chris Mills")
html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
# initially, no db assigned
self.assertEqual(chris._state.db, None)
self.assertEqual(html5._state.db, None)
# old object comes from 'other', so the new object is set to use the
# source of 'other'...
self.assertEqual(dive._state.db, 'other')
chris.save()
dive.editor = chris
html5.editor = mark
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
self.assertEqual(chris._state.db, 'default')
self.assertEqual(html5._state.db, 'default')
# This also works if you assign the FK in the constructor
water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark)
self.assertEqual(water._state.db, 'default')
# For the remainder of this test, create a copy of 'mark' in the
# 'default' database to prevent integrity errors on backends that
# don't defer constraints checks until the end of the transaction
mark.save(using='default')
# This moved 'mark' in the 'default' database, move it back in 'other'
mark.save(using='other')
self.assertEqual(mark._state.db, 'other')
# If you create an object through a FK relation, it will be
# written to the write database, even if the original object
# was on the read database
cheesecake = mark.edited.create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15))
self.assertEqual(cheesecake._state.db, 'default')
# Same goes for get_or_create, regardless of whether getting or creating
cheesecake, created = mark.edited.get_or_create(
title='Dive into Cheesecake',
published=datetime.date(2010, 3, 15),
)
self.assertEqual(cheesecake._state.db, 'default')
puddles, created = mark.edited.get_or_create(title='Dive into Puddles', published=datetime.date(2010, 3, 15))
self.assertEqual(puddles._state.db, 'default')
def test_m2m_cross_database_protection(self):
"M2M relations can cross databases if the database share a source"
# Create books and authors on the inverse to the usual database
pro = Book.objects.using('other').create(pk=1, title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
dive = Book.objects.using('default').create(pk=2, title="Dive into Python",
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('default').create(pk=2, name="Mark Pilgrim")
# Now save back onto the usual database.
# This simulates primary/replica - the objects exist on both database,
# but the _state.db is as it is for all other tests.
pro.save(using='default')
marty.save(using='default')
dive.save(using='other')
mark.save(using='other')
# Check that we have 2 of both types of object on both databases
self.assertEqual(Book.objects.using('default').count(), 2)
self.assertEqual(Book.objects.using('other').count(), 2)
self.assertEqual(Person.objects.using('default').count(), 2)
self.assertEqual(Person.objects.using('other').count(), 2)
# Set a m2m set with an object from a different database
try:
marty.book_set.set([pro, dive])
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Database assignments don't change
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using('default').count(), 2)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Reset relations
Book.authors.through.objects.using('default').delete()
# Add to an m2m with an object from a different database
try:
marty.book_set.add(dive)
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Database assignments don't change
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Reset relations
Book.authors.through.objects.using('default').delete()
# Set a reverse m2m with an object from a different database
try:
dive.authors.set([mark, marty])
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Database assignments don't change
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using('default').count(), 2)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Reset relations
Book.authors.through.objects.using('default').delete()
self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Add to a reverse m2m with an object from a different database
try:
dive.authors.add(marty)
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Database assignments don't change
self.assertEqual(marty._state.db, 'default')
self.assertEqual(pro._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(mark._state.db, 'other')
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# If you create an object through a M2M relation, it will be
# written to the write database, even if the original object
# was on the read database
alice = dive.authors.create(name='Alice')
self.assertEqual(alice._state.db, 'default')
# Same goes for get_or_create, regardless of whether getting or creating
alice, created = dive.authors.get_or_create(name='Alice')
self.assertEqual(alice._state.db, 'default')
bob, created = dive.authors.get_or_create(name='Bob')
self.assertEqual(bob._state.db, 'default')
def test_o2o_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error"
# Create a user and profile on the default database
alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com')
# Create a user and profile on the other database
bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
# Set a one-to-one relation with an object from a different database
alice_profile = UserProfile.objects.create(user=alice, flavor='chocolate')
try:
bob.userprofile = alice_profile
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Database assignments of original objects haven't changed...
self.assertEqual(alice._state.db, 'default')
self.assertEqual(alice_profile._state.db, 'default')
self.assertEqual(bob._state.db, 'other')
# ... but they will when the affected object is saved.
bob.save()
self.assertEqual(bob._state.db, 'default')
def test_generic_key_cross_database_protection(self):
"Generic Key operations can span databases if they share a source"
# Create a book and author on the default database
pro = Book.objects.using(
'default').create(title="Pro Django", published=datetime.date(2008, 12, 16))
review1 = Review.objects.using(
'default').create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using(
'other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
review2 = Review.objects.using(
'other').create(source="Python Weekly", content_object=dive)
# Set a generic foreign key with an object from a different database
try:
review1.content_object = dive
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Database assignments of original objects haven't changed...
self.assertEqual(pro._state.db, 'default')
self.assertEqual(review1._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(review2._state.db, 'other')
# ... but they will when the affected object is saved.
dive.save()
self.assertEqual(review1._state.db, 'default')
self.assertEqual(dive._state.db, 'default')
# ...and the source database now has a copy of any object saved
try:
Book.objects.using('default').get(title='Dive into Python').delete()
except Book.DoesNotExist:
self.fail('Source database should have a copy of saved object')
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using('other').get(title='Dive into Python')
self.assertEqual(dive._state.db, 'other')
# Add to a generic foreign key set with an object from a different database
try:
dive.reviews.add(review1)
except ValueError:
self.fail("Assignment across primary/replica databases with a common source should be ok")
# Database assignments of original objects haven't changed...
self.assertEqual(pro._state.db, 'default')
self.assertEqual(review1._state.db, 'default')
self.assertEqual(dive._state.db, 'other')
self.assertEqual(review2._state.db, 'other')
# ... but they will when the affected object is saved.
dive.save()
self.assertEqual(dive._state.db, 'default')
# ...and the source database now has a copy of any object saved
try:
Book.objects.using('default').get(title='Dive into Python').delete()
except Book.DoesNotExist:
self.fail('Source database should have a copy of saved object')
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
review3 = Review(source="Python Daily")
# initially, no db assigned
self.assertEqual(review3._state.db, None)
# Dive comes from 'other', so review3 is set to use the source of 'other'...
review3.content_object = dive
self.assertEqual(review3._state.db, 'default')
# If you create an object through a M2M relation, it will be
# written to the write database, even if the original object
# was on the read database
dive = Book.objects.using('other').get(title='Dive into Python')
nyt = dive.reviews.create(source="New York Times", content_object=dive)
self.assertEqual(nyt._state.db, 'default')
def test_m2m_managers(self):
"M2M relations are represented by managers, and can be controlled like managers"
pro = Book.objects.using('other').create(pk=1, title="Pro Django",
published=datetime.date(2008, 12, 16))
marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
self.assertEqual(pro.authors.db, 'other')
self.assertEqual(pro.authors.db_manager('default').db, 'default')
self.assertEqual(pro.authors.db_manager('default').all().db, 'default')
self.assertEqual(marty.book_set.db, 'other')
self.assertEqual(marty.book_set.db_manager('default').db, 'default')
self.assertEqual(marty.book_set.db_manager('default').all().db, 'default')
def test_foreign_key_managers(self):
"FK reverse relations are represented by managers, and can be controlled like managers"
marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
Book.objects.using('other').create(pk=1, title="Pro Django",
published=datetime.date(2008, 12, 16),
editor=marty)
self.assertEqual(marty.edited.db, 'other')
self.assertEqual(marty.edited.db_manager('default').db, 'default')
self.assertEqual(marty.edited.db_manager('default').all().db, 'default')
def test_generic_key_managers(self):
"Generic key relations are represented by managers, and can be controlled like managers"
pro = Book.objects.using('other').create(title="Pro Django",
published=datetime.date(2008, 12, 16))
Review.objects.using('other').create(source="Python Monthly",
content_object=pro)
self.assertEqual(pro.reviews.db, 'other')
self.assertEqual(pro.reviews.db_manager('default').db, 'default')
self.assertEqual(pro.reviews.db_manager('default').all().db, 'default')
def test_subquery(self):
"""Make sure as_sql works with subqueries and primary/replica."""
# Create a book and author on the other database
mark = Person.objects.using('other').create(name="Mark Pilgrim")
Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4),
editor=mark)
sub = Person.objects.filter(name='Mark Pilgrim')
qs = Book.objects.filter(editor__in=sub)
# When you call __str__ on the query object, it doesn't know about using
# so it falls back to the default. Don't let routing instructions
# force the subquery to an incompatible database.
str(qs.query)
# If you evaluate the query, it should work, running on 'other'
self.assertEqual(list(qs.values_list('title', flat=True)), ['Dive into Python'])
def test_deferred_models(self):
mark_def = Person.objects.using('default').create(name="Mark Pilgrim")
mark_other = Person.objects.using('other').create(name="Mark Pilgrim")
orig_b = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4),
editor=mark_other)
b = Book.objects.using('other').only('title').get(pk=orig_b.pk)
self.assertEqual(b.published, datetime.date(2009, 5, 4))
b = Book.objects.using('other').only('title').get(pk=orig_b.pk)
b.editor = mark_def
b.save(using='default')
self.assertEqual(Book.objects.using('default').get(pk=b.pk).published,
datetime.date(2009, 5, 4))
@override_settings(DATABASE_ROUTERS=[AuthRouter()])
class AuthTestCase(TestCase):
multi_db = True
def test_auth_manager(self):
"The methods on the auth manager obey database hints"
# Create one user using default allocation policy
User.objects.create_user('alice', 'alice@example.com')
# Create another user, explicitly specifying the database
User.objects.db_manager('default').create_user('bob', 'bob@example.com')
# The second user only exists on the other database
alice = User.objects.using('other').get(username='alice')
self.assertEqual(alice.username, 'alice')
self.assertEqual(alice._state.db, 'other')
self.assertRaises(User.DoesNotExist, User.objects.using('default').get, username='alice')
# The second user only exists on the default database
bob = User.objects.using('default').get(username='bob')
self.assertEqual(bob.username, 'bob')
self.assertEqual(bob._state.db, 'default')
self.assertRaises(User.DoesNotExist, User.objects.using('other').get, username='bob')
# That is... there is one user on each database
self.assertEqual(User.objects.using('default').count(), 1)
self.assertEqual(User.objects.using('other').count(), 1)
def test_dumpdata(self):
"Check that dumpdata honors allow_migrate restrictions on the router"
User.objects.create_user('alice', 'alice@example.com')
User.objects.db_manager('default').create_user('bob', 'bob@example.com')
# Check that dumping the default database doesn't try to include auth
# because allow_migrate prohibits auth on default
new_io = StringIO()
management.call_command('dumpdata', 'auth', format='json', database='default', stdout=new_io)
command_output = new_io.getvalue().strip()
self.assertEqual(command_output, '[]')
# Check that dumping the other database does include auth
new_io = StringIO()
management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io)
command_output = new_io.getvalue().strip()
self.assertIn('"email": "alice@example.com"', command_output)
class AntiPetRouter(object):
# A router that only expresses an opinion on migrate,
# passing pets to the 'other' database
def allow_migrate(self, db, app_label, model_name=None, **hints):
if db == 'other':
return model_name == 'pet'
else:
return model_name != 'pet'
class FixtureTestCase(TestCase):
multi_db = True
fixtures = ['multidb-common', 'multidb']
@override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
def test_fixture_loading(self):
"Multi-db fixtures are loaded correctly"
# Check that "Pro Django" exists on the default database, but not on other database
try:
Book.objects.get(title="Pro Django")
Book.objects.using('default').get(title="Pro Django")
except Book.DoesNotExist:
self.fail('"Pro Django" should exist on default database')
self.assertRaises(
Book.DoesNotExist,
Book.objects.using('other').get,
title="Pro Django"
)
# Check that "Dive into Python" exists on the default database, but not on other database
try:
Book.objects.using('other').get(title="Dive into Python")
except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on other database')
self.assertRaises(
Book.DoesNotExist,
Book.objects.get,
title="Dive into Python"
)
self.assertRaises(
Book.DoesNotExist,
Book.objects.using('default').get,
title="Dive into Python"
)
# Check that "Definitive Guide" exists on the both databases
try:
Book.objects.get(title="The Definitive Guide to Django")
Book.objects.using('default').get(title="The Definitive Guide to Django")
Book.objects.using('other').get(title="The Definitive Guide to Django")
except Book.DoesNotExist:
self.fail('"The Definitive Guide to Django" should exist on both databases')
@override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
def test_pseudo_empty_fixtures(self):
"""
A fixture can contain entries, but lead to nothing in the database;
this shouldn't raise an error (#14068).
"""
new_io = StringIO()
management.call_command('loaddata', 'pets', stdout=new_io, stderr=new_io)
command_output = new_io.getvalue().strip()
# No objects will actually be loaded
self.assertEqual(command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)")
class PickleQuerySetTestCase(TestCase):
multi_db = True
def test_pickling(self):
for db in connections:
Book.objects.using(db).create(title='Dive into Python', published=datetime.date(2009, 5, 4))
qs = Book.objects.all()
self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db)
class DatabaseReceiver(object):
"""
Used in the tests for the database argument in signals (#13552)
"""
def __call__(self, signal, sender, **kwargs):
self._database = kwargs['using']
class WriteToOtherRouter(object):
"""
A router that sends all writes to the other database.
"""
def db_for_write(self, model, **hints):
return "other"
class SignalTests(TestCase):
multi_db = True
def override_router(self):
return override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()])
def test_database_arg_save_and_delete(self):
"""
Tests that the pre/post_save signal contains the correct database.
(#13552)
"""
# Make some signal receivers
pre_save_receiver = DatabaseReceiver()
post_save_receiver = DatabaseReceiver()
pre_delete_receiver = DatabaseReceiver()
post_delete_receiver = DatabaseReceiver()
# Make model and connect receivers
signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
signals.post_save.connect(sender=Person, receiver=post_save_receiver)
signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
p = Person.objects.create(name='Darth Vader')
# Save and test receivers got calls
p.save()
self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
# Delete, and test
p.delete()
self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
# Save again to a different database
p.save(using="other")
self.assertEqual(pre_save_receiver._database, "other")
self.assertEqual(post_save_receiver._database, "other")
# Delete, and test
p.delete(using="other")
self.assertEqual(pre_delete_receiver._database, "other")
self.assertEqual(post_delete_receiver._database, "other")
signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver)
def test_database_arg_m2m(self):
"""
Test that the m2m_changed signal has a correct database arg (#13552)
"""
# Make a receiver
receiver = DatabaseReceiver()
# Connect it
signals.m2m_changed.connect(receiver=receiver)
# Create the models that will be used for the tests
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
p = Person.objects.create(name="Marty Alchin")
# Create a copy of the models on the 'other' database to prevent
# integrity errors on backends that don't defer constraints checks
Book.objects.using('other').create(pk=b.pk, title=b.title,
published=b.published)
Person.objects.using('other').create(pk=p.pk, name=p.name)
# Test addition
b.authors.add(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.add(p)
self.assertEqual(receiver._database, "other")
# Test removal
b.authors.remove(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.remove(p)
self.assertEqual(receiver._database, "other")
# Test addition in reverse
p.book_set.add(b)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
p.book_set.add(b)
self.assertEqual(receiver._database, "other")
# Test clearing
b.authors.clear()
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.clear()
self.assertEqual(receiver._database, "other")
class AttributeErrorRouter(object):
"A router to test the exception handling of ConnectionRouter"
def db_for_read(self, model, **hints):
raise AttributeError
def db_for_write(self, model, **hints):
raise AttributeError
class RouterAttributeErrorTestCase(TestCase):
multi_db = True
def override_router(self):
return override_settings(DATABASE_ROUTERS=[AttributeErrorRouter()])
def test_attribute_error_read(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up"
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
with self.override_router():
self.assertRaises(AttributeError, Book.objects.get, pk=b.pk)
def test_attribute_error_save(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up"
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
with self.override_router():
self.assertRaises(AttributeError, dive.save)
def test_attribute_error_delete(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up"
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
p = Person.objects.create(name="Marty Alchin")
b.authors.set([p])
b.editor = p
with self.override_router():
self.assertRaises(AttributeError, b.delete)
def test_attribute_error_m2m(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up"
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
p = Person.objects.create(name="Marty Alchin")
with self.override_router():
with self.assertRaises(AttributeError):
b.authors.set([p])
class ModelMetaRouter(object):
"A router to ensure model arguments are real model classes"
def db_for_write(self, model, **hints):
if not hasattr(model, '_meta'):
raise ValueError
@override_settings(DATABASE_ROUTERS=[ModelMetaRouter()])
class RouterModelArgumentTestCase(TestCase):
multi_db = True
def test_m2m_collection(self):
b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
p = Person.objects.create(name="Marty Alchin")
# test add
b.authors.add(p)
# test remove
b.authors.remove(p)
# test clear
b.authors.clear()
# test setattr
b.authors.set([p])
# test M2M collection
b.delete()
def test_foreignkey_collection(self):
person = Person.objects.create(name='Bob')
Pet.objects.create(owner=person, name='Wart')
# test related FK collection
person.delete()
class SyncOnlyDefaultDatabaseRouter(object):
def allow_migrate(self, db, app_label, **hints):
return db == DEFAULT_DB_ALIAS
class MigrateTestCase(TestCase):
available_apps = [
'multiple_database',
'django.contrib.auth',
'django.contrib.contenttypes'
]
multi_db = True
def test_migrate_to_other_database(self):
"""Regression test for #16039: migrate with --database option."""
cts = ContentType.objects.using('other').filter(app_label='multiple_database')
count = cts.count()
self.assertGreater(count, 0)
cts.delete()
management.call_command('migrate', verbosity=0, interactive=False, database='other')
self.assertEqual(cts.count(), count)
def test_migrate_to_other_database_with_router(self):
"""Regression test for #16039: migrate with --database option."""
cts = ContentType.objects.using('other').filter(app_label='multiple_database')
cts.delete()
with override_settings(DATABASE_ROUTERS=[SyncOnlyDefaultDatabaseRouter()]):
management.call_command('migrate', verbosity=0, interactive=False, database='other')
self.assertEqual(cts.count(), 0)
class RouterUsed(Exception):
WRITE = 'write'
def __init__(self, mode, model, hints):
self.mode = mode
self.model = model
self.hints = hints
class RouteForWriteTestCase(TestCase):
multi_db = True
class WriteCheckRouter(object):
def db_for_write(self, model, **hints):
raise RouterUsed(mode=RouterUsed.WRITE, model=model, hints=hints)
def override_router(self):
return override_settings(DATABASE_ROUTERS=[RouteForWriteTestCase.WriteCheckRouter()])
def test_fk_delete(self):
owner = Person.objects.create(name='Someone')
pet = Pet.objects.create(name='fido', owner=owner)
try:
with self.override_router():
pet.owner.delete()
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {'instance': owner})
def test_reverse_fk_delete(self):
owner = Person.objects.create(name='Someone')
to_del_qs = owner.pet_set.all()
try:
with self.override_router():
to_del_qs.delete()
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Pet)
self.assertEqual(e.hints, {'instance': owner})
def test_reverse_fk_get_or_create(self):
owner = Person.objects.create(name='Someone')
try:
with self.override_router():
owner.pet_set.get_or_create(name='fido')
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Pet)
self.assertEqual(e.hints, {'instance': owner})
def test_reverse_fk_update(self):
owner = Person.objects.create(name='Someone')
Pet.objects.create(name='fido', owner=owner)
try:
with self.override_router():
owner.pet_set.update(name='max')
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Pet)
self.assertEqual(e.hints, {'instance': owner})
def test_m2m_add(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
try:
with self.override_router():
book.authors.add(auth)
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_clear(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
try:
with self.override_router():
book.authors.clear()
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_delete(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
try:
with self.override_router():
book.authors.all().delete()
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_get_or_create(self):
Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
try:
with self.override_router():
book.authors.get_or_create(name='Someone else')
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_remove(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
try:
with self.override_router():
book.authors.remove(auth)
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': book})
def test_m2m_update(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
try:
with self.override_router():
book.authors.all().update(name='Different')
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {'instance': book})
def test_reverse_m2m_add(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
try:
with self.override_router():
auth.book_set.add(book)
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_clear(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
try:
with self.override_router():
auth.book_set.clear()
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_delete(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
try:
with self.override_router():
auth.book_set.all().delete()
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_get_or_create(self):
auth = Person.objects.create(name='Someone')
Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
try:
with self.override_router():
auth.book_set.get_or_create(title="New Book", published=datetime.datetime.now())
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_remove(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
try:
with self.override_router():
auth.book_set.remove(book)
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {'instance': auth})
def test_reverse_m2m_update(self):
auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16))
book.authors.add(auth)
try:
with self.override_router():
auth.book_set.all().update(title='Different')
self.fail('db_for_write() not invoked on router')
except RouterUsed as e:
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)
self.assertEqual(e.hints, {'instance': auth})
| bsd-3-clause |
invisiblek/python-for-android | python3-alpha/python3-src/Lib/encodings/cp1256.py | 272 | 12814 | """ Python Character Mapping Codec cp1256 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1256.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp1256',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
'\x00' # 0x00 -> NULL
'\x01' # 0x01 -> START OF HEADING
'\x02' # 0x02 -> START OF TEXT
'\x03' # 0x03 -> END OF TEXT
'\x04' # 0x04 -> END OF TRANSMISSION
'\x05' # 0x05 -> ENQUIRY
'\x06' # 0x06 -> ACKNOWLEDGE
'\x07' # 0x07 -> BELL
'\x08' # 0x08 -> BACKSPACE
'\t' # 0x09 -> HORIZONTAL TABULATION
'\n' # 0x0A -> LINE FEED
'\x0b' # 0x0B -> VERTICAL TABULATION
'\x0c' # 0x0C -> FORM FEED
'\r' # 0x0D -> CARRIAGE RETURN
'\x0e' # 0x0E -> SHIFT OUT
'\x0f' # 0x0F -> SHIFT IN
'\x10' # 0x10 -> DATA LINK ESCAPE
'\x11' # 0x11 -> DEVICE CONTROL ONE
'\x12' # 0x12 -> DEVICE CONTROL TWO
'\x13' # 0x13 -> DEVICE CONTROL THREE
'\x14' # 0x14 -> DEVICE CONTROL FOUR
'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE
'\x16' # 0x16 -> SYNCHRONOUS IDLE
'\x17' # 0x17 -> END OF TRANSMISSION BLOCK
'\x18' # 0x18 -> CANCEL
'\x19' # 0x19 -> END OF MEDIUM
'\x1a' # 0x1A -> SUBSTITUTE
'\x1b' # 0x1B -> ESCAPE
'\x1c' # 0x1C -> FILE SEPARATOR
'\x1d' # 0x1D -> GROUP SEPARATOR
'\x1e' # 0x1E -> RECORD SEPARATOR
'\x1f' # 0x1F -> UNIT SEPARATOR
' ' # 0x20 -> SPACE
'!' # 0x21 -> EXCLAMATION MARK
'"' # 0x22 -> QUOTATION MARK
'#' # 0x23 -> NUMBER SIGN
'$' # 0x24 -> DOLLAR SIGN
'%' # 0x25 -> PERCENT SIGN
'&' # 0x26 -> AMPERSAND
"'" # 0x27 -> APOSTROPHE
'(' # 0x28 -> LEFT PARENTHESIS
')' # 0x29 -> RIGHT PARENTHESIS
'*' # 0x2A -> ASTERISK
'+' # 0x2B -> PLUS SIGN
',' # 0x2C -> COMMA
'-' # 0x2D -> HYPHEN-MINUS
'.' # 0x2E -> FULL STOP
'/' # 0x2F -> SOLIDUS
'0' # 0x30 -> DIGIT ZERO
'1' # 0x31 -> DIGIT ONE
'2' # 0x32 -> DIGIT TWO
'3' # 0x33 -> DIGIT THREE
'4' # 0x34 -> DIGIT FOUR
'5' # 0x35 -> DIGIT FIVE
'6' # 0x36 -> DIGIT SIX
'7' # 0x37 -> DIGIT SEVEN
'8' # 0x38 -> DIGIT EIGHT
'9' # 0x39 -> DIGIT NINE
':' # 0x3A -> COLON
';' # 0x3B -> SEMICOLON
'<' # 0x3C -> LESS-THAN SIGN
'=' # 0x3D -> EQUALS SIGN
'>' # 0x3E -> GREATER-THAN SIGN
'?' # 0x3F -> QUESTION MARK
'@' # 0x40 -> COMMERCIAL AT
'A' # 0x41 -> LATIN CAPITAL LETTER A
'B' # 0x42 -> LATIN CAPITAL LETTER B
'C' # 0x43 -> LATIN CAPITAL LETTER C
'D' # 0x44 -> LATIN CAPITAL LETTER D
'E' # 0x45 -> LATIN CAPITAL LETTER E
'F' # 0x46 -> LATIN CAPITAL LETTER F
'G' # 0x47 -> LATIN CAPITAL LETTER G
'H' # 0x48 -> LATIN CAPITAL LETTER H
'I' # 0x49 -> LATIN CAPITAL LETTER I
'J' # 0x4A -> LATIN CAPITAL LETTER J
'K' # 0x4B -> LATIN CAPITAL LETTER K
'L' # 0x4C -> LATIN CAPITAL LETTER L
'M' # 0x4D -> LATIN CAPITAL LETTER M
'N' # 0x4E -> LATIN CAPITAL LETTER N
'O' # 0x4F -> LATIN CAPITAL LETTER O
'P' # 0x50 -> LATIN CAPITAL LETTER P
'Q' # 0x51 -> LATIN CAPITAL LETTER Q
'R' # 0x52 -> LATIN CAPITAL LETTER R
'S' # 0x53 -> LATIN CAPITAL LETTER S
'T' # 0x54 -> LATIN CAPITAL LETTER T
'U' # 0x55 -> LATIN CAPITAL LETTER U
'V' # 0x56 -> LATIN CAPITAL LETTER V
'W' # 0x57 -> LATIN CAPITAL LETTER W
'X' # 0x58 -> LATIN CAPITAL LETTER X
'Y' # 0x59 -> LATIN CAPITAL LETTER Y
'Z' # 0x5A -> LATIN CAPITAL LETTER Z
'[' # 0x5B -> LEFT SQUARE BRACKET
'\\' # 0x5C -> REVERSE SOLIDUS
']' # 0x5D -> RIGHT SQUARE BRACKET
'^' # 0x5E -> CIRCUMFLEX ACCENT
'_' # 0x5F -> LOW LINE
'`' # 0x60 -> GRAVE ACCENT
'a' # 0x61 -> LATIN SMALL LETTER A
'b' # 0x62 -> LATIN SMALL LETTER B
'c' # 0x63 -> LATIN SMALL LETTER C
'd' # 0x64 -> LATIN SMALL LETTER D
'e' # 0x65 -> LATIN SMALL LETTER E
'f' # 0x66 -> LATIN SMALL LETTER F
'g' # 0x67 -> LATIN SMALL LETTER G
'h' # 0x68 -> LATIN SMALL LETTER H
'i' # 0x69 -> LATIN SMALL LETTER I
'j' # 0x6A -> LATIN SMALL LETTER J
'k' # 0x6B -> LATIN SMALL LETTER K
'l' # 0x6C -> LATIN SMALL LETTER L
'm' # 0x6D -> LATIN SMALL LETTER M
'n' # 0x6E -> LATIN SMALL LETTER N
'o' # 0x6F -> LATIN SMALL LETTER O
'p' # 0x70 -> LATIN SMALL LETTER P
'q' # 0x71 -> LATIN SMALL LETTER Q
'r' # 0x72 -> LATIN SMALL LETTER R
's' # 0x73 -> LATIN SMALL LETTER S
't' # 0x74 -> LATIN SMALL LETTER T
'u' # 0x75 -> LATIN SMALL LETTER U
'v' # 0x76 -> LATIN SMALL LETTER V
'w' # 0x77 -> LATIN SMALL LETTER W
'x' # 0x78 -> LATIN SMALL LETTER X
'y' # 0x79 -> LATIN SMALL LETTER Y
'z' # 0x7A -> LATIN SMALL LETTER Z
'{' # 0x7B -> LEFT CURLY BRACKET
'|' # 0x7C -> VERTICAL LINE
'}' # 0x7D -> RIGHT CURLY BRACKET
'~' # 0x7E -> TILDE
'\x7f' # 0x7F -> DELETE
'\u20ac' # 0x80 -> EURO SIGN
'\u067e' # 0x81 -> ARABIC LETTER PEH
'\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK
'\u0192' # 0x83 -> LATIN SMALL LETTER F WITH HOOK
'\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK
'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS
'\u2020' # 0x86 -> DAGGER
'\u2021' # 0x87 -> DOUBLE DAGGER
'\u02c6' # 0x88 -> MODIFIER LETTER CIRCUMFLEX ACCENT
'\u2030' # 0x89 -> PER MILLE SIGN
'\u0679' # 0x8A -> ARABIC LETTER TTEH
'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK
'\u0152' # 0x8C -> LATIN CAPITAL LIGATURE OE
'\u0686' # 0x8D -> ARABIC LETTER TCHEH
'\u0698' # 0x8E -> ARABIC LETTER JEH
'\u0688' # 0x8F -> ARABIC LETTER DDAL
'\u06af' # 0x90 -> ARABIC LETTER GAF
'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK
'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK
'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK
'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK
'\u2022' # 0x95 -> BULLET
'\u2013' # 0x96 -> EN DASH
'\u2014' # 0x97 -> EM DASH
'\u06a9' # 0x98 -> ARABIC LETTER KEHEH
'\u2122' # 0x99 -> TRADE MARK SIGN
'\u0691' # 0x9A -> ARABIC LETTER RREH
'\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
'\u0153' # 0x9C -> LATIN SMALL LIGATURE OE
'\u200c' # 0x9D -> ZERO WIDTH NON-JOINER
'\u200d' # 0x9E -> ZERO WIDTH JOINER
'\u06ba' # 0x9F -> ARABIC LETTER NOON GHUNNA
'\xa0' # 0xA0 -> NO-BREAK SPACE
'\u060c' # 0xA1 -> ARABIC COMMA
'\xa2' # 0xA2 -> CENT SIGN
'\xa3' # 0xA3 -> POUND SIGN
'\xa4' # 0xA4 -> CURRENCY SIGN
'\xa5' # 0xA5 -> YEN SIGN
'\xa6' # 0xA6 -> BROKEN BAR
'\xa7' # 0xA7 -> SECTION SIGN
'\xa8' # 0xA8 -> DIAERESIS
'\xa9' # 0xA9 -> COPYRIGHT SIGN
'\u06be' # 0xAA -> ARABIC LETTER HEH DOACHASHMEE
'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
'\xac' # 0xAC -> NOT SIGN
'\xad' # 0xAD -> SOFT HYPHEN
'\xae' # 0xAE -> REGISTERED SIGN
'\xaf' # 0xAF -> MACRON
'\xb0' # 0xB0 -> DEGREE SIGN
'\xb1' # 0xB1 -> PLUS-MINUS SIGN
'\xb2' # 0xB2 -> SUPERSCRIPT TWO
'\xb3' # 0xB3 -> SUPERSCRIPT THREE
'\xb4' # 0xB4 -> ACUTE ACCENT
'\xb5' # 0xB5 -> MICRO SIGN
'\xb6' # 0xB6 -> PILCROW SIGN
'\xb7' # 0xB7 -> MIDDLE DOT
'\xb8' # 0xB8 -> CEDILLA
'\xb9' # 0xB9 -> SUPERSCRIPT ONE
'\u061b' # 0xBA -> ARABIC SEMICOLON
'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
'\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER
'\xbd' # 0xBD -> VULGAR FRACTION ONE HALF
'\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS
'\u061f' # 0xBF -> ARABIC QUESTION MARK
'\u06c1' # 0xC0 -> ARABIC LETTER HEH GOAL
'\u0621' # 0xC1 -> ARABIC LETTER HAMZA
'\u0622' # 0xC2 -> ARABIC LETTER ALEF WITH MADDA ABOVE
'\u0623' # 0xC3 -> ARABIC LETTER ALEF WITH HAMZA ABOVE
'\u0624' # 0xC4 -> ARABIC LETTER WAW WITH HAMZA ABOVE
'\u0625' # 0xC5 -> ARABIC LETTER ALEF WITH HAMZA BELOW
'\u0626' # 0xC6 -> ARABIC LETTER YEH WITH HAMZA ABOVE
'\u0627' # 0xC7 -> ARABIC LETTER ALEF
'\u0628' # 0xC8 -> ARABIC LETTER BEH
'\u0629' # 0xC9 -> ARABIC LETTER TEH MARBUTA
'\u062a' # 0xCA -> ARABIC LETTER TEH
'\u062b' # 0xCB -> ARABIC LETTER THEH
'\u062c' # 0xCC -> ARABIC LETTER JEEM
'\u062d' # 0xCD -> ARABIC LETTER HAH
'\u062e' # 0xCE -> ARABIC LETTER KHAH
'\u062f' # 0xCF -> ARABIC LETTER DAL
'\u0630' # 0xD0 -> ARABIC LETTER THAL
'\u0631' # 0xD1 -> ARABIC LETTER REH
'\u0632' # 0xD2 -> ARABIC LETTER ZAIN
'\u0633' # 0xD3 -> ARABIC LETTER SEEN
'\u0634' # 0xD4 -> ARABIC LETTER SHEEN
'\u0635' # 0xD5 -> ARABIC LETTER SAD
'\u0636' # 0xD6 -> ARABIC LETTER DAD
'\xd7' # 0xD7 -> MULTIPLICATION SIGN
'\u0637' # 0xD8 -> ARABIC LETTER TAH
'\u0638' # 0xD9 -> ARABIC LETTER ZAH
'\u0639' # 0xDA -> ARABIC LETTER AIN
'\u063a' # 0xDB -> ARABIC LETTER GHAIN
'\u0640' # 0xDC -> ARABIC TATWEEL
'\u0641' # 0xDD -> ARABIC LETTER FEH
'\u0642' # 0xDE -> ARABIC LETTER QAF
'\u0643' # 0xDF -> ARABIC LETTER KAF
'\xe0' # 0xE0 -> LATIN SMALL LETTER A WITH GRAVE
'\u0644' # 0xE1 -> ARABIC LETTER LAM
'\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
'\u0645' # 0xE3 -> ARABIC LETTER MEEM
'\u0646' # 0xE4 -> ARABIC LETTER NOON
'\u0647' # 0xE5 -> ARABIC LETTER HEH
'\u0648' # 0xE6 -> ARABIC LETTER WAW
'\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA
'\xe8' # 0xE8 -> LATIN SMALL LETTER E WITH GRAVE
'\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE
'\xea' # 0xEA -> LATIN SMALL LETTER E WITH CIRCUMFLEX
'\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS
'\u0649' # 0xEC -> ARABIC LETTER ALEF MAKSURA
'\u064a' # 0xED -> ARABIC LETTER YEH
'\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX
'\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS
'\u064b' # 0xF0 -> ARABIC FATHATAN
'\u064c' # 0xF1 -> ARABIC DAMMATAN
'\u064d' # 0xF2 -> ARABIC KASRATAN
'\u064e' # 0xF3 -> ARABIC FATHA
'\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
'\u064f' # 0xF5 -> ARABIC DAMMA
'\u0650' # 0xF6 -> ARABIC KASRA
'\xf7' # 0xF7 -> DIVISION SIGN
'\u0651' # 0xF8 -> ARABIC SHADDA
'\xf9' # 0xF9 -> LATIN SMALL LETTER U WITH GRAVE
'\u0652' # 0xFA -> ARABIC SUKUN
'\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX
'\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS
'\u200e' # 0xFD -> LEFT-TO-RIGHT MARK
'\u200f' # 0xFE -> RIGHT-TO-LEFT MARK
'\u06d2' # 0xFF -> ARABIC LETTER YEH BARREE
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
| apache-2.0 |
meletakis/collato | lib/python2.7/site-packages/django/conf/locale/ka/formats.py | 106 | 1849 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'l, j F, Y'
TIME_FORMAT = 'h:i:s a'
DATETIME_FORMAT = 'j F, Y h:i:s a'
YEAR_MONTH_FORMAT = 'F, Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'j.M.Y'
SHORT_DATETIME_FORMAT = 'j.M.Y H:i:s'
FIRST_DAY_OF_WEEK = 1 # (Monday)
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
# Kept ISO formats as they are in first position
DATE_INPUT_FORMATS = (
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
# '%d %b %Y', '%d %b, %Y', '%d %b. %Y', # '25 Oct 2006', '25 Oct, 2006', '25 Oct. 2006'
# '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
# '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06'
)
DATETIME_INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59'
'%d.%m.%Y %H:%M', # '25.10.2006 14:30'
'%d.%m.%Y', # '25.10.2006'
'%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59'
'%d.%m.%y %H:%M', # '25.10.06 14:30'
'%d.%m.%y', # '25.10.06'
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
)
DECIMAL_SEPARATOR = '.'
THOUSAND_SEPARATOR = " "
NUMBER_GROUPING = 3
| gpl-2.0 |
JavML/django | django/conf/__init__.py | 84 | 6865 | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import importlib
import os
import time
from django.conf import global_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import LazyObject, empty
ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
class LazySettings(LazyObject):
"""
A lazy proxy for either global Django settings or a custom settings object.
The user can manually configure settings prior to using them. Otherwise,
Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
"""
def _setup(self, name=None):
"""
Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually.
"""
settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
if not settings_module:
desc = ("setting %s" % name) if name else "settings"
raise ImproperlyConfigured(
"Requested %s, but settings are not configured. "
"You must either define the environment variable %s "
"or call settings.configure() before accessing settings."
% (desc, ENVIRONMENT_VARIABLE))
self._wrapped = Settings(settings_module)
def __repr__(self):
# Hardcode the class name as otherwise it yields 'Settings'.
if self._wrapped is empty:
return '<LazySettings [Unevaluated]>'
return '<LazySettings "%(settings_module)s">' % {
'settings_module': self._wrapped.SETTINGS_MODULE,
}
def __getattr__(self, name):
if self._wrapped is empty:
self._setup(name)
return getattr(self._wrapped, name)
def configure(self, default_settings=global_settings, **options):
"""
Called to manually configure the settings. The 'default_settings'
parameter sets where to retrieve any unspecified values from (its
argument must support attribute access (__getattr__)).
"""
if self._wrapped is not empty:
raise RuntimeError('Settings already configured.')
holder = UserSettingsHolder(default_settings)
for name, value in options.items():
setattr(holder, name, value)
self._wrapped = holder
@property
def configured(self):
"""
Returns True if the settings have already been configured.
"""
return self._wrapped is not empty
class BaseSettings(object):
"""
Common logic for settings whether set by a module or by the user.
"""
def __setattr__(self, name, value):
if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'):
raise ImproperlyConfigured("If set, %s must end with a slash" % name)
object.__setattr__(self, name, value)
class Settings(BaseSettings):
def __init__(self, settings_module):
# update this dict from global settings (but only for ALL_CAPS settings)
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))
# store the settings module in case someone later cares
self.SETTINGS_MODULE = settings_module
mod = importlib.import_module(self.SETTINGS_MODULE)
tuple_settings = (
"INSTALLED_APPS",
"TEMPLATE_DIRS",
"LOCALE_PATHS",
)
self._explicit_settings = set()
for setting in dir(mod):
if setting.isupper():
setting_value = getattr(mod, setting)
if (setting in tuple_settings and
not isinstance(setting_value, (list, tuple))):
raise ImproperlyConfigured("The %s setting must be a list or a tuple. "
"Please fix your settings." % setting)
setattr(self, setting, setting_value)
self._explicit_settings.add(setting)
if not self.SECRET_KEY:
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
if hasattr(time, 'tzset') and self.TIME_ZONE:
# When we can, attempt to validate the timezone. If we can't find
# this file, no check happens and it's harmless.
zoneinfo_root = '/usr/share/zoneinfo'
if (os.path.exists(zoneinfo_root) and not
os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
os.environ['TZ'] = self.TIME_ZONE
time.tzset()
def is_overridden(self, setting):
return setting in self._explicit_settings
def __repr__(self):
return '<%(cls)s "%(settings_module)s">' % {
'cls': self.__class__.__name__,
'settings_module': self.SETTINGS_MODULE,
}
class UserSettingsHolder(BaseSettings):
"""
Holder for user configured settings.
"""
# SETTINGS_MODULE doesn't make much sense in the manually configured
# (standalone) case.
SETTINGS_MODULE = None
def __init__(self, default_settings):
"""
Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).
"""
self.__dict__['_deleted'] = set()
self.default_settings = default_settings
def __getattr__(self, name):
if name in self._deleted:
raise AttributeError
return getattr(self.default_settings, name)
def __setattr__(self, name, value):
self._deleted.discard(name)
super(UserSettingsHolder, self).__setattr__(name, value)
def __delattr__(self, name):
self._deleted.add(name)
if hasattr(self, name):
super(UserSettingsHolder, self).__delattr__(name)
def __dir__(self):
return list(self.__dict__) + dir(self.default_settings)
def is_overridden(self, setting):
deleted = (setting in self._deleted)
set_locally = (setting in self.__dict__)
set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
return (deleted or set_locally or set_on_default)
def __repr__(self):
return '<%(cls)s>' % {
'cls': self.__class__.__name__,
}
settings = LazySettings()
| bsd-3-clause |
Islast/BrainNetworksInPython | tests/write_fixtures.py | 1 | 4563 | # -------------------------- Write fixtures ---------------------------
# To regression test our wrappers we need examples. This script
# generates files. We save these files once, and regression_test.py
# re-generates these files to tests them for identicality with the
# presaved examples (fixtures). If they are found not to be identical
# it throws up an error.
#
# The point of this is to check that throughout the changes we make to
# scona the functionality of this script stays the same
#
# Currently the functionality of write_fixtures is to generate corrmat
# and network_analysis data via the functions
# corrmat_from_regionalmeasures and network_analysis_from_corrmat.
# ---------------------------------------------------------------------
import os
import scona as scn
import scona.datasets as datasets
def recreate_correlation_matrix_fixture(folder):
# generate a correlation matrix in the given folder using
# the Whitaker_Vertes dataset
regionalmeasures, names, covars, centroids = (
datasets.NSPN_WhitakerVertes_PNAS2016._data())
corrmat_path = os.path.join(folder, 'corrmat_file.txt')
scn.wrappers.corrmat_from_regionalmeasures(
regionalmeasures,
names,
corrmat_path)
def recreate_network_analysis_fixture(folder, corrmat_path):
# generate network analysis in the given folder using the #####
# data in example_data and the correlation matrix given #####
# by corrmat_path #####
regionalmeasures, names, covars, centroids = (
datasets.NSPN_WhitakerVertes_PNAS2016._data())
# It is necessary to specify a random seed because
# network_analysis_from_corrmat generates random graphs to
# calculate global measures
scn.wrappers.network_analysis_from_corrmat(
corrmat_path,
names,
centroids,
os.path.join(os.getcwd(), folder, 'network-analysis'),
cost=10,
n_rand=10, # this is not a reasonable
# value for n, we generate only 10 random
# graphs to save time
edge_swap_seed=2984
)
def write_fixtures(folder='temporary_test_fixtures'):
# Run functions corrmat_from_regionalmeasures and ##
# network_analysis_from_corrmat to save corrmat in given folder ##
# --------------------------------------------------------------##
# if the folder does not exist, create it
if not os.path.isdir(os.path.join(os.getcwd(), folder)):
os.makedirs(os.path.join(os.getcwd(), folder))
# generate and save the correlation matrix
print("generating new correlation matrix")
recreate_correlation_matrix_fixture(folder)
# generate and save the network analysis
print("generating new network analysis")
corrmat_path = os.path.join(folder, 'corrmat_file.txt')
recreate_network_analysis_fixture(folder, corrmat_path)
def delete_fixtures(folder):
import shutil
print('\ndeleting temporary files')
shutil.rmtree(os.getcwd()+folder)
def hash_folder(folder='temporary_test_fixtures'):
hashes = {}
for path, directories, files in os.walk(folder):
for file in sorted(files):
hashes[os.path.join(path, file)] = hash_file(
os.path.join(path, file))
for dir in sorted(directories):
hashes.update(hash_folder(os.path.join(path, dir)))
break
return hashes
def hash_file(filename):
import hashlib
m = hashlib.sha256()
with open(filename, 'rb') as f:
while True:
b = f.read(2**10)
if not b:
break
m.update(b)
return m.hexdigest()
def generate_fixture_hashes(folder='temporary_test_fixtures'):
# generate the fixtures
write_fixtures(folder=folder)
# calculate the hash
hash_dict = hash_folder(folder=folder)
# delete the new files
delete_fixtures("/"+folder)
# return hash
return hash_dict
def pickle_hash(hash_dict):
import pickle
with open("tests/.fixture_hash", 'wb') as f:
pickle.dump(hash_dict, f)
def unpickle_hash():
import pickle
# import fixture relevant to the current python, networkx versions
print('loading test fixtures')
with open("tests/.fixture_hash", "rb") as f:
pickle_file = pickle.load(f)
return pickle_file
if __name__ == '__main__':
if (input("Are you sure you want to update scona's test fixtures? (y/n)")
== 'y'):
hash_dict = generate_fixture_hashes()
pickle_hash(hash_dict)
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.