text
stringlengths 6
947k
| repo_name
stringlengths 5
100
| path
stringlengths 4
231
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 6
947k
| score
float64 0
0.34
|
---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
#
# flask-ponywhoosh documentation build configuration file, created by
# sphinx-quickstart on Tue Jun 1 14:31:57 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.append(os.path.abspath('_themes'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.doctest']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
roject = u'flask-ponywhoosh'
copyright = u'2018, Jonathan Prieto-Cubides & Felipe Rodriguez'
author = u'Jonathan Prieto-Cubides & Felipe Rodriguez'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
# import pkg_resources
# try:
# release = pkg_resources.get_distribution('flask-ponywhoosh').version
# except pkg_resources.DistributionNotFound:
# print('To build the documentation, The distribution information of')
# print('Flask-Ponywhoosh has to be available. Either install the package')
# print('into your development environment or run "setup.py develop"')
# print('to setup the metadata. A virtualenv is recommended!')
# sys.exit(1)
# del pkg_resources
# if 'dev' in release:
# release = release.split('dev')[0] + 'dev'
# version = '.'.join(release.split('.')[:2])
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
pygments_style = 'sphinx'
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'flask'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'index_logo': 'logo.png'
}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['_themes']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar. Do not set, template magic!
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],
'**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',
'sourcelink.html', 'searchbox.html']
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_use_modindex = False
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'flask-ponywhooshdoc'
# -- Options for LaTeX output --------------------------------------------------
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
(master_doc, 'flask-ponywhoosh.tex', u'flask-ponywhoosh Documentation',
u'Jonathan Prieto-Cubides \\& Felipe Rodriguez', 'manual'),
]
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
latex_use_modindex = False
latex_elements = {
'fontpkg': r'\usepackage{mathpazo}',
'papersize': 'a4paper',
'pointsize': '12pt',
'preamble': r'\usepackage{flaskstyle}'
}
latex_use_parts = True
latex_additional_files = ['flaskstyle.sty', 'logo.pdf']
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'flask-ponywhoosh', u'flask-ponywhoosh Documentation',
[author], 1)
]
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None,
'http://flask.pocoo.org/docs/': None}
pygments_style = 'flask_theme_support.FlaskyStyle'
texinfo_documents = [
(master_doc, 'flask-ponywhoosh', u'flask-ponywhoosh Documentation',
author, 'flask-ponywhoosh', 'One line description of project.',
'Miscellaneous'),
]
# fall back if theme is not there
try:
__import__('flask_theme_support')
except ImportError as e:
print('-' * 74)
print('Warning: Flask themes unavailable. Building with default theme')
print('If you want the Flask themes, run this command and build again:')
print()
print(' git submodule update --init')
print('-' * 74)
pygments_style = 'tango'
html_theme = 'default'
html_theme_options = {}
| compiteing/flask-ponywhoosh | docs/src/conf.py | Python | mit | 8,701 | 0.004252 |
from django.contrib import admin
from video.models import TaggedVideo, Video
class VideoAdmin(admin.TabularInline):
model = Video
@admin.register(TaggedVideo)
class TaggedVideoAdmin(admin.ModelAdmin):
search_fields = ['^tag']
inlines = [VideoAdmin]
| stevecassidy/signbank-video | video/admin.py | Python | bsd-3-clause | 264 | 0.007576 |
# -*- coding: utf-8 -*-
import unittest
import weakref
from pyopenapi.migration.scan import Scanner, Dispatcher, scan
from pyopenapi.migration.versions.v1_2.objects import (
ApiDeclaration, Authorization, Operation, ResponseMessage, Parameter)
from pyopenapi.migration.versions.v3_0_0.objects import (
Header as Header3,
Parameter as Parameter3,
)
from ..utils import get_test_data_folder, SampleApp
class CountObject(object):
""" a scanner for counting objects and looking for
longest attribute name. Just for test.
"""
class Disp(Dispatcher):
pass
def __init__(self):
self.total = {
ApiDeclaration: 0,
Authorization: 0,
Operation: 0,
ResponseMessage: 0
}
self.long_name = ''
@Disp.register([ApiDeclaration, Authorization, Operation, ResponseMessage])
def _count(self, path, obj, _):
self.total[obj.__class__] = self.total[obj.__class__] + 1
return path
@Disp.result
def _result(self, name):
if len(name) > len(self.long_name):
self.long_name = name
class PathRecord(object):
""" a scanner to record all json path
"""
class Disp(Dispatcher):
pass
def __init__(self):
self.api_declaration = []
self.authorization = []
self.response_message = []
self.parameter = []
# pylint: disable=unused-argument
@Disp.register([ApiDeclaration])
def _api_declaration(self, path, obj, _):
self.api_declaration.append(path)
# pylint: disable=unused-argument
@Disp.register([Authorization])
def _authorization(self, path, obj, _):
self.authorization.append(path)
# pylint: disable=unused-argument
@Disp.register([ResponseMessage])
def _response_message(self, path, obj, _):
self.response_message.append(path)
@Disp.register([Parameter])
def _parameter(self, path, obj, _):
self.parameter.append(path)
class ScannerTestCase(unittest.TestCase):
""" test scanner """
@classmethod
def setUpClass(cls):
cls.app = SampleApp.load(
get_test_data_folder(version='1.2', which='wordnik'))
def test_count(self):
scanner = Scanner(self.app)
count_obj = CountObject()
scanner.scan(route=[count_obj], root=self.app.raw)
for name in self.app.raw.cached_apis:
scanner.scan(route=[count_obj], root=self.app.raw.cached_apis[name])
self.assertEqual(
len(count_obj.long_name),
len('#/apis/3/operations/0/responseMessages/0'))
self.assertEqual(count_obj.total, {
Authorization: 1,
ApiDeclaration: 3,
Operation: 20,
ResponseMessage: 23
})
def test_leaves(self):
scanner = Scanner(self.app)
count_obj = CountObject()
scanner.scan(route=[count_obj], root=self.app.raw, leaves=[Operation])
for name in self.app.raw.cached_apis:
scanner.scan(
route=[count_obj],
root=self.app.raw.cached_apis[name],
leaves=[Operation])
# the scanning would stop at Operation, so ResponseMessage
# would not be counted.
self.assertEqual(count_obj.total, {
Authorization: 1,
ApiDeclaration: 3,
Operation: 20,
ResponseMessage: 0
})
def test_path(self):
scanner = Scanner(self.app)
path_record = PathRecord()
scanner.scan(route=[path_record], root=self.app.raw)
scanner.scan(
route=[path_record], root=self.app.raw.cached_apis['store'])
self.assertEqual(sorted(path_record.api_declaration), sorted(['#']))
self.assertEqual(path_record.authorization, ['#/authorizations/oauth2'])
self.assertEqual(
sorted(path_record.response_message),
sorted([
'#/apis/0/operations/0/responseMessages/0',
'#/apis/1/operations/0/responseMessages/1',
'#/apis/1/operations/0/responseMessages/0',
'#/apis/1/operations/1/responseMessages/1',
'#/apis/1/operations/1/responseMessages/0'
]))
self.assertEqual(
sorted(path_record.parameter),
sorted([
'#/apis/0/operations/0/parameters/0',
'#/apis/1/operations/0/parameters/0',
'#/apis/1/operations/1/parameters/0',
]))
class ResolveTestCase(unittest.TestCase):
""" test for scanner: Resolve """
@classmethod
def setUpClass(cls):
cls.app = SampleApp.create(
get_test_data_folder(version='1.2', which='model_subtypes'),
to_spec_version='2.0')
def test_ref_resolve(self):
""" make sure pre resolve works """
schema, _ = self.app.resolve_obj(
'#/definitions/user!##!UserWithInfo/allOf/0',
from_spec_version='2.0')
ref = schema.get_attrs('migration').ref_obj
self.assertTrue(isinstance(ref, weakref.ProxyTypes))
schema, _ = self.app.resolve_obj(
'#/definitions/user!##!User',
from_spec_version='2.0',
)
self.assertEqual(ref, schema)
class CountParemeter3(object):
""" a scanner just for test
"""
class Disp(Dispatcher):
pass
def __init__(self):
self.total = {
Header3: 0,
Parameter3: 0,
}
@Disp.register([Header3, Parameter3])
def _count(self, _, obj):
self.total[obj.__class__] = self.total[obj.__class__] + 1
class Scanner2TestCase(unittest.TestCase):
""" test case for Scanner2 """
def test_child_class_called_twice(self):
""" make a callback for 'Header' and 'Parameter' would only be called once,
when Header inherit Paremeter
"""
header = Header3({})
count_param = CountParemeter3()
scan(route=[count_param], root=header)
self.assertEqual(count_param.total[Header3], 1)
self.assertEqual(count_param.total[Parameter3], 0)
| mission-liao/pyopenapi | pyopenapi/tests/migration/test_scan.py | Python | mit | 6,151 | 0.000488 |
# Copyright (c) 2014 Mirantis 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.
from oslo_config import cfg
from oslo_log import log as logging
from sahara import context
from sahara.utils import rpc as messaging
LOG = logging.getLogger(__name__)
SERVICE = 'sahara'
CLUSTER_EVENT_TEMPLATE = "sahara.cluster.%s"
HEALTH_EVENT_TYPE = CLUSTER_EVENT_TEMPLATE % "health"
notifier_opts = [
cfg.StrOpt('level',
default='INFO',
deprecated_name='notification_level',
deprecated_group='DEFAULT',
help='Notification level for outgoing notifications'),
cfg.StrOpt('publisher_id',
deprecated_name='notification_publisher_id',
deprecated_group='DEFAULT')
]
notifier_opts_group = 'oslo_messaging_notifications'
CONF = cfg.CONF
CONF.register_opts(notifier_opts, group=notifier_opts_group)
def _get_publisher():
publisher_id = CONF.oslo_messaging_notifications.publisher_id
if publisher_id is None:
publisher_id = SERVICE
return publisher_id
def _notify(event_type, body):
LOG.debug("Notification about cluster is going to be sent. Notification "
"type={type}".format(type=event_type))
ctx = context.ctx()
level = CONF.oslo_messaging_notifications.level
body.update({'project_id': ctx.tenant_id, 'user_id': ctx.user_id})
client = messaging.get_notifier(_get_publisher())
method = getattr(client, level.lower())
method(ctx, event_type, body)
def _health_notification_body(cluster, health_check):
verification = cluster.verification
return {
'cluster_id': cluster.id,
'cluster_name': cluster.name,
'verification_id': verification['id'],
'health_check_status': health_check['status'],
'health_check_name': health_check['name'],
'health_check_description': health_check['description'],
'created_at': health_check['created_at'],
'updated_at': health_check['updated_at']
}
def status_notify(cluster_id, cluster_name, cluster_status, ev_type):
"""Sends notification about creating/updating/deleting cluster."""
_notify(CLUSTER_EVENT_TEMPLATE % ev_type, {
'cluster_id': cluster_id, 'cluster_name': cluster_name,
'cluster_status': cluster_status})
def health_notify(cluster, health_check):
"""Sends notification about current cluster health."""
_notify(HEALTH_EVENT_TYPE,
_health_notification_body(cluster, health_check))
| tellesnobrega/sahara | sahara/utils/notification/sender.py | Python | apache-2.0 | 2,996 | 0 |
# coding: utf-8
from __future__ import unicode_literals
from django.contrib import admin
from .models import Book, Author, Publisher, Genre
admin.site.register(Book, admin.ModelAdmin)
admin.site.register(Author, admin.ModelAdmin)
admin.site.register(Publisher, admin.ModelAdmin)
admin.site.register(Genre, admin.ModelAdmin)
| ToxicWar/bibliotheque | library/admin.py | Python | mit | 326 | 0 |
#!/usr/bin/env python
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies actions which are not depended on by other targets get executed.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('bare.gyp', chdir='src')
test.relocate('src', 'relocate/src')
test.build('bare.gyp', chdir='relocate/src')
file_content = 'Hello from bare.py\n'
test.built_file_must_match('out.txt', file_content, chdir='relocate/src')
test.pass_test()
| ibc/MediaSoup | worker/deps/gyp/test/actions-bare/gyptest-bare.py | Python | isc | 558 | 0 |
from django.test import TestCase
from django.core import mail
from django.contrib.auth.models import User
from userena.models import UserenaSignup
from userena import settings as userena_settings
from guardian.shortcuts import get_perms
import datetime, re
class UserenaManagerTests(TestCase):
""" Test the manager of Userena """
user_info = {'username': 'alice',
'password': 'swordfish',
'email': 'alice@example.com'}
fixtures = ['users']
def test_create_inactive_user(self):
"""
Test the creation of a new user.
``UserenaSignup.create_inactive_user`` should create a new user that is
not active. The user should get an ``activation_key`` that is used to
set the user as active.
Every user also has a profile, so this method should create an empty
profile.
"""
# Check that the fields are set.
new_user = UserenaSignup.objects.create_user(**self.user_info)
self.assertEqual(new_user.username, self.user_info['username'])
self.assertEqual(new_user.email, self.user_info['email'])
self.failUnless(new_user.check_password(self.user_info['password']))
# User should be inactive
self.failIf(new_user.is_active)
# User has a valid SHA1 activation key
self.failUnless(re.match('^[a-f0-9]{40}$', new_user.userena_signup.activation_key))
# User now has an profile.
self.failUnless(new_user.get_profile())
# User should be saved
self.failUnlessEqual(User.objects.filter(email=self.user_info['email']).count(), 1)
def test_activation_valid(self):
"""
Valid activation of an user.
Activation of an user with a valid ``activation_key`` should activate
the user and set a new invalid ``activation_key`` that is defined in
the setting ``USERENA_ACTIVATED``.
"""
user = UserenaSignup.objects.create_user(**self.user_info)
active_user = UserenaSignup.objects.activate_user(user.username,
user.userena_signup.activation_key)
# The returned user should be the same as the one just created.
self.failUnlessEqual(user, active_user)
# The user should now be active.
self.failUnless(active_user.is_active)
# The user should have permission to view and change its profile
self.failUnless('view_profile' in get_perms(active_user, active_user.get_profile()))
self.failUnless('change_profile' in get_perms(active_user, active_user.get_profile()))
# The activation key should be the same as in the settings
self.assertEqual(active_user.userena_signup.activation_key,
userena_settings.USERENA_ACTIVATED)
def test_activation_invalid(self):
"""
Activation with a key that's invalid should make
``UserenaSignup.objects.activate_user`` return ``False``.
"""
# Wrong key
self.failIf(UserenaSignup.objects.activate_user('john', 'wrong_key'))
# At least the right length
invalid_key = 10 * 'a1b2'
self.failIf(UserenaSignup.objects.activate_user('john', invalid_key))
def test_activation_expired(self):
"""
Activation with a key that's expired should also make
``UserenaSignup.objects.activation_user`` return ``False``.
"""
user = UserenaSignup.objects.create_user(**self.user_info)
# Set the date that the key is created a day further away than allowed
user.date_joined -= datetime.timedelta(days=userena_settings.USERENA_ACTIVATION_DAYS + 1)
user.save()
# Try to activate the user
UserenaSignup.objects.activate_user(user.username, user.userena_signup.activation_key)
active_user = User.objects.get(username='alice')
# UserenaSignup activation should have failed
self.failIf(active_user.is_active)
# The activation key should still be a hash
self.assertEqual(user.userena_signup.activation_key,
active_user.userena_signup.activation_key)
def test_confirmation_valid(self):
"""
Confirmation of a new e-mail address with turns out to be valid.
"""
new_email = 'john@newexample.com'
user = User.objects.get(pk=1)
user.userena_signup.change_email(new_email)
# Confirm email
confirmed_user = UserenaSignup.objects.confirm_email(user.username,
user.userena_signup.email_confirmation_key)
self.failUnlessEqual(user, confirmed_user)
# Check the new email is set.
self.failUnlessEqual(confirmed_user.email, new_email)
# ``email_new`` and ``email_verification_key`` should be empty
self.failIf(confirmed_user.userena_signup.email_unconfirmed)
self.failIf(confirmed_user.userena_signup.email_confirmation_key)
def test_confirmation_invalid(self):
"""
Trying to confirm a new e-mail address when the ``confirmation_key``
is invalid.
"""
new_email = 'john@newexample.com'
user = User.objects.get(pk=1)
user.userena_signup.change_email(new_email)
# Verify email with wrong SHA1
self.failIf(UserenaSignup.objects.confirm_email('john', 'sha1'))
# Correct SHA1, but non-existend in db.
self.failIf(UserenaSignup.objects.confirm_email('john', 10 * 'a1b2'))
def test_delete_expired_users(self):
"""
Test if expired users are deleted from the database.
"""
expired_user = UserenaSignup.objects.create_user(**self.user_info)
expired_user.date_joined -= datetime.timedelta(days=userena_settings.USERENA_ACTIVATION_DAYS + 1)
expired_user.save()
deleted_users = UserenaSignup.objects.delete_expired_users()
self.failUnlessEqual(deleted_users[0].username, 'alice')
| pirata-cat/agora-ciudadana | userena/tests/managers.py | Python | agpl-3.0 | 6,047 | 0.001984 |
"""
The "engine room" of django mailer.
Methods here actually handle the sending of queued messages.
"""
from django_mailer import constants, models, settings
from lockfile import FileLock, AlreadyLocked, LockTimeout
from socket import error as SocketError
import logging
import os
import smtplib
import tempfile
import time
if constants.EMAIL_BACKEND_SUPPORT:
from django.core.mail import get_connection
else:
from django.core.mail import SMTPConnection as get_connection
LOCK_PATH = settings.LOCK_PATH or os.path.join(tempfile.gettempdir(),
'send_mail')
logger = logging.getLogger('django_mailer.engine')
def _message_queue(block_size, exclude_messages=[]):
"""
A generator which iterates queued messages in blocks so that new
prioritised messages can be inserted during iteration of a large number of
queued messages.
To avoid an infinite loop, yielded messages *must* be deleted or deferred.
"""
def get_block():
queue = models.QueuedMessage.objects.non_deferred() \
.exclude(pk__in=exclude_messages).select_related()
if block_size:
queue = queue[:block_size]
return queue
queue = get_block()
while queue:
for message in queue:
yield message
queue = get_block()
def send_all(block_size=500, backend=None):
"""
Send all non-deferred messages in the queue.
A lock file is used to ensure that this process can not be started again
while it is already running.
The ``block_size`` argument allows for queued messages to be iterated in
blocks, allowing new prioritised messages to be inserted during iteration
of a large number of queued messages.
"""
lock = FileLock(LOCK_PATH)
logger.debug("Acquiring lock...")
try:
# lockfile has a bug dealing with a negative LOCK_WAIT_TIMEOUT (which
# is the default if it's not provided) systems which use a LinkFileLock
# so ensure that it is never a negative number.
lock.acquire(settings.LOCK_WAIT_TIMEOUT or 0)
#lock.acquire(settings.LOCK_WAIT_TIMEOUT)
except AlreadyLocked:
logger.debug("Lock already in place. Exiting.")
return
except LockTimeout:
logger.debug("Waiting for the lock timed out. Exiting.")
return
logger.debug("Lock acquired.")
start_time = time.time()
sent = deferred = skipped = 0
# A list of messages to be sent, usually contains messages that failed
exclude_messages = []
try:
if constants.EMAIL_BACKEND_SUPPORT:
connection = get_connection(backend=backend)
else:
connection = get_connection()
blacklist = models.Blacklist.objects.values_list('email', flat=True)
connection.open()
for message in _message_queue(block_size, exclude_messages=exclude_messages):
result = send_queued_message(message, connection=connection,
blacklist=blacklist)
if result == constants.RESULT_SENT:
sent += 1
elif result == constants.RESULT_FAILED:
deferred += 1
# Don't try to send this message again for now
exclude_messages.append(message.pk)
elif result == constants.RESULT_SKIPPED:
skipped += 1
connection.close()
finally:
logger.debug("Releasing lock...")
lock.release()
logger.debug("Lock released.")
logger.debug("")
if sent or deferred or skipped:
log = logger.warning
else:
log = logger.info
log("%s sent, %s deferred, %s skipped." % (sent, deferred, skipped))
logger.debug("Completed in %.2f seconds." % (time.time() - start_time))
def send_loop(empty_queue_sleep=None):
"""
Loop indefinitely, checking queue at intervals and sending and queued
messages.
The interval (in seconds) can be provided as the ``empty_queue_sleep``
argument. The default is attempted to be retrieved from the
``MAILER_EMPTY_QUEUE_SLEEP`` setting (or if not set, 30s is used).
"""
empty_queue_sleep = empty_queue_sleep or settings.EMPTY_QUEUE_SLEEP
while True:
while not models.QueuedMessage.objects.all():
logger.debug("Sleeping for %s seconds before checking queue "
"again." % empty_queue_sleep)
time.sleep(empty_queue_sleep)
send_all()
def send_queued_message(queued_message, connection=None, blacklist=None,
log=True):
"""
Send a queued message, returning a response code as to the action taken.
The response codes can be found in ``django_mailer.constants``. The
response will be either ``RESULT_SKIPPED`` for a blacklisted email,
``RESULT_FAILED`` for a deferred message or ``RESULT_SENT`` for a
successful sent message.
To allow optimizations if multiple messages are to be sent, a
connection can be provided and a list of blacklisted email addresses.
Otherwise a new connection will be opened to send this message and the
email recipient address checked against the ``Blacklist`` table.
If the message recipient is blacklisted, the message will be removed from
the queue without being sent. Otherwise, the message is attempted to be
sent with an SMTP failure resulting in the message being flagged as
deferred so it can be tried again later.
By default, a log is created as to the action. Either way, the original
message is not deleted.
"""
message = queued_message.message
if connection is None:
connection = get_connection()
connection.open()
arg_connection = False
else:
arg_connection = True
if blacklist is None:
blacklisted = models.Blacklist.objects.filter(email=message.to_address)
else:
blacklisted = message.to_address in blacklist
if blacklisted:
logger.info("Not sending to blacklisted email: %s" %
message.to_address.encode("utf-8"))
queued_message.delete()
result = constants.RESULT_SKIPPED
else:
result = send_message(message, connection=connection)
if not arg_connection:
connection.close()
return result
def send_message(message, connection=None):
"""
Send an EmailMessage, returning a response code as to the action taken.
The response codes can be found in ``django_mailer.constants``. The
response will be either ``RESULT_FAILED`` for a failed send or
``RESULT_SENT`` for a successfully sent message.
To allow optimizations if multiple messages are to be sent, a
connection can be provided. Otherwise a new connection will be opened
to send this message.
This function does not perform any logging or queueing.
"""
if connection is None:
connection = get_connection()
opened_connection = False
try:
logger.info("Sending message to %s: %s" %
(message.to_address.encode("utf-8"),
message.subject.encode("utf-8")))
message.email_message(connection=connection).send()
message.queuedmessage.delete()
result = constants.RESULT_SENT
log_message = 'Sent'
except Exception, err:
if isinstance(err, settings.DEFER_ON_ERRORS):
message.queuedmessage.defer()
logger.warning("Message to %s deferred due to failure: %s" %
(message.to_address.encode("utf-8"), err))
log_message = unicode(err)
result = constants.RESULT_FAILED
models.Log.objects.create(message=message, result=result,
log_message=log_message)
if opened_connection:
connection.close()
return result
| selwin/django-mailer | django_mailer/engine.py | Python | mit | 7,863 | 0.001145 |
# -*- coding: utf-8 -*-
import config
from metodos import *
from mensagens import myid
def my_id(msg):
chat_id = msg['chat']['id']
try: user = '@' + msg['from']['username']
except:user = " "
if msg['text'] == '/id':
if msg['chat']['type'] == 'private':
sendMessage(chat_id, myid['private'].decode('utf8').format(msg['from']['first_name'].encode('utf-8'),msg['from']['id'],user))
if msg['chat']['type'] == 'supergroup' or msg['chat']['type'] == 'group':
sendMessage(chat_id, myid['private'].decode('utf8').format(msg['from']['first_name'],msg['from']['id'],user))
| francis-taylor/Timotty-Master | cybot/plug/myid.py | Python | mit | 625 | 0.0224 |
from typing import Any, Generator, List, Optional
from backend.common.consts.suggestion_state import SuggestionState
from backend.common.models.account import Account
from backend.common.models.suggestion import Suggestion
from backend.common.queries.database_query import DatabaseQuery
from backend.common.tasklets import typed_tasklet
class SuggestionQuery(DatabaseQuery[List[Suggestion], None]):
DICT_CONVERTER = None
def __init__(
self,
review_state: SuggestionState,
author: Optional[Account] = None,
reviewer: Optional[Account] = None,
keys_only: bool = False,
) -> None:
super().__init__(
review_state=review_state,
author=author,
reviewer=reviewer,
keys_only=keys_only,
)
@typed_tasklet
def _query_async(
self,
review_state: SuggestionState,
author: Optional[Account] = None,
reviewer: Optional[Account] = None,
keys_only: bool = False,
) -> Generator[Any, Any, List[Suggestion]]:
params = [Suggestion.review_state == review_state]
if author:
params.append(Suggestion.author == author.key)
if reviewer:
params.append(Suggestion.reviewer == reviewer.key)
return (yield (Suggestion.query(*params).fetch_async(keys_only=keys_only)))
| the-blue-alliance/the-blue-alliance | src/backend/common/queries/suggestion_query.py | Python | mit | 1,368 | 0.000731 |
"""
Courseware views functions
"""
import logging
import urllib
import json
from collections import defaultdict
from django.utils.translation import ugettext as _
from django.conf import settings
from django.core.context_processors import csrf
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_GET
from django.http import Http404, HttpResponse
from django.shortcuts import redirect
from edxmako.shortcuts import render_to_response, render_to_string
from django_future.csrf import ensure_csrf_cookie
from django.views.decorators.cache import cache_control
from django.db import transaction
from markupsafe import escape
from courseware import grades
from courseware.access import has_access
from courseware.courses import get_courses, get_course, get_studio_url, get_course_with_access, sort_by_announcement
from courseware.masquerade import setup_masquerade
from courseware.model_data import FieldDataCache
from .module_render import toc_for_course, get_module_for_descriptor, get_module
from courseware.models import StudentModule, StudentModuleHistory
from course_modes.models import CourseMode
from open_ended_grading import open_ended_notifications
from student.models import UserTestGroup, CourseEnrollment
from student.views import course_from_id, single_course_reverification_info
from util.cache import cache, cache_if_anonymous
from xblock.fragment import Fragment
from xmodule.modulestore import Location
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.exceptions import InvalidLocationError, ItemNotFoundError, NoPathToItem
from xmodule.modulestore.search import path_to_location
from xmodule.course_module import CourseDescriptor
from xmodule.tabs import CourseTabList, StaffGradingTab, PeerGradingTab, OpenEndedGradingTab
import shoppingcart
from microsite_configuration import microsite
log = logging.getLogger("edx.courseware")
template_imports = {'urllib': urllib}
def user_groups(user):
"""
TODO (vshnayder): This is not used. When we have a new plan for groups, adjust appropriately.
"""
if not user.is_authenticated():
return []
# TODO: Rewrite in Django
key = 'user_group_names_{user.id}'.format(user=user)
cache_expiration = 60 * 60 # one hour
# Kill caching on dev machines -- we switch groups a lot
group_names = cache.get(key)
if settings.DEBUG:
group_names = None
if group_names is None:
group_names = [u.name for u in UserTestGroup.objects.filter(users=user)]
cache.set(key, group_names, cache_expiration)
return group_names
@ensure_csrf_cookie
@cache_if_anonymous
def courses(request):
"""
Render "find courses" page. The course selection work is done in courseware.courses.
"""
courses = get_courses(request.user, request.META.get('HTTP_HOST'))
courses = sort_by_announcement(courses)
return render_to_response("courseware/courses.html", {'courses': courses})
def render_accordion(request, course, chapter, section, field_data_cache):
"""
Draws navigation bar. Takes current position in accordion as
parameter.
If chapter and section are '' or None, renders a default accordion.
course, chapter, and section are the url_names.
Returns the html string
"""
# grab the table of contents
user = User.objects.prefetch_related("groups").get(id=request.user.id)
request.user = user # keep just one instance of User
toc = toc_for_course(user, request, course, chapter, section, field_data_cache)
context = dict([
('toc', toc),
('course_id', course.id),
('csrf', csrf(request)['csrf_token']),
('due_date_display_format', course.due_date_display_format)
] + template_imports.items())
return render_to_string('courseware/accordion.html', context)
def get_current_child(xmodule):
"""
Get the xmodule.position's display item of an xmodule that has a position and
children. If xmodule has no position or is out of bounds, return the first child.
Returns None only if there are no children at all.
"""
if not hasattr(xmodule, 'position'):
return None
if xmodule.position is None:
pos = 0
else:
# position is 1-indexed.
pos = xmodule.position - 1
children = xmodule.get_display_items()
if 0 <= pos < len(children):
child = children[pos]
elif len(children) > 0:
# Something is wrong. Default to first child
child = children[0]
else:
child = None
return child
def redirect_to_course_position(course_module):
"""
Return a redirect to the user's current place in the course.
If this is the user's first time, redirects to COURSE/CHAPTER/SECTION.
If this isn't the users's first time, redirects to COURSE/CHAPTER,
and the view will find the current section and display a message
about reusing the stored position.
If there is no current position in the course or chapter, then selects
the first child.
"""
urlargs = {'course_id': course_module.id}
chapter = get_current_child(course_module)
if chapter is None:
# oops. Something bad has happened.
raise Http404("No chapter found when loading current position in course")
urlargs['chapter'] = chapter.url_name
if course_module.position is not None:
return redirect(reverse('courseware_chapter', kwargs=urlargs))
# Relying on default of returning first child
section = get_current_child(chapter)
if section is None:
raise Http404("No section found when loading current position in course")
urlargs['section'] = section.url_name
return redirect(reverse('courseware_section', kwargs=urlargs))
def save_child_position(seq_module, child_name):
"""
child_name: url_name of the child
"""
for position, c in enumerate(seq_module.get_display_items(), start=1):
if c.url_name == child_name:
# Only save if position changed
if position != seq_module.position:
seq_module.position = position
# Save this new position to the underlying KeyValueStore
seq_module.save()
def chat_settings(course, user):
"""
Returns a dict containing the settings required to connect to a
Jabber chat server and room.
"""
domain = getattr(settings, "JABBER_DOMAIN", None)
if domain is None:
log.warning('You must set JABBER_DOMAIN in the settings to '
'enable the chat widget')
return None
return {
'domain': domain,
# Jabber doesn't like slashes, so replace with dashes
'room': "{ID}_class".format(ID=course.id.replace('/', '-')),
'username': "{USER}@{DOMAIN}".format(
USER=user.username, DOMAIN=domain
),
# TODO: clearly this needs to be something other than the username
# should also be something that's not necessarily tied to a
# particular course
'password': "{USER}@{DOMAIN}".format(
USER=user.username, DOMAIN=domain
),
}
@login_required
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def index(request, course_id, chapter=None, section=None,
position=None):
"""
Displays courseware accordion and associated content. If course, chapter,
and section are all specified, renders the page, or returns an error if they
are invalid.
If section is not specified, displays the accordion opened to the right chapter.
If neither chapter or section are specified, redirects to user's most recent
chapter, or the first chapter if this is the user's first visit.
Arguments:
- request : HTTP request
- course_id : course id (str: ORG/course/URL_NAME)
- chapter : chapter url_name (str)
- section : section url_name (str)
- position : position in module, eg of <sequential> module (str)
Returns:
- HTTPresponse
"""
user = User.objects.prefetch_related("groups").get(id=request.user.id)
request.user = user # keep just one instance of User
course = get_course_with_access(user, course_id, 'load', depth=2)
staff_access = has_access(user, course, 'staff')
registered = registered_for_course(course, user)
if not registered:
# TODO (vshnayder): do course instructors need to be registered to see course?
log.debug(u'User %s tried to view course %s but is not enrolled', user, course.location.url())
return redirect(reverse('about_course', args=[course.id]))
masq = setup_masquerade(request, staff_access)
try:
field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
course.id, user, course, depth=2)
course_module = get_module_for_descriptor(user, request, course, field_data_cache, course.id)
if course_module is None:
log.warning(u'If you see this, something went wrong: if we got this'
u' far, should have gotten a course module for this user')
return redirect(reverse('about_course', args=[course.id]))
studio_url = get_studio_url(course_id, 'course')
if chapter is None:
return redirect_to_course_position(course_module)
context = {
'csrf': csrf(request)['csrf_token'],
'accordion': render_accordion(request, course, chapter, section, field_data_cache),
'COURSE_TITLE': course.display_name_with_default,
'course': course,
'init': '',
'fragment': Fragment(),
'staff_access': staff_access,
'studio_url': studio_url,
'masquerade': masq,
'xqa_server': settings.FEATURES.get('USE_XQA_SERVER', 'http://xqa:server@content-qa.mitx.mit.edu/xqa'),
'reverifications': fetch_reverify_banner_info(request, course_id),
}
# Only show the chat if it's enabled by the course and in the
# settings.
show_chat = course.show_chat and settings.FEATURES['ENABLE_CHAT']
if show_chat:
context['chat'] = chat_settings(course, user)
# If we couldn't load the chat settings, then don't show
# the widget in the courseware.
if context['chat'] is None:
show_chat = False
context['show_chat'] = show_chat
chapter_descriptor = course.get_child_by(lambda m: m.url_name == chapter)
if chapter_descriptor is not None:
save_child_position(course_module, chapter)
else:
raise Http404('No chapter descriptor found with name {}'.format(chapter))
chapter_module = course_module.get_child_by(lambda m: m.url_name == chapter)
if chapter_module is None:
# User may be trying to access a chapter that isn't live yet
if masq == 'student': # if staff is masquerading as student be kinder, don't 404
log.debug('staff masq as student: no chapter %s' % chapter)
return redirect(reverse('courseware', args=[course.id]))
raise Http404
if section is not None:
section_descriptor = chapter_descriptor.get_child_by(lambda m: m.url_name == section)
if section_descriptor is None:
# Specifically asked-for section doesn't exist
if masq == 'student': # if staff is masquerading as student be kinder, don't 404
log.debug('staff masq as student: no section %s' % section)
return redirect(reverse('courseware', args=[course.id]))
raise Http404
# cdodge: this looks silly, but let's refetch the section_descriptor with depth=None
# which will prefetch the children more efficiently than doing a recursive load
section_descriptor = modulestore().get_instance(course.id, section_descriptor.location, depth=None)
# Load all descendants of the section, because we're going to display its
# html, which in general will need all of its children
section_field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
course_id, user, section_descriptor, depth=None)
section_module = get_module_for_descriptor(
request.user,
request,
section_descriptor,
section_field_data_cache,
course_id,
position
)
if section_module is None:
# User may be trying to be clever and access something
# they don't have access to.
raise Http404
# Save where we are in the chapter
save_child_position(chapter_module, section)
context['fragment'] = section_module.render('student_view')
context['section_title'] = section_descriptor.display_name_with_default
else:
# section is none, so display a message
studio_url = get_studio_url(course_id, 'course')
prev_section = get_current_child(chapter_module)
if prev_section is None:
# Something went wrong -- perhaps this chapter has no sections visible to the user
raise Http404
prev_section_url = reverse('courseware_section', kwargs={'course_id': course_id,
'chapter': chapter_descriptor.url_name,
'section': prev_section.url_name})
context['fragment'] = Fragment(content=render_to_string(
'courseware/welcome-back.html',
{
'course': course,
'studio_url': studio_url,
'chapter_module': chapter_module,
'prev_section': prev_section,
'prev_section_url': prev_section_url
}
))
result = render_to_response('courseware/courseware.html', context)
except Exception as e:
if isinstance(e, Http404):
# let it propagate
raise
# In production, don't want to let a 500 out for any reason
if settings.DEBUG:
raise
else:
log.exception(
u"Error in index view: user={user}, course={course}, chapter={chapter}"
u" section={section} position={position}".format(
user=user,
course=course,
chapter=chapter,
section=section,
position=position
))
try:
result = render_to_response('courseware/courseware-error.html', {
'staff_access': staff_access,
'course': course
})
except:
# Let the exception propagate, relying on global config to at
# at least return a nice error message
log.exception("Error while rendering courseware-error page")
raise
return result
@ensure_csrf_cookie
def jump_to_id(request, course_id, module_id):
"""
This entry point allows for a shorter version of a jump to where just the id of the element is
passed in. This assumes that id is unique within the course_id namespace
"""
course_location = CourseDescriptor.id_to_location(course_id)
items = modulestore().get_items(
Location('i4x', course_location.org, course_location.course, None, module_id),
course_id=course_id
)
if len(items) == 0:
raise Http404(
u"Could not find id: {0} in course_id: {1}. Referer: {2}".format(
module_id, course_id, request.META.get("HTTP_REFERER", "")
))
if len(items) > 1:
log.warning(
u"Multiple items found with id: {0} in course_id: {1}. Referer: {2}. Using first: {3}".format(
module_id, course_id, request.META.get("HTTP_REFERER", ""), items[0].location.url()
))
return jump_to(request, course_id, items[0].location.url())
@ensure_csrf_cookie
def jump_to(request, course_id, location):
"""
Show the page that contains a specific location.
If the location is invalid or not in any class, return a 404.
Otherwise, delegates to the index view to figure out whether this user
has access, and what they should see.
"""
# Complain if the location isn't valid
try:
location = Location(location)
except InvalidLocationError:
raise Http404("Invalid location")
# Complain if there's not data for this location
try:
(course_id, chapter, section, position) = path_to_location(modulestore(), course_id, location)
except ItemNotFoundError:
raise Http404(u"No data at this location: {0}".format(location))
except NoPathToItem:
raise Http404(u"This location is not in any class: {0}".format(location))
# choose the appropriate view (and provide the necessary args) based on the
# args provided by the redirect.
# Rely on index to do all error handling and access control.
if chapter is None:
return redirect('courseware', course_id=course_id)
elif section is None:
return redirect('courseware_chapter', course_id=course_id, chapter=chapter)
elif position is None:
return redirect('courseware_section', course_id=course_id, chapter=chapter, section=section)
else:
return redirect('courseware_position', course_id=course_id, chapter=chapter, section=section, position=position)
@ensure_csrf_cookie
def course_info(request, course_id):
"""
Display the course's info.html, or 404 if there is no such course.
Assumes the course_id is in a valid format.
"""
course = get_course_with_access(request.user, course_id, 'load')
staff_access = has_access(request.user, course, 'staff')
masq = setup_masquerade(request, staff_access) # allow staff to toggle masquerade on info page
studio_url = get_studio_url(course_id, 'course_info')
reverifications = fetch_reverify_banner_info(request, course_id)
context = {
'request': request,
'course_id': course_id,
'cache': None,
'course': course,
'staff_access': staff_access,
'masquerade': masq,
'studio_url': studio_url,
'reverifications': reverifications,
}
return render_to_response('courseware/info.html', context)
@ensure_csrf_cookie
def static_tab(request, course_id, tab_slug):
"""
Display the courses tab with the given name.
Assumes the course_id is in a valid format.
"""
course = get_course_with_access(request.user, course_id, 'load')
tab = CourseTabList.get_tab_by_slug(course.tabs, tab_slug)
if tab is None:
raise Http404
contents = get_static_tab_contents(
request,
course,
tab
)
if contents is None:
raise Http404
return render_to_response('courseware/static_tab.html', {
'course': course,
'tab': tab,
'tab_contents': contents,
})
# TODO arjun: remove when custom tabs in place, see courseware/syllabus.py
@ensure_csrf_cookie
def syllabus(request, course_id):
"""
Display the course's syllabus.html, or 404 if there is no such course.
Assumes the course_id is in a valid format.
"""
course = get_course_with_access(request.user, course_id, 'load')
staff_access = has_access(request.user, course, 'staff')
return render_to_response('courseware/syllabus.html', {
'course': course,
'staff_access': staff_access,
})
def registered_for_course(course, user):
"""
Return True if user is registered for course, else False
"""
if user is None:
return False
if user.is_authenticated():
return CourseEnrollment.is_enrolled(user, course.id)
else:
return False
@ensure_csrf_cookie
@cache_if_anonymous
def course_about(request, course_id):
"""
Display the course's about page.
Assumes the course_id is in a valid format.
"""
if microsite.get_value(
'ENABLE_MKTG_SITE',
settings.FEATURES.get('ENABLE_MKTG_SITE', False)
):
raise Http404
course = get_course_with_access(request.user, course_id, 'see_exists')
registered = registered_for_course(course, request.user)
staff_access = has_access(request.user, course, 'staff')
studio_url = get_studio_url(course_id, 'settings/details')
if has_access(request.user, course, 'load'):
course_target = reverse('info', args=[course.id])
else:
course_target = reverse('about_course', args=[course.id])
show_courseware_link = (has_access(request.user, course, 'load') or
settings.FEATURES.get('ENABLE_LMS_MIGRATION'))
# Note: this is a flow for payment for course registration, not the Verified Certificate flow.
registration_price = 0
in_cart = False
reg_then_add_to_cart_link = ""
if (settings.FEATURES.get('ENABLE_SHOPPING_CART') and
settings.FEATURES.get('ENABLE_PAID_COURSE_REGISTRATION')):
registration_price = CourseMode.min_course_price_for_currency(course_id,
settings.PAID_COURSE_REGISTRATION_CURRENCY[0])
if request.user.is_authenticated():
cart = shoppingcart.models.Order.get_cart_for_user(request.user)
in_cart = shoppingcart.models.PaidCourseRegistration.contained_in_order(cart, course_id)
reg_then_add_to_cart_link = "{reg_url}?course_id={course_id}&enrollment_action=add_to_cart".format(
reg_url=reverse('register_user'), course_id=course.id)
# see if we have already filled up all allowed enrollments
is_course_full = CourseEnrollment.is_course_full(course)
return render_to_response('courseware/course_about.html', {
'course': course,
'staff_access': staff_access,
'studio_url': studio_url,
'registered': registered,
'course_target': course_target,
'registration_price': registration_price,
'in_cart': in_cart,
'reg_then_add_to_cart_link': reg_then_add_to_cart_link,
'show_courseware_link': show_courseware_link,
'is_course_full': is_course_full
})
@ensure_csrf_cookie
@cache_if_anonymous
def mktg_course_about(request, course_id):
"""
This is the button that gets put into an iframe on the Drupal site
"""
try:
course = get_course_with_access(request.user, course_id, 'see_exists')
except (ValueError, Http404) as e:
# if a course does not exist yet, display a coming
# soon button
return render_to_response(
'courseware/mktg_coming_soon.html', {'course_id': course_id}
)
registered = registered_for_course(course, request.user)
if has_access(request.user, course, 'load'):
course_target = reverse('info', args=[course.id])
else:
course_target = reverse('about_course', args=[course.id])
allow_registration = has_access(request.user, course, 'enroll')
show_courseware_link = (has_access(request.user, course, 'load') or
settings.FEATURES.get('ENABLE_LMS_MIGRATION'))
course_modes = CourseMode.modes_for_course(course.id)
return render_to_response('courseware/mktg_course_about.html', {
'course': course,
'registered': registered,
'allow_registration': allow_registration,
'course_target': course_target,
'show_courseware_link': show_courseware_link,
'course_modes': course_modes,
})
@login_required
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@transaction.commit_manually
def progress(request, course_id, student_id=None):
"""
Wraps "_progress" with the manual_transaction context manager just in case
there are unanticipated errors.
"""
with grades.manual_transaction():
return _progress(request, course_id, student_id)
def _progress(request, course_id, student_id):
"""
Unwrapped version of "progress".
User progress. We show the grade bar and every problem score.
Course staff are allowed to see the progress of students in their class.
"""
course = get_course_with_access(request.user, course_id, 'load', depth=None)
staff_access = has_access(request.user, course, 'staff')
if student_id is None or student_id == request.user.id:
# always allowed to see your own profile
student = request.user
else:
# Requesting access to a different student's profile
if not staff_access:
raise Http404
student = User.objects.get(id=int(student_id))
# NOTE: To make sure impersonation by instructor works, use
# student instead of request.user in the rest of the function.
# The pre-fetching of groups is done to make auth checks not require an
# additional DB lookup (this kills the Progress page in particular).
student = User.objects.prefetch_related("groups").get(id=student.id)
courseware_summary = grades.progress_summary(student, request, course)
studio_url = get_studio_url(course_id, 'settings/grading')
grade_summary = grades.grade(student, request, course)
if courseware_summary is None:
#This means the student didn't have access to the course (which the instructor requested)
raise Http404
context = {
'course': course,
'courseware_summary': courseware_summary,
'studio_url': studio_url,
'grade_summary': grade_summary,
'staff_access': staff_access,
'student': student,
'reverifications': fetch_reverify_banner_info(request, course_id)
}
with grades.manual_transaction():
response = render_to_response('courseware/progress.html', context)
return response
def fetch_reverify_banner_info(request, course_id):
"""
Fetches needed context variable to display reverification banner in courseware
"""
reverifications = defaultdict(list)
user = request.user
if not user.id:
return reverifications
enrollment = CourseEnrollment.get_or_create_enrollment(request.user, course_id)
course = course_from_id(course_id)
info = single_course_reverification_info(user, course, enrollment)
if info:
reverifications[info.status].append(info)
return reverifications
@login_required
def submission_history(request, course_id, student_username, location):
"""Render an HTML fragment (meant for inclusion elsewhere) that renders a
history of all state changes made by this user for this problem location.
Right now this only works for problems because that's all
StudentModuleHistory records.
"""
course = get_course_with_access(request.user, course_id, 'load')
staff_access = has_access(request.user, course, 'staff')
# Permission Denied if they don't have staff access and are trying to see
# somebody else's submission history.
if (student_username != request.user.username) and (not staff_access):
raise PermissionDenied
try:
student = User.objects.get(username=student_username)
student_module = StudentModule.objects.get(
course_id=course_id,
module_state_key=location,
student_id=student.id
)
except User.DoesNotExist:
return HttpResponse(escape(_(u'User {username} does not exist.').format(username=student_username)))
except StudentModule.DoesNotExist:
return HttpResponse(escape(_(u'User {username} has never accessed problem {location}').format(
username=student_username,
location=location
)))
history_entries = StudentModuleHistory.objects.filter(
student_module=student_module
).order_by('-id')
# If no history records exist, let's force a save to get history started.
if not history_entries:
student_module.save()
history_entries = StudentModuleHistory.objects.filter(
student_module=student_module
).order_by('-id')
context = {
'history_entries': history_entries,
'username': student.username,
'location': location,
'course_id': course_id
}
return render_to_response('courseware/submission_history.html', context)
def notification_image_for_tab(course_tab, user, course):
"""
Returns the notification image path for the given course_tab if applicable, otherwise None.
"""
tab_notification_handlers = {
StaffGradingTab.type: open_ended_notifications.staff_grading_notifications,
PeerGradingTab.type: open_ended_notifications.peer_grading_notifications,
OpenEndedGradingTab.type: open_ended_notifications.combined_notifications
}
if course_tab.type in tab_notification_handlers:
notifications = tab_notification_handlers[course_tab.type](course, user)
if notifications and notifications['pending_grading']:
return notifications['img_path']
return None
def get_static_tab_contents(request, course, tab):
"""
Returns the contents for the given static tab
"""
loc = Location(
course.location.tag,
course.location.org,
course.location.course,
tab.type,
tab.url_slug,
)
field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
course.id, request.user, modulestore().get_instance(course.id, loc), depth=0
)
tab_module = get_module(
request.user, request, loc, field_data_cache, course.id, static_asset_path=course.static_asset_path
)
logging.debug('course_module = {0}'.format(tab_module))
html = ''
if tab_module is not None:
try:
html = tab_module.render('student_view').content
except Exception: # pylint: disable=broad-except
html = render_to_string('courseware/error-message.html', None)
log.exception(
u"Error rendering course={course}, tab={tab_url}".format(course=course,tab_url=tab['url_slug'])
)
return html
@require_GET
def get_course_lti_endpoints(request, course_id):
"""
View that, given a course_id, returns the a JSON object that enumerates all of the LTI endpoints for that course.
The LTI 2.0 result service spec at
http://www.imsglobal.org/lti/ltiv2p0/uml/purl.imsglobal.org/vocab/lis/v2/outcomes/Result/service.html
says "This specification document does not prescribe a method for discovering the endpoint URLs." This view
function implements one way of discovering these endpoints, returning a JSON array when accessed.
Arguments:
request (django request object): the HTTP request object that triggered this view function
course_id (unicode): id associated with the course
Returns:
(django response object): HTTP response. 404 if course is not found, otherwise 200 with JSON body.
"""
try:
course = get_course(course_id, depth=2)
except ValueError: # get_course raises ValueError if course_id is invalid or doesn't refer to a course
return HttpResponse(status=404)
anonymous_user = AnonymousUser()
anonymous_user.known = False # make these "noauth" requests like module_render.handle_xblock_callback_noauth
lti_descriptors = modulestore().get_items(Location("i4x", course.org, course.number, "lti", None), course.id)
lti_noauth_modules = [
get_module_for_descriptor(
anonymous_user,
request,
descriptor,
FieldDataCache.cache_for_descriptor_descendents(
course_id,
anonymous_user,
descriptor
),
course_id
)
for descriptor in lti_descriptors
]
endpoints = [
{
'display_name': module.display_name,
'lti_2_0_result_service_json_endpoint': module.get_outcome_service_url(
service_name='lti_2_0_result_rest_handler') + "/user/{anon_user_id}",
'lti_1_1_result_service_xml_endpoint': module.get_outcome_service_url(
service_name='grade_handler'),
}
for module in lti_noauth_modules
]
return HttpResponse(json.dumps(endpoints), content_type='application/json')
| hkawasaki/kawasaki-aio8-1 | lms/djangoapps/courseware/views.py | Python | agpl-3.0 | 32,876 | 0.002555 |
import numpy as np
from week3 import lnn, tools
import os
def f(x):
if 0 <= x < 0.25:
return float(0)
elif 0.25 <= x < 0.5:
return 16.0 * (x - 0.25)
elif 0.5 <= x < 0.75:
return -16.0 * (x - 0.75)
elif 0.75 < x <= 1:
return float(0)
else:
raise ValueError('value should in [0, 1], now is {0}'.format(x))
def MCMC_SD(size=100):
"""
Assume X~U(0, 1) with only 1 dimension, then generate lots of that X,
if acceptable, add it to the result set, if not, add last X.
"""
result = []
current = 0.5
for i in range(0, size):
next_ = np.random.rand()
u = np.random.rand()
if f(current) == float(0):
condition = 0
else:
condition = min(f(next_) / f(current), 1)
if u < condition:
# accept
result.append(next_)
current = next_
else:
# refuse
result.append(current)
return result
def main():
# change the size of samples
size = 100000
data = MCMC_SD(size)
data = [[data[i]] for i in range(size)]
data = np.array(data)
true = -1.276263936
# for k in (24):
k = 27
result = []
for tr in range(k, 40, 5):
try:
entropy = lnn.LNN_2_entropy(data, k=k, tr=tr, bw=0)
print entropy
result.append(entropy)
# print 'k={0} tr={1} error={2}'.format(k, tr, error)
except ValueError, e:
print 'k={0} tr={1} error={2}'.format(k, tr, e)
except IndexError, e:
print 'k={0} tr={1} error={2}'.format(k, tr, e)
result = np.array(result)
with open('w3_klnn-estimate-result', 'a') as f:
print result-true
RMSE = tools.getRootMeanSquaredError(result, true)
f.write(':'.join([str(size), str(k), str(RMSE)]))
f.write('\n')
f.close()
print 'write for k={0} done'.format(k)
return tools.getRootMeanSquaredError(result, true)
if __name__ == '__main__':
# if os.path.exists('w3_klnn-estimate-result'):
# os.remove('w3_klnn-estimate-result')
results = []
# repeat for 50 times
for i in range(0, 50):
results.append(main())
print tools.getMean(results)
| cyruscyliu/diffentropy | week3/w3_lnn.py | Python | mit | 2,275 | 0 |
# Time: O(n)
# Space: O(n)
# Given a binary tree, return the tilt of the whole tree.
#
# The tilt of a tree node is defined as the absolute difference
# between the sum of all left subtree node values and
# the sum of all right subtree node values. Null node has tilt 0.
#
# The tilt of the whole tree is defined as the sum of all nodes' tilt.
#
# Example:
# Input:
# 1
# / \
# 2 3
# Output: 1
# Explanation:
# Tilt of node 2 : 0
# Tilt of node 3 : 0
# Tilt of node 1 : |2-3| = 1
# Tilt of binary tree : 0 + 0 + 1 = 1
# Note:
#
# The sum of node values in any subtree won't exceed
# the range of 32-bit integer.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def postOrderTraverse(root, tilt):
if not root:
return 0, tilt
left, tilt = postOrderTraverse(root.left, tilt)
right, tilt = postOrderTraverse(root.right, tilt)
tilt += abs(left-right)
return left+right+root.val, tilt
return postOrderTraverse(root, 0)[1]
| kamyu104/LeetCode | Python/binary-tree-tilt.py | Python | mit | 1,289 | 0 |
#!/usr/bin/python
#
# Generate the build trees and Makefiles for PyQwt.
import compileall
import glob
import optparse
import os
import pprint
import re
import shutil
import sys
import traceback
class Die(Exception):
def __init__(self, info):
Exception.__init__(self, info)
# __init__()
# class Die
try:
required = 'Requires at least SIP-4.6 and its development tools.'
import sipconfig
except ImportError:
raise Die, required
if 0x040600 > sipconfig._pkg_config['sip_version']:
raise Die, required
del required
def get_pyqt_configuration(options):
"""Return the PyQt configuration for Qt3 or Qt4
"""
required = 'Requires at least PyQt-3.17 and its development tools.'
options.qwt = 'qwt4qt3'
options.iqt = 'iqt4qt3'
try:
import pyqtconfig as pyqtconfig
except ImportError:
raise Die, required
if 0x031100 > pyqtconfig._pkg_config['pyqt_version']:
raise Die, required
try:
configuration = pyqtconfig.Configuration()
except AttributeError:
raise Die, 'Check if SIP and PyQt have been installed properly.'
return configuration
# get_pyqt_configuration()
def compile_qt_program(name, configuration,
extra_defines=[],
extra_include_dirs=[],
extra_lib_dirs=[],
extra_libs=[],
):
"""Compile a simple Qt application.
name is the name of the single source file
configuration is the pyqtconfig.Configuration()
extra_defines is a list of extra preprocessor definitions
extra_include_dirs is a list of extra directories to search for headers
extra_lib_dirs is a list of extra directories to search for libraries
extra_libs is a list of extra libraries
"""
makefile = sipconfig.ProgramMakefile(
configuration, console=True, qt=True, warnings=True)
makefile.extra_defines.extend(extra_defines)
makefile.extra_include_dirs.extend(extra_include_dirs)
makefile.extra_lib_dirs.extend(extra_lib_dirs)
makefile.extra_libs.extend(extra_libs)
exe, build = makefile.build_command(name)
# zap a spurious executable
try:
os.remove(exe)
except OSError:
pass
os.system(build)
if not os.access(exe, os.X_OK):
return None
if sys.platform != 'win32':
exe = './' + exe
return exe
# compile_qt_program()
def copy_files(sources, directory):
"""Copy a list of files to a directory
"""
for source in sources:
shutil.copy2(source, os.path.join(directory, os.path.basename(source)))
# copy_files()
def fix_build_file(name, extra_sources, extra_headers, extra_moc_headers):
"""Extend the targets of a SIP build file with extra files
"""
keys = ('target', 'sources', 'headers', 'moc_headers')
sbf = {}
for key in keys:
sbf[key] = []
# Parse,
nr = 0
for line in open(name, 'r'):
nr += 1
if line[0] != '#':
eq = line.find('=')
if eq == -1:
raise Die, ('"%s\" line %d: Line must be in the form '
'"key = value value...."' % (name, nr)
)
key = line[:eq].strip()
value = line[eq+1:].strip()
if key in keys:
sbf[key].append(value)
# extend,
sbf['sources'].extend(extra_sources)
sbf['headers'].extend(extra_headers)
sbf['moc_headers'].extend(extra_moc_headers)
# and write.
output = open(name, 'w')
for key in keys:
if sbf[key]:
print >> output, '%s = %s' % (key, ' '.join(sbf[key]))
# fix_build_file()
def lazy_copy_file(source, target):
"""Lazy copy a file to another file:
- check for a SIP time stamp to skip,
- check if source and target do really differ,
- copy the source file to the target if they do,
- return True on copy and False on no copy.
"""
if not os.path.exists(target):
shutil.copy2(source, target)
return True
sourcelines = open(source).readlines()
targetlines = open(target).readlines()
# global length check
if len(sourcelines) != len(targetlines):
shutil.copy2(source, target)
return True
# skip a SIP time stamp
if (len(sourcelines) > 3
and sourcelines[3].startswith(' * Generated by SIP')
):
line = 4
else:
line = 0
# line by line check
while line < len(sourcelines):
if sourcelines[line] != targetlines[line]:
shutil.copy2(source, target)
return True
line = line + 1
return False
# lazy_copy_file()
def check_numarray(configuration, options, package):
"""See if the numarray extension has been installed.
"""
if options.disable_numarray:
options.excluded_features.append("-x HAS_NUMARRAY")
return options
try:
import numarray
# Try to find numarray/arrayobject.h.
numarray_inc = os.path.join(
configuration.py_inc_dir, "numarray", "arrayobject.h")
if os.access(numarray_inc, os.F_OK):
print "Found numarray-%s.\n" % numarray.__version__
options.extra_defines.append("HAS_NUMARRAY")
else:
print ("numarray has been installed, "
"but its headers are not in the standard location.\n"
"%s will be build without support for numarray.\n"
"(Linux users may have to install a development package)\n"
) % (package,)
raise ImportError
except ImportError:
options.excluded_features.append("-x HAS_NUMARRAY")
print ("Failed to import numarray: "
"%s will be build without support for numarray.\n"
) % (package,)
return options
# check_numarray()
def check_numeric(configuration, options, package):
"""See if the Numeric extension has been installed.
"""
if options.disable_numeric:
options.excluded_features.append("-x HAS_NUMERIC")
return options
try:
import Numeric
# Try to find Numeric/arrayobject.h.
numeric_inc = os.path.join(
configuration.py_inc_dir, "Numeric", "arrayobject.h")
if os.access(numeric_inc, os.F_OK):
print "Found Numeric-%s.\n" % Numeric.__version__
options.extra_defines.append("HAS_NUMERIC")
else:
print ("Numeric has been installed, "
"but its headers are not in the standard location.\n"
"%s will be build without support for Numeric.\n"
"(Linux users may have to install a development package)\n"
) % (package,)
raise ImportError
except ImportError:
options.excluded_features.append("-x HAS_NUMERIC")
print ("Failed to find Numeric2: "
"%s will be build without support for Numeric.\n"
) % (package,)
return options
# check_numeric()
def check_numpy(configuration, options, package):
"""See if the NumPy extension has been installed.
"""
if options.disable_numpy:
options.excluded_features.append("-x HAS_NUMPY")
return options
try:
import numpy
# Try to find numpy/arrayobject.h.
from numpy.distutils.misc_util import get_numpy_include_dirs
include_dirs = get_numpy_include_dirs()
for inc_dir in include_dirs:
header = os.path.join(inc_dir, 'numpy', 'arrayobject.h')
if os.access(header, os.F_OK):
break
else:
print ('NumPy has been installed, '
'but its headers are not in the standard location.\n'
'%s will be build without support for NumPy.\n'
'(Linux users may have to install a development package)\n'
) % (package,)
raise ImportError
print 'Found NumPy-%s.\n' % numpy.__version__
options.extra_defines.append('HAS_NUMPY')
options.extra_include_dirs.extend(include_dirs)
except ImportError:
options.excluded_features.append("-x HAS_NUMPY")
print ("Failed to find NumPy: "
"%s will be build without support for NumPy.\n"
) % (package,)
return options
# check_numpy()
def check_compiler(configuration, options):
"""Check compiler specifics.
"""
print 'Do not get upset by error messages in the next 3 compiler checks:'
makefile = sipconfig.Makefile(configuration)
generator = makefile.optional_string('MAKEFILE_GENERATOR', 'UNIX')
if generator in ['MSVC', 'MSVC.NET']:
options.extra_cxxflags.extend(['-GR'])
program = '\n'.join([
r'#include <stddef.h>',
r'class a { public: void f(size_t); };',
r'void a::f(%s) {};',
r'int main() { return 0; }',
r'',
])
name = "size_t_check.cpp"
new = [
'// Automagically generated by configure.py',
'',
'// Uncomment one of the following three lines',
]
for ctype in ('unsigned int', 'unsigned long', 'unsigned long long'):
open(name, "w").write(program % ctype)
print "Check if 'size_t' and '%s' are the same type:" % ctype
if compile_qt_program(name, configuration):
comment = ''
print "YES"
else:
print "NO"
comment = '// '
new.append('%stypedef %s size_t;' % (comment, ctype))
new.extend(['',
'// Local Variables:',
'// mode: C++',
'// c-file-style: "stroustrup"',
'// End:',
'',
])
new = '\n'.join(new)
types_sip = os.path.join(os.pardir, 'sip', options.qwt, 'QwtTypes.sip')
if os.access(types_sip, os.R_OK):
old = open(types_sip, 'r').read()
else:
old = ''
if old != new:
open(types_sip, 'w').write(new)
return options
# check_compiler()
def check_os(configuration, options):
"""Check operating system specifics.
"""
print "Found '%s' operating system:" % os.name
print sys.version
if os.name == 'nt':
options.extra_defines.append('WIN32')
return options
# check_os()
def check_sip(configuration, options):
"""Check if PyQwt can be built with SIP
"""
version = configuration.sip_version
version_str = configuration.sip_version_str
print "Found SIP-%s." % version_str
if 0x040600 > version:
raise Die, 'PyQwt requires at least SIP-4.6.'
if 0x031105 > configuration.pyqt_version:
options.excluded_features.append('-x HAS_PYQT_031105')
options.extra_include_dirs.append(configuration.sip_inc_dir)
return options
# check_sip()
def check_iqt(configuration, options):
"""Check iqt module specifics.
"""
options.subdirs.append(options.iqt)
options.modules.append('iqt')
options.iqt_sipfile = os.path.join(
os.pardir, 'sip', options.iqt, 'IQtModule.sip')
return options
# check_iqt()
def check_qwt(configuration, options):
"""Check qwt module specifics.
"""
# zap all qwt_version_info*
for name in glob.glob('qwt_version_info*'):
try:
os.remove(name)
except OSError:
pass
program = '\n'.join([
r'#include <stdio.h>',
r'#include <qwt_global.h>',
r'',
r'int main(int, char **)',
r'{',
r' FILE *file;',
r'',
r' if (!(file = fopen("qwt_version_info.py", "w"))) {',
r' fprintf(stderr, "Failed to create qwt_version_info.py\n");',
r' return 1;',
r' }',
r'',
r' fprintf(file, "QWT_VERSION = %#08x\n", QWT_VERSION);',
r' fprintf(file, "QWT_VERSION_STR = \"%s\"\n", QWT_VERSION_STR);',
r'',
r' fclose(file);',
r'',
r' return 0;',
r'}',
r'',
r'// Local Variables:',
r'// mode: C++',
r'// c-file-style: "stroustrup"',
r'// End:',
r'',
])
open('qwt_version_info.cpp', 'w').write(program)
extra_include_dirs = [os.path.join(configuration.qt_inc_dir, 'Qt')]
if options.qwt_sources:
extra_include_dirs.append(os.path.join(options.qwt_sources, 'include'))
if options.extra_include_dirs:
extra_include_dirs.extend(options.extra_include_dirs)
exe = compile_qt_program('qwt_version_info.cpp', configuration,
extra_include_dirs = extra_include_dirs)
if not exe:
raise Die, 'Failed to build the qwt_version_info tool.'
os.system(exe)
try:
from qwt_version_info import QWT_VERSION, QWT_VERSION_STR
except ImportError:
raise Die, 'Failed to import qwt_version_info.'
if QWT_VERSION != 0x040200:
raise Die, 'Qwt-%s is not supported.' % QWT_VERSION_STR
print ('Found Qwt-%s.' % QWT_VERSION_STR)
options.extra_defines.append('HAS_QWT4')
options.excluded_features.append('-x HAS_QWT5')
options.subdirs.append(options.qwt)
options.modules.append('Qwt4')
options.qwt_sipfile = os.path.join(
os.pardir, 'sip', options.qwt, 'QwtModule.sip')
return options
# check_qwt()
def setup_iqt_build(configuration, options, package):
"""Setup the iqt package build
"""
if 'iqt' not in options.modules:
return
print 'Setup the iqt package build.'
build_dir = options.iqt
tmp_dir = 'tmp-' + build_dir
build_file = os.path.join(tmp_dir, '%s.sbf' % options.iqt)
# zap the temporary directory
try:
shutil.rmtree(tmp_dir)
except:
pass
# make a clean temporary directory
try:
os.mkdir(tmp_dir)
except:
raise Die, 'Failed to create the temporary build directory.'
# invoke SIP
cmd = ' '.join(
[configuration.sip_bin,
'-b', build_file,
'-c', tmp_dir,
options.jobs,
options.trace,
]
+ options.excluded_features
# SIP assumes POSIX style path separators
+ [options.iqt_sipfile.replace('\\', '/')]
)
print 'sip invokation:'
pprint.pprint(cmd)
if os.path.exists(build_file):
os.remove(build_file)
os.system(cmd)
if not os.path.exists(build_file):
raise Die, 'SIP failed to generate the C++ code.'
# copy lazily to the build directory to speed up recompilation
if not os.path.exists(build_dir):
try:
os.mkdir(build_dir)
except:
raise Die, 'Failed to create the build directory.'
lazy_copies = 0
for pattern in ('*.c', '*.cpp', '*.h', '*.py', '*.sbf'):
for source in glob.glob(os.path.join(tmp_dir, pattern)):
target = os.path.join(build_dir, os.path.basename(source))
if lazy_copy_file(source, target):
print 'Copy %s -> %s.' % (source, target)
lazy_copies += 1
print '%s file(s) lazily copied.' % lazy_copies
makefile = sipconfig.ModuleMakefile(
configuration = configuration,
build_file = os.path.basename(build_file),
dir = build_dir,
install_dir = options.module_install_path,
qt = 1,
warnings = 1,
debug = options.debug
)
makefile._target = '_iqt'
makefile.extra_cflags.extend(options.extra_cflags)
makefile.extra_cxxflags.extend(options.extra_cxxflags)
makefile.extra_defines.extend(options.extra_defines)
makefile.extra_include_dirs.extend(options.extra_include_dirs)
makefile.extra_lflags.extend(options.extra_lflags)
makefile.extra_libs.extend(options.extra_libs)
makefile.extra_lib_dirs.extend(options.extra_lib_dirs)
makefile.generate()
# setup_iqt_build()
def setup_qwt4_build(configuration, options, package):
"""Setup the qwt package build
"""
if 'Qwt4' not in options.modules:
return
print 'Setup the qwt package build.'
build_dir = options.qwt
tmp_dir = 'tmp-%s' % options.qwt
build_file = os.path.join(tmp_dir, '%s.sbf' % options.qwt)
extra_sources = []
extra_headers = []
extra_moc_headers = []
extra_py_files = glob.glob(
os.path.join(os.pardir, 'qt3lib', 'Qwt4', '*.py'))
# do we compile and link the sources of Qwt statically into PyQwt?
if options.qwt_sources:
extra_sources += glob.glob(os.path.join(
options.qwt_sources, 'src', '*.cpp'))
extra_headers += glob.glob(os.path.join(
options.qwt_sources, 'include', '*.h'))
extra_moc_headers = []
for header in extra_headers:
text = open(header).read()
if re.compile(r'^\s*Q_OBJECT', re.M).search(text):
extra_moc_headers.append(header)
# add the interface to the numerical Python extensions
extra_sources += glob.glob(os.path.join(os.pardir, 'support', '*.cpp'))
extra_headers += glob.glob(os.path.join(os.pardir, 'support', '*.h'))
# do we compile and link the sources of Qwt into PyQwt?
if options.qwt_sources:
# yes, zap all 'qwt'
while options.extra_libs.count('qwt'):
options.extra_libs.remove('qwt')
elif 'qwt' not in options.extra_libs:
# no, add 'qwt' if needed
options.extra_libs.append('qwt')
# zap the temporary directory
try:
shutil.rmtree(tmp_dir)
except:
pass
# make a clean temporary directory
try:
os.mkdir(tmp_dir)
except:
raise Die, 'Failed to create the temporary build directory.'
# copy the extra files
copy_files(extra_sources, tmp_dir)
copy_files(extra_headers, tmp_dir)
copy_files(extra_moc_headers, tmp_dir)
copy_files(extra_py_files, tmp_dir)
try: # Qt4
pyqt_sip_flags = configuration.pyqt_sip_flags
except AttributeError: # Qt3
pyqt_sip_flags = configuration.pyqt_qt_sip_flags
# invoke SIP
cmd = ' '.join(
[configuration.sip_bin,
# SIP assumes POSIX style path separators
'-I', configuration.pyqt_sip_dir.replace('\\', '/'),
'-b', build_file,
'-c', tmp_dir,
options.jobs,
options.trace,
pyqt_sip_flags,
]
+ options.sip_include_dirs
+ options.excluded_features
+ options.timelines
# SIP assumes POSIX style path separators
+ [options.qwt_sipfile.replace('\\', '/')]
)
print 'sip invokation:'
pprint.pprint(cmd)
if os.path.exists(build_file):
os.remove(build_file)
os.system(cmd)
if not os.path.exists(build_file):
raise Die, 'SIP failed to generate the C++ code.'
# FIXME: sip-4.7 does not generate those include files anymore
for name in [os.path.join(tmp_dir, name) for name in [
'sipQwtQwtArrayDouble.h',
'sipQwtQwtArrayInt.h',
'sipQwtQwtArrayQwtDoublePoint.h',
]]:
if not os.path.exists(name):
open(name, 'w')
# fix the SIP build file
fix_build_file(build_file,
[os.path.basename(f) for f in extra_sources],
[os.path.basename(f) for f in extra_headers],
[os.path.basename(f) for f in extra_moc_headers])
# copy lazily to the build directory to speed up recompilation
if not os.path.exists(build_dir):
try:
os.mkdir(build_dir)
except:
raise Die, 'Failed to create the build directory.'
lazy_copies = 0
for pattern in ('*.c', '*.cpp', '*.h', '*.py', '*.sbf'):
for source in glob.glob(os.path.join(tmp_dir, pattern)):
target = os.path.join(build_dir, os.path.basename(source))
if lazy_copy_file(source, target):
print 'Copy %s -> %s.' % (source, target)
lazy_copies += 1
print '%s file(s) lazily copied.' % lazy_copies
# byte-compile the Python files
compileall.compile_dir(build_dir, 1, options.module_install_path)
# files to be installed
installs = []
installs.append([[os.path.basename(f) for f in glob.glob(
os.path.join(build_dir, '*.py*'))], options.module_install_path])
pattern = os.path.join(os.pardir, 'sip', options.qwt, '*.sip')
installs.append(
[[os.path.join(os.pardir, f) for f in glob.glob(pattern)],
os.path.join(configuration.pyqt_sip_dir, 'Qwt4')])
pattern = os.path.join(os.pardir, 'sip', options.qwt, 'common', '*.sip')
installs.append(
[[os.path.join(os.pardir, f) for f in glob.glob(pattern)],
os.path.join(configuration.pyqt_sip_dir, 'Qwt4', 'common')])
# module makefile
makefile = sipconfig.ModuleMakefile(
configuration = configuration,
build_file = os.path.basename(build_file),
dir = build_dir,
install_dir = options.module_install_path,
installs = installs,
qt = 1,
warnings = 1,
debug = options.debug,
)
makefile.extra_cflags.extend(options.extra_cflags)
makefile.extra_cxxflags.extend(options.extra_cxxflags)
makefile.extra_defines.extend(options.extra_defines)
makefile.extra_include_dirs.extend(options.extra_include_dirs)
makefile.extra_lflags.extend(options.extra_lflags)
makefile.extra_libs.extend(options.extra_libs)
makefile.extra_lib_dirs.extend(options.extra_lib_dirs)
makefile.generate()
# setup_qwt5_build()
def setup_parent_build(configuration, options):
"""Generate the parent Makefile
"""
print "Setup the PyQwt build."
sipconfig.ParentMakefile(configuration = configuration,
subdirs = options.subdirs).generate()
# setup_main_build
def parse_args():
"""Return the parsed options and args from the command line
"""
usage = (
'python configure.py [options]'
'\n\nEach option takes at most one argument, but some options'
'\naccumulate arguments when repeated. For example, invoke:'
'\n\n\tpython configure.py -I %s -I %s'
'\n\nto search the current *and* parent directories for headers.'
) % (os.curdir, os.pardir)
parser = optparse.OptionParser(usage=usage)
common_options = optparse.OptionGroup(parser, 'Common options')
common_options.add_option(
'-Q', '--qwt-sources', default='', action='store',
type='string', metavar='/sources/of/qwt',
help=('compile and link the Qwt source files in'
' /sources/of/qwt statically into PyQwt'))
common_options.add_option(
'-I', '--extra-include-dirs', default=[], action='append',
type='string', metavar='/usr/lib/qt3/include/qwt',
help=('add an extra directory to search for headers'
' (the compiler must be able to find the Qwt headers'
' without the -Q option)'))
common_options.add_option(
'-L', '--extra-lib-dirs', default=[], action='append',
type='string', metavar='/usr/lib/qt3/lib',
help=('add an extra directory to search for libraries'
' (the linker must be able to find the Qwt library'
' without the -Q option)'))
common_options.add_option(
'-j', '--jobs', default=0, action='store',
type='int', metavar='N',
help=('concatenate the SIP generated code into N files'
' [default 1 per class] (to speed up make by running '
' simultaneous jobs on multiprocessor systems)'))
parser.add_option_group(common_options)
make_options = optparse.OptionGroup(parser, 'Make options')
make_options.add_option(
'--debug', default=False, action='store_true',
help='enable debugging symbols [default disabled]')
make_options.add_option(
'--extra-cflags', default=[], action='append',
type='string', metavar='EXTRA_CFLAG',
help='add an extra C compiler flag')
make_options.add_option(
'--extra-cxxflags', default=[], action='append',
type='string', metavar='EXTRA_CXXFLAG',
help='add an extra C++ compiler flag')
make_options.add_option(
'-D', '--extra-defines', default=[], action='append',
type='string', metavar='HAS_EXTRA_SENSORY_PERCEPTION',
help='add an extra preprocessor definition')
make_options.add_option(
'-l', '--extra-libs', default=[], action='append',
type='string', metavar='extra_sensory_perception',
help='add an extra library')
make_options.add_option(
'--extra-lflags', default=[], action='append',
type='string', metavar='EXTRA_LFLAG',
help='add an extra linker flag')
parser.add_option_group(make_options)
sip_options = optparse.OptionGroup(parser, 'SIP options')
sip_options.add_option(
'-x', '--excluded-features', default=[], action='append',
type='string', metavar='EXTRA_SENSORY_PERCEPTION',
help=('add a feature for SIP to exclude'
' (normally one of the features in sip/features.sip)'))
sip_options.add_option(
'-t', '--timelines', default=[], action='append',
type='string', metavar='EXTRA_SENSORY_PERCEPTION',
help=('add a timeline option for SIP'
' (normally one of the timeline options in sip/timelines.sip)'))
sip_options.add_option(
'--sip-include-dirs', default=[],
action='append', type='string', metavar='SIP_INCLUDE_DIR',
help='add an extra directory for SIP to search')
sip_options.add_option(
'--trace', default=False, action='store_true',
help=('enable trace of the execution of the bindings'
' [default disabled]'))
parser.add_option_group(sip_options)
detection_options = optparse.OptionGroup(parser, 'Detection options')
detection_options.add_option(
'--disable-numarray', default=False, action='store_true',
help='disable detection and use of numarray [default enabled]'
)
detection_options.add_option(
'--disable-numeric', default=False, action='store_true',
help='disable detection and use of Numeric [default enabled]'
)
detection_options.add_option(
'--disable-numpy', default=False, action='store_true',
help='disable detection and use of NumPy [default enabled]'
)
parser.add_option_group(detection_options)
install_options = optparse.OptionGroup(parser, 'Install options')
install_options.add_option(
'--module-install-path', default='', action='store',
help= 'specify the install directory for the Python modules'
)
parser.add_option_group(install_options)
options, args = parser.parse_args()
# tweak some of the options to facilitate later processing
if options.jobs < 1:
options.jobs = ''
else:
options.jobs = '-j %s' % options.jobs
options.excluded_features = [
('-x %s' % f) for f in options.excluded_features
]
# SIP assumes POSIX style path separators
options.sip_include_dirs = [
('-I %s' % f).replace('\\', '/') for f in options.sip_include_dirs
]
options.timelines = [
('-t %s' % t) for t in options.timelines
]
if options.trace:
options.trace = '-r'
options.extra_defines.append('TRACE_PYQWT')
else:
options.trace = ''
options.modules = []
options.subdirs = []
return options, args
# parse_args()
def main():
"""Generate the build tree and the Makefiles
"""
options, args = parse_args()
print 'Command line options:'
pprint.pprint(options.__dict__)
print
configuration = get_pyqt_configuration(options)
options = check_sip(configuration, options)
options = check_os(configuration, options)
options = check_compiler(configuration, options)
options = check_numarray(configuration, options, 'PyQwt')
options = check_numeric(configuration, options, 'PyQwt')
options = check_numpy(configuration, options, 'PyQwt')
options = check_iqt(configuration, options)
options = check_qwt(configuration, options)
if not options.module_install_path:
options.module_install_path = os.path.join(
configuration.pyqt_mod_dir, 'Qwt4')
print
print 'Extended command line options:'
pprint.pprint(options.__dict__)
print
print 'The following modules will be built: %s.' % options.modules
print
setup_iqt_build(configuration, options, 'PyQwt')
print
setup_qwt4_build(configuration, options, 'PyQwt')
print
setup_parent_build(configuration, options)
print
print 'Great, run make or nmake to build and install PyQwt.'
# main()
if __name__ == '__main__':
try:
main()
except Die, info:
print info
sys.exit(1)
except:
# catch the optparse --help option
for entry in traceback.extract_tb(sys.exc_info()[-1]):
if 'optparse.py' in entry[0]:
sys.exit(0)
else:
print (
'An internal error occured. Please report all the output\n'
'from the program, including the following traceback, to\n'
'pyqwt-users@lists.sourceforge.net'
)
traceback.print_exc()
sys.exit(1)
# Local Variables: ***
# mode: python ***
# End: ***
| PyQwt/PyQwt4 | configure/configure.py | Python | gpl-2.0 | 29,680 | 0.003605 |
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import string
import testtools
import mock
from neutron.api.v2 import attributes
from neutron.common import exceptions as n_exc
from neutron.tests import base
class TestAttributes(base.BaseTestCase):
def _construct_dict_and_constraints(self):
"""Constructs a test dictionary and a definition of constraints.
:return: A (dictionary, constraint) tuple
"""
constraints = {'key1': {'type:values': ['val1', 'val2'],
'required': True},
'key2': {'type:string': None,
'required': False},
'key3': {'type:dict': {'k4': {'type:string': None,
'required': True}},
'required': True}}
dictionary = {'key1': 'val1',
'key2': 'a string value',
'key3': {'k4': 'a string value'}}
return dictionary, constraints
def test_is_attr_set(self):
data = attributes.ATTR_NOT_SPECIFIED
self.assertIs(attributes.is_attr_set(data), False)
data = None
self.assertIs(attributes.is_attr_set(data), False)
data = "I'm set"
self.assertIs(attributes.is_attr_set(data), True)
def test_validate_values(self):
msg = attributes._validate_values(4, [4, 6])
self.assertIsNone(msg)
msg = attributes._validate_values(4, (4, 6))
self.assertIsNone(msg)
msg = attributes._validate_values(7, [4, 6])
self.assertEqual("'7' is not in [4, 6]", msg)
msg = attributes._validate_values(7, (4, 6))
self.assertEqual("'7' is not in (4, 6)", msg)
def test_validate_not_empty_string(self):
msg = attributes._validate_not_empty_string(' ', None)
self.assertEqual(u"' ' Blank strings are not permitted", msg)
def test_validate_not_empty_string_or_none(self):
msg = attributes._validate_not_empty_string_or_none(' ', None)
self.assertEqual(u"' ' Blank strings are not permitted", msg)
msg = attributes._validate_not_empty_string_or_none(None, None)
self.assertIsNone(msg)
def test_validate_string_or_none(self):
msg = attributes._validate_not_empty_string_or_none('test', None)
self.assertIsNone(msg)
msg = attributes._validate_not_empty_string_or_none(None, None)
self.assertIsNone(msg)
def test_validate_string(self):
msg = attributes._validate_string(None, None)
self.assertEqual("'None' is not a valid string", msg)
# 0 == len(data) == max_len
msg = attributes._validate_string("", 0)
self.assertIsNone(msg)
# 0 == len(data) < max_len
msg = attributes._validate_string("", 9)
self.assertIsNone(msg)
# 0 < len(data) < max_len
msg = attributes._validate_string("123456789", 10)
self.assertIsNone(msg)
# 0 < len(data) == max_len
msg = attributes._validate_string("123456789", 9)
self.assertIsNone(msg)
# 0 < max_len < len(data)
msg = attributes._validate_string("1234567890", 9)
self.assertEqual("'1234567890' exceeds maximum length of 9", msg)
msg = attributes._validate_string("123456789", None)
self.assertIsNone(msg)
def test_validate_no_whitespace(self):
data = 'no_white_space'
result = attributes._validate_no_whitespace(data)
self.assertEqual(data, result)
self.assertRaises(n_exc.InvalidInput,
attributes._validate_no_whitespace,
'i have whitespace')
self.assertRaises(n_exc.InvalidInput,
attributes._validate_no_whitespace,
'i\thave\twhitespace')
for ws in string.whitespace:
self.assertRaises(n_exc.InvalidInput,
attributes._validate_no_whitespace,
'%swhitespace-at-head' % ws)
self.assertRaises(n_exc.InvalidInput,
attributes._validate_no_whitespace,
'whitespace-at-tail%s' % ws)
def test_validate_range(self):
msg = attributes._validate_range(1, [1, 9])
self.assertIsNone(msg)
msg = attributes._validate_range(5, [1, 9])
self.assertIsNone(msg)
msg = attributes._validate_range(9, [1, 9])
self.assertIsNone(msg)
msg = attributes._validate_range(1, (1, 9))
self.assertIsNone(msg)
msg = attributes._validate_range(5, (1, 9))
self.assertIsNone(msg)
msg = attributes._validate_range(9, (1, 9))
self.assertIsNone(msg)
msg = attributes._validate_range(0, [1, 9])
self.assertEqual("'0' is too small - must be at least '1'", msg)
msg = attributes._validate_range(10, (1, 9))
self.assertEqual("'10' is too large - must be no larger than '9'", msg)
msg = attributes._validate_range("bogus", (1, 9))
self.assertEqual("'bogus' is not an integer", msg)
msg = attributes._validate_range(10, (attributes.UNLIMITED,
attributes.UNLIMITED))
self.assertIsNone(msg)
msg = attributes._validate_range(10, (1, attributes.UNLIMITED))
self.assertIsNone(msg)
msg = attributes._validate_range(1, (attributes.UNLIMITED, 9))
self.assertIsNone(msg)
msg = attributes._validate_range(-1, (0, attributes.UNLIMITED))
self.assertEqual("'-1' is too small - must be at least '0'", msg)
msg = attributes._validate_range(10, (attributes.UNLIMITED, 9))
self.assertEqual("'10' is too large - must be no larger than '9'", msg)
def _test_validate_mac_address(self, validator, allow_none=False):
mac_addr = "ff:16:3e:4f:00:00"
msg = validator(mac_addr)
self.assertIsNone(msg)
mac_addr = "ffa:16:3e:4f:00:00"
msg = validator(mac_addr)
err_msg = "'%s' is not a valid MAC address"
self.assertEqual(err_msg % mac_addr, msg)
mac_addr = "123"
msg = validator(mac_addr)
self.assertEqual(err_msg % mac_addr, msg)
mac_addr = None
msg = validator(mac_addr)
if allow_none:
self.assertIsNone(msg)
else:
self.assertEqual(err_msg % mac_addr, msg)
mac_addr = "ff:16:3e:4f:00:00\r"
msg = validator(mac_addr)
self.assertEqual(err_msg % mac_addr, msg)
def test_validate_mac_address(self):
self._test_validate_mac_address(attributes._validate_mac_address)
def test_validate_mac_address_or_none(self):
self._test_validate_mac_address(
attributes._validate_mac_address_or_none, allow_none=True)
def test_validate_ip_address(self):
ip_addr = '1.1.1.1'
msg = attributes._validate_ip_address(ip_addr)
self.assertIsNone(msg)
ip_addr = '1111.1.1.1'
msg = attributes._validate_ip_address(ip_addr)
self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
# Depending on platform to run UTs, this case might or might not be
# an equivalent to test_validate_ip_address_bsd.
ip_addr = '1' * 59
msg = attributes._validate_ip_address(ip_addr)
self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
ip_addr = '1.1.1.1 has whitespace'
msg = attributes._validate_ip_address(ip_addr)
self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
ip_addr = '111.1.1.1\twhitespace'
msg = attributes._validate_ip_address(ip_addr)
self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
ip_addr = '111.1.1.1\nwhitespace'
msg = attributes._validate_ip_address(ip_addr)
self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
for ws in string.whitespace:
ip_addr = '%s111.1.1.1' % ws
msg = attributes._validate_ip_address(ip_addr)
self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
for ws in string.whitespace:
ip_addr = '111.1.1.1%s' % ws
msg = attributes._validate_ip_address(ip_addr)
self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
def test_validate_ip_address_bsd(self):
# NOTE(yamamoto): On NetBSD and OS X, netaddr.IPAddress() accepts
# '1' * 59 as a valid address. The behaviour is inherited from
# libc behaviour there. This test ensures that our validator reject
# such addresses on such platforms by mocking netaddr to emulate
# the behaviour.
ip_addr = '1' * 59
with mock.patch('netaddr.IPAddress') as ip_address_cls:
msg = attributes._validate_ip_address(ip_addr)
ip_address_cls.assert_called_once_with(ip_addr)
self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
def test_validate_ip_pools(self):
pools = [[{'end': '10.0.0.254'}],
[{'start': '10.0.0.254'}],
[{'start': '1000.0.0.254',
'end': '1.1.1.1'}],
[{'start': '10.0.0.2', 'end': '10.0.0.254',
'forza': 'juve'}],
[{'start': '10.0.0.2', 'end': '10.0.0.254'},
{'end': '10.0.0.254'}],
[None],
None]
for pool in pools:
msg = attributes._validate_ip_pools(pool)
self.assertIsNotNone(msg)
pools = [[{'end': '10.0.0.254', 'start': '10.0.0.2'},
{'start': '11.0.0.2', 'end': '11.1.1.1'}],
[{'start': '11.0.0.2', 'end': '11.0.0.100'}]]
for pool in pools:
msg = attributes._validate_ip_pools(pool)
self.assertIsNone(msg)
invalid_ip = '10.0.0.2\r'
pools = [[{'end': '10.0.0.254', 'start': invalid_ip}]]
for pool in pools:
msg = attributes._validate_ip_pools(pool)
self.assertEqual("'%s' is not a valid IP address" % invalid_ip,
msg)
def test_validate_fixed_ips(self):
fixed_ips = [
{'data': [{'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
'ip_address': '1111.1.1.1'}],
'error_msg': "'1111.1.1.1' is not a valid IP address"},
{'data': [{'subnet_id': 'invalid',
'ip_address': '1.1.1.1'}],
'error_msg': "'invalid' is not a valid UUID"},
{'data': None,
'error_msg': "Invalid data format for fixed IP: 'None'"},
{'data': "1.1.1.1",
'error_msg': "Invalid data format for fixed IP: '1.1.1.1'"},
{'data': ['00000000-ffff-ffff-ffff-000000000000', '1.1.1.1'],
'error_msg': "Invalid data format for fixed IP: "
"'00000000-ffff-ffff-ffff-000000000000'"},
{'data': [['00000000-ffff-ffff-ffff-000000000000', '1.1.1.1']],
'error_msg': "Invalid data format for fixed IP: "
"'['00000000-ffff-ffff-ffff-000000000000', "
"'1.1.1.1']'"},
{'data': [{'subnet_id': '00000000-0fff-ffff-ffff-000000000000',
'ip_address': '1.1.1.1'},
{'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
'ip_address': '1.1.1.1'}],
'error_msg': "Duplicate IP address '1.1.1.1'"}]
for fixed in fixed_ips:
msg = attributes._validate_fixed_ips(fixed['data'])
self.assertEqual(fixed['error_msg'], msg)
fixed_ips = [[{'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
'ip_address': '1.1.1.1'}],
[{'subnet_id': '00000000-0fff-ffff-ffff-000000000000',
'ip_address': '1.1.1.1'},
{'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
'ip_address': '1.1.1.2'}]]
for fixed in fixed_ips:
msg = attributes._validate_fixed_ips(fixed)
self.assertIsNone(msg)
def test_validate_nameservers(self):
ns_pools = [['1.1.1.2', '1.1.1.2'],
['www.hostname.com', 'www.hostname.com'],
['1000.0.0.1'],
None]
for ns in ns_pools:
msg = attributes._validate_nameservers(ns, None)
self.assertIsNotNone(msg)
ns_pools = [['100.0.0.2'],
['www.hostname.com'],
['www.great.marathons.to.travel'],
['valid'],
['77.hostname.com'],
['1' * 59],
['www.internal.hostname.com']]
for ns in ns_pools:
msg = attributes._validate_nameservers(ns, None)
self.assertIsNone(msg)
def test_validate_hostroutes(self):
hostroute_pools = [[{'destination': '100.0.0.0/24'}],
[{'nexthop': '10.0.2.20'}],
[{'nexthop': '10.0.2.20',
'forza': 'juve',
'destination': '100.0.0.0/8'}],
[{'nexthop': '1110.0.2.20',
'destination': '100.0.0.0/8'}],
[{'nexthop': '10.0.2.20',
'destination': '100.0.0.0'}],
[{'nexthop': '10.0.2.20',
'destination': '100.0.0.0/8'},
{'nexthop': '10.0.2.20',
'destination': '100.0.0.0/8'}],
[None],
None]
for host_routes in hostroute_pools:
msg = attributes._validate_hostroutes(host_routes, None)
self.assertIsNotNone(msg)
hostroute_pools = [[{'destination': '100.0.0.0/24',
'nexthop': '10.0.2.20'}],
[{'nexthop': '10.0.2.20',
'destination': '100.0.0.0/8'},
{'nexthop': '10.0.2.20',
'destination': '101.0.0.0/8'}]]
for host_routes in hostroute_pools:
msg = attributes._validate_hostroutes(host_routes, None)
self.assertIsNone(msg)
def test_validate_ip_address_or_none(self):
ip_addr = None
msg = attributes._validate_ip_address_or_none(ip_addr)
self.assertIsNone(msg)
ip_addr = '1.1.1.1'
msg = attributes._validate_ip_address_or_none(ip_addr)
self.assertIsNone(msg)
ip_addr = '1111.1.1.1'
msg = attributes._validate_ip_address_or_none(ip_addr)
self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
def test_hostname_pattern(self):
bad_values = ['@openstack', 'ffff.abcdefg' * 26, 'f' * 80, '-hello',
'goodbye-', 'example..org']
for data in bad_values:
msg = attributes._validate_hostname(data)
self.assertIsNotNone(msg)
# All numeric hostnames are allowed per RFC 1123 section 2.1
good_values = ['www.openstack.org', '1234x', '1234',
'openstack-1', 'v.xyz', '1' * 50, 'a1a',
'x.x1x', 'x.yz', 'example.org.']
for data in good_values:
msg = attributes._validate_hostname(data)
self.assertIsNone(msg)
def test_uuid_pattern(self):
data = 'garbage'
msg = attributes._validate_regex(data, attributes.UUID_PATTERN)
self.assertIsNotNone(msg)
data = '00000000-ffff-ffff-ffff-000000000000'
msg = attributes._validate_regex(data, attributes.UUID_PATTERN)
self.assertIsNone(msg)
def test_mac_pattern(self):
# Valid - 3 octets
base_mac = "fa:16:3e:00:00:00"
msg = attributes._validate_regex(base_mac,
attributes.MAC_PATTERN)
self.assertIsNone(msg)
# Valid - 4 octets
base_mac = "fa:16:3e:4f:00:00"
msg = attributes._validate_regex(base_mac,
attributes.MAC_PATTERN)
self.assertIsNone(msg)
# Invalid - not unicast
base_mac = "01:16:3e:4f:00:00"
msg = attributes._validate_regex(base_mac,
attributes.MAC_PATTERN)
self.assertIsNotNone(msg)
# Invalid - invalid format
base_mac = "a:16:3e:4f:00:00"
msg = attributes._validate_regex(base_mac,
attributes.MAC_PATTERN)
self.assertIsNotNone(msg)
# Invalid - invalid format
base_mac = "ffa:16:3e:4f:00:00"
msg = attributes._validate_regex(base_mac,
attributes.MAC_PATTERN)
self.assertIsNotNone(msg)
# Invalid - invalid format
base_mac = "01163e4f0000"
msg = attributes._validate_regex(base_mac,
attributes.MAC_PATTERN)
self.assertIsNotNone(msg)
# Invalid - invalid format
base_mac = "01-16-3e-4f-00-00"
msg = attributes._validate_regex(base_mac,
attributes.MAC_PATTERN)
self.assertIsNotNone(msg)
# Invalid - invalid format
base_mac = "00:16:3:f:00:00"
msg = attributes._validate_regex(base_mac,
attributes.MAC_PATTERN)
self.assertIsNotNone(msg)
# Invalid - invalid format
base_mac = "12:3:4:5:67:89ab"
msg = attributes._validate_regex(base_mac,
attributes.MAC_PATTERN)
self.assertIsNotNone(msg)
def _test_validate_subnet(self, validator, allow_none=False):
# Valid - IPv4
cidr = "10.0.2.0/24"
msg = validator(cidr, None)
self.assertIsNone(msg)
# Valid - IPv6 without final octets
cidr = "fe80::/24"
msg = validator(cidr, None)
self.assertIsNone(msg)
# Valid - IPv6 with final octets
cidr = "fe80::/24"
msg = validator(cidr, None)
self.assertIsNone(msg)
# Valid - uncompressed ipv6 address
cidr = "fe80:0:0:0:0:0:0:0/128"
msg = validator(cidr, None)
self.assertIsNone(msg)
# Valid - ipv6 address with multiple consecutive zero
cidr = "2001:0db8:0:0:1::1/128"
msg = validator(cidr, None)
self.assertIsNone(msg)
# Valid - ipv6 address with multiple consecutive zero
cidr = "2001:0db8::1:0:0:1/128"
msg = validator(cidr, None)
self.assertIsNone(msg)
# Valid - ipv6 address with multiple consecutive zero
cidr = "2001::0:1:0:0:1100/120"
msg = validator(cidr, None)
self.assertIsNone(msg)
# Valid - abbreviated ipv4 address
cidr = "10/24"
msg = validator(cidr, None)
self.assertIsNone(msg)
# Invalid - IPv4 missing mask
cidr = "10.0.2.0"
msg = validator(cidr, None)
error = _("'%(data)s' isn't a recognized IP subnet cidr,"
" '%(cidr)s' is recommended") % {"data": cidr,
"cidr": "10.0.2.0/32"}
self.assertEqual(error, msg)
# Valid - IPv4 with non-zero masked bits is ok
for i in range(1, 255):
cidr = "192.168.1.%s/24" % i
msg = validator(cidr, None)
self.assertIsNone(msg)
# Invalid - IPv6 without final octets, missing mask
cidr = "fe80::"
msg = validator(cidr, None)
error = _("'%(data)s' isn't a recognized IP subnet cidr,"
" '%(cidr)s' is recommended") % {"data": cidr,
"cidr": "fe80::/128"}
self.assertEqual(error, msg)
# Invalid - IPv6 with final octets, missing mask
cidr = "fe80::0"
msg = validator(cidr, None)
error = _("'%(data)s' isn't a recognized IP subnet cidr,"
" '%(cidr)s' is recommended") % {"data": cidr,
"cidr": "fe80::/128"}
self.assertEqual(error, msg)
# Invalid - Address format error
cidr = 'invalid'
msg = validator(cidr, None)
error = "'%s' is not a valid IP subnet" % cidr
self.assertEqual(error, msg)
cidr = None
msg = validator(cidr, None)
if allow_none:
self.assertIsNone(msg)
else:
error = "'%s' is not a valid IP subnet" % cidr
self.assertEqual(error, msg)
# Invalid - IPv4 with trailing CR
cidr = "10.0.2.0/24\r"
msg = validator(cidr, None)
error = "'%s' is not a valid IP subnet" % cidr
self.assertEqual(error, msg)
def test_validate_subnet(self):
self._test_validate_subnet(attributes._validate_subnet)
def test_validate_subnet_or_none(self):
self._test_validate_subnet(attributes._validate_subnet_or_none,
allow_none=True)
def _test_validate_regex(self, validator, allow_none=False):
pattern = '[hc]at'
data = None
msg = validator(data, pattern)
if allow_none:
self.assertIsNone(msg)
else:
self.assertEqual("'None' is not a valid input", msg)
data = 'bat'
msg = validator(data, pattern)
self.assertEqual("'%s' is not a valid input" % data, msg)
data = 'hat'
msg = validator(data, pattern)
self.assertIsNone(msg)
data = 'cat'
msg = validator(data, pattern)
self.assertIsNone(msg)
def test_validate_regex(self):
self._test_validate_regex(attributes._validate_regex)
def test_validate_regex_or_none(self):
self._test_validate_regex(attributes._validate_regex_or_none,
allow_none=True)
def test_validate_uuid(self):
msg = attributes._validate_uuid('garbage')
self.assertEqual("'garbage' is not a valid UUID", msg)
msg = attributes._validate_uuid('00000000-ffff-ffff-ffff-000000000000')
self.assertIsNone(msg)
def test_validate_uuid_list(self):
# check not a list
uuids = [None,
123,
'e5069610-744b-42a7-8bd8-ceac1a229cd4',
'12345678123456781234567812345678',
{'uuid': 'e5069610-744b-42a7-8bd8-ceac1a229cd4'}]
for uuid in uuids:
msg = attributes._validate_uuid_list(uuid)
error = "'%s' is not a list" % uuid
self.assertEqual(error, msg)
# check invalid uuid in a list
invalid_uuid_lists = [[None],
[123],
[123, 'e5069610-744b-42a7-8bd8-ceac1a229cd4'],
['123', '12345678123456781234567812345678'],
['t5069610-744b-42a7-8bd8-ceac1a229cd4'],
['e5069610-744b-42a7-8bd8-ceac1a229cd44'],
['e50696100-744b-42a7-8bd8-ceac1a229cd4'],
['e5069610-744bb-42a7-8bd8-ceac1a229cd4']]
for uuid_list in invalid_uuid_lists:
msg = attributes._validate_uuid_list(uuid_list)
error = "'%s' is not a valid UUID" % uuid_list[0]
self.assertEqual(error, msg)
# check duplicate items in a list
duplicate_uuids = ['e5069610-744b-42a7-8bd8-ceac1a229cd4',
'f3eeab00-8367-4524-b662-55e64d4cacb5',
'e5069610-744b-42a7-8bd8-ceac1a229cd4']
msg = attributes._validate_uuid_list(duplicate_uuids)
error = ("Duplicate items in the list: "
"'%s'" % ', '.join(duplicate_uuids))
self.assertEqual(error, msg)
# check valid uuid lists
valid_uuid_lists = [['e5069610-744b-42a7-8bd8-ceac1a229cd4'],
['f3eeab00-8367-4524-b662-55e64d4cacb5'],
['e5069610-744b-42a7-8bd8-ceac1a229cd4',
'f3eeab00-8367-4524-b662-55e64d4cacb5']]
for uuid_list in valid_uuid_lists:
msg = attributes._validate_uuid_list(uuid_list)
self.assertIsNone(msg)
def test_validate_dict_type(self):
for value in (None, True, '1', []):
self.assertEqual("'%s' is not a dictionary" % value,
attributes._validate_dict(value))
def test_validate_dict_without_constraints(self):
msg = attributes._validate_dict({})
self.assertIsNone(msg)
# Validate a dictionary without constraints.
msg = attributes._validate_dict({'key': 'value'})
self.assertIsNone(msg)
def test_validate_a_valid_dict_with_constraints(self):
dictionary, constraints = self._construct_dict_and_constraints()
msg = attributes._validate_dict(dictionary, constraints)
self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
def test_validate_dict_with_invalid_validator(self):
dictionary, constraints = self._construct_dict_and_constraints()
constraints['key1'] = {'type:unsupported': None, 'required': True}
msg = attributes._validate_dict(dictionary, constraints)
self.assertEqual("Validator 'type:unsupported' does not exist.", msg)
def test_validate_dict_not_required_keys(self):
dictionary, constraints = self._construct_dict_and_constraints()
del dictionary['key2']
msg = attributes._validate_dict(dictionary, constraints)
self.assertIsNone(msg, 'Field that was not required by the specs was'
'required by the validator.')
def test_validate_dict_required_keys(self):
dictionary, constraints = self._construct_dict_and_constraints()
del dictionary['key1']
msg = attributes._validate_dict(dictionary, constraints)
self.assertIn('Expected keys:', msg)
def test_validate_dict_wrong_values(self):
dictionary, constraints = self._construct_dict_and_constraints()
dictionary['key1'] = 'UNSUPPORTED'
msg = attributes._validate_dict(dictionary, constraints)
self.assertIsNotNone(msg)
def test_validate_dict_convert_boolean(self):
dictionary, constraints = self._construct_dict_and_constraints()
constraints['key_bool'] = {
'type:boolean': None,
'required': False,
'convert_to': attributes.convert_to_boolean}
dictionary['key_bool'] = 'true'
msg = attributes._validate_dict(dictionary, constraints)
self.assertIsNone(msg)
# Explicitly comparing with literal 'True' as assertTrue
# succeeds also for 'true'
self.assertIs(True, dictionary['key_bool'])
def test_subdictionary(self):
dictionary, constraints = self._construct_dict_and_constraints()
del dictionary['key3']['k4']
dictionary['key3']['k5'] = 'a string value'
msg = attributes._validate_dict(dictionary, constraints)
self.assertIn('Expected keys:', msg)
def test_validate_dict_or_none(self):
dictionary, constraints = self._construct_dict_and_constraints()
# Check whether None is a valid value.
msg = attributes._validate_dict_or_none(None, constraints)
self.assertIsNone(msg, 'Validation of a None dictionary failed.')
# Check validation of a regular dictionary.
msg = attributes._validate_dict_or_none(dictionary, constraints)
self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
def test_validate_dict_or_empty(self):
dictionary, constraints = self._construct_dict_and_constraints()
# Check whether an empty dictionary is valid.
msg = attributes._validate_dict_or_empty({}, constraints)
self.assertIsNone(msg, 'Validation of a None dictionary failed.')
# Check validation of a regular dictionary.
msg = attributes._validate_dict_or_none(dictionary, constraints)
self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
def test_validate_non_negative(self):
for value in (-1, '-2'):
self.assertEqual("'%s' should be non-negative" % value,
attributes._validate_non_negative(value))
for value in (0, 1, '2', True, False):
msg = attributes._validate_non_negative(value)
self.assertIsNone(msg)
class TestConvertToBoolean(base.BaseTestCase):
def test_convert_to_boolean_bool(self):
self.assertIs(attributes.convert_to_boolean(True), True)
self.assertIs(attributes.convert_to_boolean(False), False)
def test_convert_to_boolean_int(self):
self.assertIs(attributes.convert_to_boolean(0), False)
self.assertIs(attributes.convert_to_boolean(1), True)
self.assertRaises(n_exc.InvalidInput,
attributes.convert_to_boolean,
7)
def test_convert_to_boolean_str(self):
self.assertIs(attributes.convert_to_boolean('True'), True)
self.assertIs(attributes.convert_to_boolean('true'), True)
self.assertIs(attributes.convert_to_boolean('False'), False)
self.assertIs(attributes.convert_to_boolean('false'), False)
self.assertIs(attributes.convert_to_boolean('0'), False)
self.assertIs(attributes.convert_to_boolean('1'), True)
self.assertRaises(n_exc.InvalidInput,
attributes.convert_to_boolean,
'7')
class TestConvertToInt(base.BaseTestCase):
def test_convert_to_int_int(self):
self.assertEqual(-1, attributes.convert_to_int(-1))
self.assertEqual(0, attributes.convert_to_int(0))
self.assertEqual(1, attributes.convert_to_int(1))
def test_convert_to_int_if_not_none(self):
self.assertEqual(-1, attributes.convert_to_int_if_not_none(-1))
self.assertEqual(0, attributes.convert_to_int_if_not_none(0))
self.assertEqual(1, attributes.convert_to_int_if_not_none(1))
self.assertIsNone(attributes.convert_to_int_if_not_none(None))
def test_convert_to_int_str(self):
self.assertEqual(4, attributes.convert_to_int('4'))
self.assertEqual(6, attributes.convert_to_int('6'))
self.assertRaises(n_exc.InvalidInput,
attributes.convert_to_int,
'garbage')
def test_convert_to_int_none(self):
self.assertRaises(n_exc.InvalidInput,
attributes.convert_to_int,
None)
def test_convert_none_to_empty_list_none(self):
self.assertEqual([], attributes.convert_none_to_empty_list(None))
def test_convert_none_to_empty_dict(self):
self.assertEqual({}, attributes.convert_none_to_empty_dict(None))
def test_convert_none_to_empty_list_value(self):
values = ['1', 3, [], [1], {}, {'a': 3}]
for value in values:
self.assertEqual(
value, attributes.convert_none_to_empty_list(value))
class TestConvertToFloat(base.BaseTestCase):
# NOTE: the routine being tested here is a plugin-specific extension
# module. As the plugin split proceed towards its second phase this
# test should either be remove, or the validation routine moved into
# neutron.api.v2.attributes
def test_convert_to_float_positve_value(self):
self.assertEqual(
1.111, attributes.convert_to_positive_float_or_none(1.111))
self.assertEqual(1, attributes.convert_to_positive_float_or_none(1))
self.assertEqual(0, attributes.convert_to_positive_float_or_none(0))
def test_convert_to_float_negative_value(self):
self.assertRaises(n_exc.InvalidInput,
attributes.convert_to_positive_float_or_none,
-1.11)
def test_convert_to_float_string(self):
self.assertEqual(4, attributes.convert_to_positive_float_or_none('4'))
self.assertEqual(
4.44, attributes.convert_to_positive_float_or_none('4.44'))
self.assertRaises(n_exc.InvalidInput,
attributes.convert_to_positive_float_or_none,
'garbage')
def test_convert_to_float_none_value(self):
self.assertIsNone(attributes.convert_to_positive_float_or_none(None))
class TestConvertKvp(base.BaseTestCase):
def test_convert_kvp_list_to_dict_succeeds_for_missing_values(self):
result = attributes.convert_kvp_list_to_dict(['True'])
self.assertEqual({}, result)
def test_convert_kvp_list_to_dict_succeeds_for_multiple_values(self):
result = attributes.convert_kvp_list_to_dict(
['a=b', 'a=c', 'a=c', 'b=a'])
self.assertEqual({'a': ['c', 'b'], 'b': ['a']}, result)
def test_convert_kvp_list_to_dict_succeeds_for_values(self):
result = attributes.convert_kvp_list_to_dict(['a=b', 'c=d'])
self.assertEqual({'a': ['b'], 'c': ['d']}, result)
def test_convert_kvp_str_to_list_fails_for_missing_key(self):
with testtools.ExpectedException(n_exc.InvalidInput):
attributes.convert_kvp_str_to_list('=a')
def test_convert_kvp_str_to_list_fails_for_missing_equals(self):
with testtools.ExpectedException(n_exc.InvalidInput):
attributes.convert_kvp_str_to_list('a')
def test_convert_kvp_str_to_list_succeeds_for_one_equals(self):
result = attributes.convert_kvp_str_to_list('a=')
self.assertEqual(['a', ''], result)
def test_convert_kvp_str_to_list_succeeds_for_two_equals(self):
result = attributes.convert_kvp_str_to_list('a=a=a')
self.assertEqual(['a', 'a=a'], result)
class TestConvertToList(base.BaseTestCase):
def test_convert_to_empty_list(self):
for item in (None, [], (), {}):
self.assertEqual([], attributes.convert_to_list(item))
def test_convert_to_list_string(self):
for item in ('', 'foo'):
self.assertEqual([item], attributes.convert_to_list(item))
def test_convert_to_list_iterable(self):
for item in ([None], [1, 2, 3], (1, 2, 3), set([1, 2, 3]), ['foo']):
self.assertEqual(list(item), attributes.convert_to_list(item))
def test_convert_to_list_non_iterable(self):
for item in (True, False, 1, 1.2, object()):
self.assertEqual([item], attributes.convert_to_list(item))
| alexandrucoman/vbox-neutron-agent | neutron/tests/unit/api/v2/test_attributes.py | Python | apache-2.0 | 35,656 | 0 |
import numpy as np
import logging
from plunc.common import round_to_digits
from plunc.exceptions import SearchFailedException, InsufficientPrecisionError, OutsideDomainError
from plunc.WaryInterpolator import WaryInterpolator
class IntervalChoice(object):
"""Base interval choice method class
"""
method = 'rank' # 'rank' or 'threshold'
threshold = float('inf')
precision_digits = 2
use_interval_cache = True
wrap_interpolator = True
background = 0
confidence_level = 0.9
max_hypothesis = 1e6
interpolator_log_domain = (-1, 3)
fixed_upper_limit = None
fixed_lower_limit = None
# Use only for testing:
forbid_exact_computation = False
def __init__(self, statistic, **kwargs):
self.statistic = statistic
for k, v in kwargs.items():
setattr(self, k, v)
self.cl = self.confidence_level
self.log = logging.getLogger(self.__class__.__name__)
if self.wrap_interpolator:
self.log.debug("Initializing interpolators")
if self.fixed_lower_limit is None:
self.low_limit_interpolator = WaryInterpolator(precision=10**(-self.precision_digits),
domain=self.interpolator_log_domain)
if self.fixed_upper_limit is None:
self.high_limit_interpolator = WaryInterpolator(precision=10**(-self.precision_digits),
domain=self.interpolator_log_domain)
# "Joints" of the interpolator must have better precision than required of the interpolator results
self.precision_digits += 1
# Dictionary holding "horizontal" intervals: interval on statistic for each precision and hypothesis.
self.cached_intervals = {}
def get_interval_on_statistic(self, hypothesis, precision_digits):
"""Returns the self.cl confidence level interval on self.statistic for the event rate hypothesis
The event rate here includes signal as well as identically distributed background.
Intervals are inclusive = closed.
"""
if self.use_interval_cache and (hypothesis, precision_digits) in self.cached_intervals:
return self.cached_intervals[(hypothesis, precision_digits)]
stat_values, likelihoods = self.statistic.get_values_and_likelihoods(hypothesis,
precision_digits=precision_digits)
likelihoods = likelihoods / np.sum(likelihoods)
# Score each statistic value (method-dependent)
stat_value_scores = self.score_stat_values(statistic_values=stat_values,
likelihoods=likelihoods,
hypothesis=hypothesis)
if self.method == 'threshold':
# Include all statistic values that score higher than some threshold
values_in_interval = stat_values[stat_value_scores > self.get_threshold()]
else:
# Include the values with highest score first, until we reach the desired confidence level
# TODO: wouldn't HIGHEST score first be more user-friendly?
ranks = np.argsort(stat_value_scores)
train_values_sorted = stat_values[ranks]
likelihoods_sorted = likelihoods[ranks]
# Find the last value to include
# (= first value that takes the included probability over the required confidence level)
sum_lhoods = np.cumsum(likelihoods_sorted)
last_index = np.where(sum_lhoods > self.cl)[0][0] # TODO: can fail?
values_in_interval = train_values_sorted[:last_index + 1]
# Limits = extreme values in the interval.
# This means we will be conservative if values_in_interval is not continuous.
low_lim, high_lim = values_in_interval.min(), values_in_interval.max()
# If we included all values given up until a boundary, don't set that boundary as a limit
if low_lim == np.min(stat_values):
low_lim = 0
if high_lim == np.max(stat_values):
high_lim = float('inf')
# Cache and return upper and lower limit on the statistic
if self.use_interval_cache:
self.cached_intervals[(hypothesis, precision_digits)] = low_lim, high_lim
return low_lim, high_lim
def get_confidence_interval(self, value, precision_digits, search_region, debug=False):
"""Performs the Neynman construction to get confidence interval on event rate (mu),
if the statistic is observed to have value
"""
log_value = np.log10(value)
if self.wrap_interpolator:
# Try to interpolate the limit from limits computed earlier
self.log.debug("Trying to get values from interpolators")
try:
if self.fixed_lower_limit is None:
low_limit = 10**(self.low_limit_interpolator(log_value))
else:
low_limit = self.fixed_lower_limit
if self.fixed_upper_limit is None:
high_limit = 10**(self.high_limit_interpolator(log_value))
else:
high_limit = self.fixed_upper_limit
return low_limit, high_limit
except InsufficientPrecisionError:
self.log.debug("Insuffienct precision achieved by interpolators")
if log_value > self.interpolator_log_domain[1]:
self.log.debug("Too high value to dare to start Neyman construction... raising exception")
# It is not safe to do the Neyman construction: too high statistics
raise
self.log.debug("Log value %s is below interpolator log domain max %s "
"=> starting Neyman construction" % (log_value, self.interpolator_log_domain[1]))
except OutsideDomainError:
# The value is below the interpolator domain (e.g. 0 while the domain ends at 10**0 = 1)
pass
if self.forbid_exact_computation:
raise RuntimeError("Exact computation triggered")
def is_value_in(mu):
low_lim, high_lim = self.get_interval_on_statistic(mu + self.background,
precision_digits=precision_digits)
return low_lim <= value <= high_lim
# We first need one value in the interval to bound the limit searches
try:
true_point, low_search_bound, high_search_bound = search_true_instance(is_value_in,
*search_region,
precision_digits=precision_digits)
except SearchFailedException as e:
self.log.debug("Exploratory search could not find a single value in the interval! "
"This is probably a problem with search region, or simply a very extreme case."
"Original exception: %s" % str(e))
if is_value_in(0):
self.log.debug("Oh, ok, only zero is in the interval... Returning (0, 0)")
return 0, 0
return 0, float('inf')
self.log.debug(">>> Exploratory search completed: %s is in interval, "
"search for boundaries in [%s, %s]" % (true_point, low_search_bound, high_search_bound))
if self.fixed_lower_limit is not None:
low_limit = self.fixed_lower_limit
elif is_value_in(low_search_bound):
# If mu=0 can't be excluded, we're apparently only setting an upper limit (mu <= ..)
low_limit = 0
else:
low_limit = bisect_search(is_value_in, low_search_bound, true_point, precision_digits=precision_digits)
self.log.debug(">>> Low limit found at %s" % low_limit)
if self.fixed_upper_limit is not None:
low_limit = self.fixed_upper_limit
elif is_value_in(high_search_bound):
# If max_mu can't be excluded, we're apparently only setting a lower limit (mu >= ..)
high_limit = float('inf')
else:
high_limit = bisect_search(is_value_in, true_point, high_search_bound, precision_digits=precision_digits)
self.log.debug(">>> High limit found at %s" % high_limit)
if self.wrap_interpolator:
# Add the values to the interpolator, if they are within the domain
# TODO: Think about dealing with inf
if self.interpolator_log_domain[0] <= log_value <= self.interpolator_log_domain[1]:
if self.fixed_lower_limit is None:
self.low_limit_interpolator.add_point(log_value, np.log10(low_limit))
if self.fixed_upper_limit is None:
self.high_limit_interpolator.add_point(log_value, np.log10(high_limit))
return low_limit, high_limit
def score_stat_values(self, **kwargs):
# Return "rank" of each hypothesis. Hypotheses with highest ranks will be included first.
raise NotImplementedError()
def __call__(self, observation, precision_digits=None, search_region=None):
"""Perform Neynman construction to get confidence interval on event rate for observation.
"""
if precision_digits is None:
precision_digits = self.precision_digits
if search_region is None:
search_region = [0, round_to_digits(10 + 3 * len(observation), precision_digits)]
if self.statistic.mu_dependent:
value = self.statistic(observation, self.statistic.mus)
else:
value = self.statistic(observation, None)
self.log.debug("Statistic evaluates to %s" % value)
return self.get_confidence_interval(value, precision_digits=precision_digits, search_region=search_region)
def search_true_instance(f, a, b, precision_digits=3, maxiter=10, log=None):
"""Find x in [a, b] where f is True, limiting search to values with precision_digits significant figures.
Returns x, low_bound, high_bound where low_bound and high_bound are either the search bounds a or b, or closer
values to x where f was still found to be False.
# TODO: If asked for precision_digits=5, first search with precision_digits=1, then 2, etc.
print(search_true_instance(lambda x: 11 < x < 13, 0, 40))
print(search_true_instance(lambda x: x < 13, 0, 1000))
"""
log = logging.getLogger('search_true_instance')
values_searched = [a, b]
log.debug("Starting exploratory search in [%s, %s]" % (a, b))
for iter_i in range(maxiter):
# First test halfway, point then 1/4 and 3/4, then 1/8, 3/8, 5/8, 7/8, etc.
fractions = 2**(iter_i + 1)
search_points = [round_to_digits(a + (b - a)*fr, precision_digits)
for fr in np.arange(1, fractions, 2)/fractions]
log.debug("Searching %s - %s (%d points)" % (search_points[0], search_points[-1], len(search_points)))
for x_i, x in enumerate(search_points):
if f(x):
values_searched = np.array(values_searched)
return x, np.max(values_searched[values_searched < x]), np.min(values_searched[values_searched > x])
else:
values_searched.append(x)
if len(search_points) > 1 and np.any(np.diff(search_points) == 0):
raise SearchFailedException("No true value found in search region [%s, %s], "
"but search depth now lower than precision digits (%s). "
"Iteration %d." % (a, b, precision_digits, iter_i))
raise ValueError("Exploratory search failed to converge or terminate - bug? excessive precision?")
def bisect_search(f, a, b, precision_digits=2, maxiter=1e2):
"""Find x in [a, b] where f changes from True to False by bisection,
limiting search to values with precision_digits significant figures.
This is useful if f can cache its results: otherwise just use e.g. scipy.optimize.brentq with rtol.
Avoid scipy.optimize.bisect with rtol, results seem seem to depend heavily on initial bounds: bug??
# TODO: If asked for precision_digits=5, first search with precision_digits=1, then 2, etc.
"""
log = logging.getLogger('bisect_search')
# Which of the bounds gives True? Can't be both!
if f(a) == f(b):
raise ValueError("f must not be true or false on both bounds")
true_on_a = f(a)
log.debug("Starting search between %s (%s) and %s (%s)"
" with %d precision digits" % (a, f(a), b, f(b), precision_digits))
# Do a bisection search, sticking to precision_digits
for iter_i in range(int(maxiter)):
# Find the new bisection point
x = (a + b) / 2
x = round_to_digits(x, precision_digits)
# If we are down to a single point, return that
if x == a or x == b:
return x
true_on_x = f(x)
# Update the appropriate bound
if true_on_a:
if true_on_x:
a = x
else:
b = x
else:
if true_on_x:
b = x
else:
a = x
log.debug("Iteration %d, searching between [%s and %s], last x was %s (%s)" % (iter_i, a, b, x, true_on_x))
else:
raise RuntimeError("Infinite loop encountered in bisection search!")
| JelleAalbers/plunc | plunc/intervals/base.py | Python | mit | 13,686 | 0.004749 |
from ..utils import getif
def init_config():
config = {}
getif(config, "token", "SLACK_TOKEN")
getif(config, "loglevel", "LIMBO_LOGLEVEL")
getif(config, "logfile", "LIMBO_LOGFILE")
getif(config, "logformat", "LIMBO_LOGFORMAT")
getif(config, "plugins", "LIMBO_PLUGINS")
getif(config, "heroku", "LIMBO_ON_HEROKU")
getif(config, "beepboop", "BEEPBOOP_TOKEN")
return config
CONFIG = init_config()
| serverdensity/sdbot | limbo/settings/__init__.py | Python | mit | 431 | 0.00464 |
#!/usr/bin/env python
from gnuradio import gr
from gnuradio.eng_option import eng_option
from optparse import OptionParser
import LTE_fdd_dl_fg
import sys
class LTE_fdd_dl_file_gen (gr.top_block):
def __init__(self):
gr.top_block.__init__(self)
usage = "usage: %prog [options] file N_frames N_ant N_id_cell bandwidth mcc mnc"
parser=OptionParser(option_class=eng_option, usage=usage)
# Add options here
(options, args) = parser.parse_args()
if len(args) != 7:
parser.print_help()
sys.exit(1)
output_filename = args[0]
N_frames = args[1]
N_ant = args[2]
N_id_cell = args[3]
bandwidth = args[4]
mcc = args[5]
mnc = args[6]
# Build flow graph
self.samp_buf = LTE_fdd_dl_fg.samp_buf(int(N_frames), int(N_ant), int(N_id_cell), float(bandwidth), mcc, mnc)
self.fsink = gr.file_sink(gr.sizeof_char, output_filename)
self.connect(self.samp_buf, self.fsink)
if __name__ == '__main__':
tb = LTE_fdd_dl_file_gen()
try:
tb.run()
except KeyboardInterrupt:
pass
| LucaBongiorni/openlte | LTE_fdd_dl_file_gen/python/LTE_fdd_dl_file_gen.py | Python | agpl-3.0 | 1,147 | 0.004359 |
# Copyright 2017 The Bazel 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.
import glob
import os
import unittest
from src.test.py.bazel import test_base
class BazelWindowsCppTest(test_base.TestBase):
def createProjectFiles(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'package(',
' default_visibility = ["//visibility:public"],',
' features=["windows_export_all_symbols"]',
')',
'',
'cc_library(',
' name = "A",',
' srcs = ["a.cc"],',
' hdrs = ["a.h"],',
' copts = ["/DCOMPILING_A_DLL"],',
' features = ["no_windows_export_all_symbols"],',
')',
'',
'cc_library(',
' name = "B",',
' srcs = ["b.cc"],',
' hdrs = ["b.h"],',
' deps = [":A"],',
' copts = ["/DNO_DLLEXPORT"],',
')',
'',
'cc_binary(',
' name = "C",',
' srcs = ["c.cc"],',
' deps = [":A", ":B" ],',
' linkstatic = 0,',
')',
])
self.ScratchFile('a.cc', [
'#include <stdio.h>',
'#include "a.h"',
'int a = 0;',
'void hello_A() {',
' a++;',
' printf("Hello A, %d\\n", a);',
'}',
])
self.ScratchFile('b.cc', [
'#include <stdio.h>',
'#include "a.h"',
'#include "b.h"',
'void hello_B() {',
' hello_A();',
' printf("Hello B\\n");',
'}',
])
header_temp = [
'#ifndef %{name}_H',
'#define %{name}_H',
'',
'#if NO_DLLEXPORT',
' #define DLLEXPORT',
'#elif COMPILING_%{name}_DLL',
' #define DLLEXPORT __declspec(dllexport)',
'#else',
' #define DLLEXPORT __declspec(dllimport)',
'#endif',
'',
'DLLEXPORT void hello_%{name}();',
'',
'#endif',
]
self.ScratchFile('a.h',
[line.replace('%{name}', 'A') for line in header_temp])
self.ScratchFile('b.h',
[line.replace('%{name}', 'B') for line in header_temp])
c_cc_content = [
'#include <stdio.h>',
'#include "a.h"',
'#include "b.h"',
'',
'void hello_C() {',
' hello_A();',
' hello_B();',
' printf("Hello C\\n");',
'}',
'',
'int main() {',
' hello_C();',
' return 0;',
'}',
]
self.ScratchFile('c.cc', c_cc_content)
self.ScratchFile('lib/BUILD', [
'cc_library(',
' name = "A",',
' srcs = ["dummy.cc"],',
' features = ["windows_export_all_symbols"],',
' visibility = ["//visibility:public"],',
')',
])
self.ScratchFile('lib/dummy.cc', ['void dummy() {}'])
self.ScratchFile('main/main.cc', c_cc_content)
def getBazelInfo(self, info_key):
exit_code, stdout, stderr = self.RunBazel(['info', info_key])
self.AssertExitCode(exit_code, 0, stderr)
return stdout[0]
def testBuildDynamicLibraryWithUserExportedSymbol(self):
self.createProjectFiles()
bazel_bin = self.getBazelInfo('bazel-bin')
# //:A export symbols by itself using __declspec(dllexport), so it doesn't
# need Bazel to export symbols using DEF file.
exit_code, _, stderr = self.RunBazel(
['build', '//:A', '--output_groups=dynamic_library'])
self.AssertExitCode(exit_code, 0, stderr)
# TODO(pcloudy): change suffixes to .lib and .dll after making DLL
# extensions correct on Windows.
import_library = os.path.join(bazel_bin, 'A.if.lib')
shared_library = os.path.join(bazel_bin, 'A.dll')
empty_def_file = os.path.join(bazel_bin, 'A.gen.empty.def')
self.assertTrue(os.path.exists(import_library))
self.assertTrue(os.path.exists(shared_library))
# An empty DEF file should be generated for //:A
self.assertTrue(os.path.exists(empty_def_file))
def testBuildDynamicLibraryWithExportSymbolFeature(self):
self.createProjectFiles()
bazel_bin = self.getBazelInfo('bazel-bin')
# //:B doesn't export symbols by itself, so it need Bazel to export symbols
# using DEF file.
exit_code, _, stderr = self.RunBazel(
['build', '//:B', '--output_groups=dynamic_library'])
self.AssertExitCode(exit_code, 0, stderr)
# TODO(pcloudy): change suffixes to .lib and .dll after making DLL
# extensions correct on Windows.
import_library = os.path.join(bazel_bin, 'B.if.lib')
shared_library = os.path.join(bazel_bin, 'B.dll')
def_file = os.path.join(bazel_bin, 'B.gen.def')
self.assertTrue(os.path.exists(import_library))
self.assertTrue(os.path.exists(shared_library))
# DEF file should be generated for //:B
self.assertTrue(os.path.exists(def_file))
# Test build //:B if windows_export_all_symbols feature is disabled by
# no_windows_export_all_symbols.
exit_code, _, stderr = self.RunBazel([
'build', '//:B', '--output_groups=dynamic_library',
'--features=no_windows_export_all_symbols'
])
self.AssertExitCode(exit_code, 0, stderr)
import_library = os.path.join(bazel_bin, 'B.if.lib')
shared_library = os.path.join(bazel_bin, 'B.dll')
empty_def_file = os.path.join(bazel_bin, 'B.gen.empty.def')
self.assertTrue(os.path.exists(import_library))
self.assertTrue(os.path.exists(shared_library))
# An empty DEF file should be generated for //:B
self.assertTrue(os.path.exists(empty_def_file))
self.AssertFileContentNotContains(empty_def_file, 'hello_B')
def testBuildCcBinaryWithDependenciesDynamicallyLinked(self):
self.createProjectFiles()
bazel_bin = self.getBazelInfo('bazel-bin')
# Since linkstatic=0 is specified for //:C, it's dependencies should be
# dynamically linked.
exit_code, _, stderr = self.RunBazel(['build', '//:C'])
self.AssertExitCode(exit_code, 0, stderr)
# TODO(pcloudy): change suffixes to .lib and .dll after making DLL
# extensions correct on
# Windows.
# a_import_library
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'A.if.lib')))
# a_shared_library
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'A.dll')))
# a_def_file
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'A.gen.empty.def')))
# b_import_library
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'B.if.lib')))
# b_shared_library
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'B.dll')))
# b_def_file
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'B.gen.def')))
# c_exe
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'C.exe')))
def testBuildCcBinaryFromDifferentPackage(self):
self.createProjectFiles()
self.ScratchFile('main/BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
' deps = ["//:B"],',
' linkstatic = 0,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(['build', '//main:main'])
self.AssertExitCode(exit_code, 0, stderr)
# Test if A.dll and B.dll are copied to the directory of main.exe
main_bin = os.path.join(bazel_bin, 'main/main.exe')
self.assertTrue(os.path.exists(main_bin))
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'main/A.dll')))
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'main/B.dll')))
# Run the binary to see if it runs successfully
exit_code, stdout, stderr = self.RunProgram([main_bin])
self.AssertExitCode(exit_code, 0, stderr)
self.assertEqual(['Hello A, 1', 'Hello A, 2', 'Hello B', 'Hello C'], stdout)
def testBuildCcBinaryDependsOnConflictDLLs(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
' deps = ["//:B", "//lib:A"],', # Transitively depends on //:A
' linkstatic = 0,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
# //main:main depends on both //lib:A and //:A
exit_code, _, stderr = self.RunBazel(
['build', '//main:main', '--incompatible_avoid_conflict_dlls'])
self.AssertExitCode(exit_code, 0, stderr)
# Run the binary to see if it runs successfully
main_bin = os.path.join(bazel_bin, 'main/main.exe')
exit_code, stdout, stderr = self.RunProgram([main_bin])
self.AssertExitCode(exit_code, 0, stderr)
self.assertEqual(['Hello A, 1', 'Hello A, 2', 'Hello B', 'Hello C'], stdout)
# There are 2 A_{hash}.dll since //main:main depends on both //lib:A and
# //:A
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'A_*.dll'))), 2)
# There is only 1 B_{hash}.dll
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'B_*.dll'))), 1)
def testBuildDifferentCcBinariesDependOnConflictDLLs(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
' deps = ["//:B"],', # Transitively depends on //:A
' linkstatic = 0,'
')',
'',
'cc_binary(',
' name = "other_main",',
' srcs = ["other_main.cc"],',
' deps = ["//lib:A"],',
' linkstatic = 0,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
self.ScratchFile('main/other_main.cc', ['int main() {return 0;}'])
# Building //main:main should succeed
exit_code, _, stderr = self.RunBazel(
['build', '//main:main', '--incompatible_avoid_conflict_dlls'])
self.AssertExitCode(exit_code, 0, stderr)
main_bin = os.path.join(bazel_bin, 'main/main.exe')
# Run the main_bin binary to see if it runs successfully
exit_code, stdout, stderr = self.RunProgram([main_bin])
self.AssertExitCode(exit_code, 0, stderr)
self.assertEqual(['Hello A, 1', 'Hello A, 2', 'Hello B', 'Hello C'], stdout)
# There is only 1 A_{hash}.dll since //main:main depends transitively on
# //:A
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'A_*.dll'))), 1)
# There is only 1 B_{hash}.dll
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'B_*.dll'))), 1)
# Building //main:other_main should succeed
exit_code, _, stderr = self.RunBazel([
'build', '//main:main', '//main:other_main',
'--incompatible_avoid_conflict_dlls'
])
self.AssertExitCode(exit_code, 0, stderr)
other_main_bin = os.path.join(bazel_bin, 'main/other_main.exe')
# Run the other_main_bin binary to see if it runs successfully
exit_code, stdout, stderr = self.RunProgram([other_main_bin])
self.AssertExitCode(exit_code, 0, stderr)
# There are 2 A_{hash}.dll since //main:main depends on //:A
# and //main:other_main depends on //lib:A
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'A_*.dll'))), 2)
def testDLLIsCopiedFromExternalRepo(self):
self.ScratchFile('ext_repo/WORKSPACE')
self.ScratchFile('ext_repo/BUILD', [
'cc_library(',
' name = "A",',
' srcs = ["a.cc"],',
' features = ["windows_export_all_symbols"],',
' visibility = ["//visibility:public"],',
')',
])
self.ScratchFile('ext_repo/a.cc', [
'#include <stdio.h>',
'void hello_A() {',
' printf("Hello A\\n");',
'}',
])
self.ScratchFile('WORKSPACE', [
'local_repository(',
' name = "ext_repo",',
' path = "ext_repo",',
')',
])
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
' deps = ["@ext_repo//:A"],',
' linkstatic = 0,',
')',
])
self.ScratchFile('main.cc', [
'extern void hello_A();',
'',
'int main() {',
' hello_A();',
' return 0;',
'}',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(['build', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
# Test if A.dll is copied to the directory of main.exe
main_bin = os.path.join(bazel_bin, 'main.exe')
self.assertTrue(os.path.exists(main_bin))
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'A.dll')))
# Run the binary to see if it runs successfully
exit_code, stdout, stderr = self.RunProgram([main_bin])
self.AssertExitCode(exit_code, 0, stderr)
self.assertEqual(['Hello A'], stdout)
def testDynamicLinkingMSVCRT(self):
self.createProjectFiles()
bazel_output = self.getBazelInfo('output_path')
# By default, it should link to msvcrt dynamically.
exit_code, _, stderr = self.RunBazel(
['build', '//:A', '--output_groups=dynamic_library', '-s'])
paramfile = os.path.join(
bazel_output, 'x64_windows-fastbuild/bin/A.dll-2.params')
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('/MD', ''.join(stderr))
self.AssertFileContentContains(paramfile, '/DEFAULTLIB:msvcrt.lib')
self.assertNotIn('/MT', ''.join(stderr))
self.AssertFileContentNotContains(paramfile, '/DEFAULTLIB:libcmt.lib')
# Test build in debug mode.
exit_code, _, stderr = self.RunBazel(
['build', '-c', 'dbg', '//:A', '--output_groups=dynamic_library', '-s'])
paramfile = os.path.join(bazel_output, 'x64_windows-dbg/bin/A.dll-2.params')
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('/MDd', ''.join(stderr))
self.AssertFileContentContains(paramfile, '/DEFAULTLIB:msvcrtd.lib')
self.assertNotIn('/MTd', ''.join(stderr))
self.AssertFileContentNotContains(paramfile, '/DEFAULTLIB:libcmtd.lib')
def testStaticLinkingMSVCRT(self):
self.createProjectFiles()
bazel_output = self.getBazelInfo('output_path')
# With static_link_msvcrt feature, it should link to msvcrt statically.
exit_code, _, stderr = self.RunBazel([
'build', '//:A', '--output_groups=dynamic_library',
'--features=static_link_msvcrt', '-s'
])
paramfile = os.path.join(
bazel_output, 'x64_windows-fastbuild/bin/A.dll-2.params')
self.AssertExitCode(exit_code, 0, stderr)
self.assertNotIn('/MD', ''.join(stderr))
self.AssertFileContentNotContains(paramfile, '/DEFAULTLIB:msvcrt.lib')
self.assertIn('/MT', ''.join(stderr))
self.AssertFileContentContains(paramfile, '/DEFAULTLIB:libcmt.lib')
# Test build in debug mode.
exit_code, _, stderr = self.RunBazel([
'build', '-c', 'dbg', '//:A', '--output_groups=dynamic_library',
'--features=static_link_msvcrt', '-s'
])
paramfile = os.path.join(bazel_output, 'x64_windows-dbg/bin/A.dll-2.params')
self.AssertExitCode(exit_code, 0, stderr)
self.assertNotIn('/MDd', ''.join(stderr))
self.AssertFileContentNotContains(paramfile, '/DEFAULTLIB:msvcrtd.lib')
self.assertIn('/MTd', ''.join(stderr))
self.AssertFileContentContains(paramfile, '/DEFAULTLIB:libcmtd.lib')
def testBuildSharedLibraryFromCcBinaryWithStaticLink(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main.dll",',
' srcs = ["main.cc"],',
' deps = ["//:B"],', # Transitively depends on //:A
' linkstatic = 1,'
' linkshared = 1,'
' features=["windows_export_all_symbols"]',
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel([
'build', '//main:main.dll',
'--output_groups=default,runtime_dynamic_libraries,interface_library'
])
self.AssertExitCode(exit_code, 0, stderr)
main_library = os.path.join(bazel_bin, 'main/main.dll')
main_interface = os.path.join(bazel_bin, 'main/main.dll.if.lib')
def_file = os.path.join(bazel_bin, 'main/main.dll.gen.def')
self.assertTrue(os.path.exists(main_library))
self.assertTrue(os.path.exists(main_interface))
self.assertTrue(os.path.exists(def_file))
# A.dll and B.dll should not be copied.
self.assertFalse(os.path.exists(os.path.join(bazel_bin, 'main/A.dll')))
self.assertFalse(os.path.exists(os.path.join(bazel_bin, 'main/B.dll')))
self.AssertFileContentContains(def_file, 'hello_A')
self.AssertFileContentContains(def_file, 'hello_B')
self.AssertFileContentContains(def_file, 'hello_C')
def testBuildSharedLibraryFromCcBinaryWithDynamicLink(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main.dll",',
' srcs = ["main.cc"],',
' deps = ["//:B"],', # Transitively depends on //:A
' linkstatic = 0,'
' linkshared = 1,'
' features=["windows_export_all_symbols"]',
')',
'',
'genrule(',
' name = "renamed_main",',
' srcs = [":main.dll"],',
' outs = ["main_renamed.dll"],',
' cmd = "cp $< $@",',
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel([
'build', '//main:main.dll',
'--output_groups=default,runtime_dynamic_libraries,interface_library'
])
self.AssertExitCode(exit_code, 0, stderr)
main_library = os.path.join(bazel_bin, 'main/main.dll')
main_interface = os.path.join(bazel_bin, 'main/main.dll.if.lib')
def_file = os.path.join(bazel_bin, 'main/main.dll.gen.def')
self.assertTrue(os.path.exists(main_library))
self.assertTrue(os.path.exists(main_interface))
self.assertTrue(os.path.exists(def_file))
# A.dll and B.dll should be built and copied because they belong to
# runtime_dynamic_libraries output group.
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'main/A.dll')))
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'main/B.dll')))
# hello_A and hello_B should not be exported.
self.AssertFileContentNotContains(def_file, 'hello_A')
self.AssertFileContentNotContains(def_file, 'hello_B')
self.AssertFileContentContains(def_file, 'hello_C')
# The copy should succeed since //main:main.dll is only supposed to refer to
# main.dll, A.dll and B.dll should be in a separate output group.
exit_code, _, stderr = self.RunBazel(['build', '//main:renamed_main'])
self.AssertExitCode(exit_code, 0, stderr)
def testGetDefFileOfSharedLibraryFromCcBinary(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main.dll",',
' srcs = ["main.cc"],',
' deps = ["//:B"],', # Transitively depends on //:A
' linkstatic = 1,'
' linkshared = 1,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(
['build', '//main:main.dll', '--output_groups=def_file'])
self.AssertExitCode(exit_code, 0, stderr)
# Although windows_export_all_symbols is not specified for this target,
# we should still be able to get the DEF file by def_file output group.
def_file = os.path.join(bazel_bin, 'main/main.dll.gen.def')
self.assertTrue(os.path.exists(def_file))
self.AssertFileContentContains(def_file, 'hello_A')
self.AssertFileContentContains(def_file, 'hello_B')
self.AssertFileContentContains(def_file, 'hello_C')
def testBuildSharedLibraryWithoutAnySymbolExported(self):
self.createProjectFiles()
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "A.dll",',
' srcs = ["a.cc", "a.h"],',
' copts = ["/DNO_DLLEXPORT"],',
' linkshared = 1,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(['build', '//:A.dll'])
self.AssertExitCode(exit_code, 0, stderr)
# Although windows_export_all_symbols is not specified for this target,
# we should still be able to build a DLL without any symbol exported.
empty_def_file = os.path.join(bazel_bin, 'A.dll.gen.empty.def')
self.assertTrue(os.path.exists(empty_def_file))
self.AssertFileContentNotContains(empty_def_file, 'hello_A')
def testUsingDefFileGeneratedFromCcLibrary(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('lib_A.cc', ['void hello_A() {}'])
self.ScratchFile('lib_B.cc', ['void hello_B() {}'])
self.ScratchFile('BUILD', [
'cc_library(',
' name = "lib_A",',
' srcs = ["lib_A.cc"],',
')',
'',
'cc_library(',
' name = "lib_B",',
' srcs = ["lib_B.cc"],',
' deps = [":lib_A"]',
')',
'',
'filegroup(',
' name = "lib_B_symbols",',
' srcs = [":lib_B"],',
' output_group = "def_file",',
')',
'',
'cc_binary(',
' name = "lib.dll",',
' deps = [":lib_B"],',
' win_def_file = ":lib_B_symbols",',
' linkshared = 1,',
')',
])
# Test specifying DEF file in cc_binary
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(['build', '//:lib.dll', '-s'])
self.AssertExitCode(exit_code, 0, stderr)
def_file = bazel_bin + '/lib_B.gen.def'
self.assertTrue(os.path.exists(def_file))
# hello_A should not be exported
self.AssertFileContentNotContains(def_file, 'hello_A')
# hello_B should be exported
self.AssertFileContentContains(def_file, 'hello_B')
def testWinDefFileAttribute(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('lib.cc', ['void hello() {}'])
self.ScratchFile('my_lib.def', [
'EXPORTS',
' ?hello@@YAXXZ',
])
self.ScratchFile('BUILD', [
'cc_library(',
' name = "lib",',
' srcs = ["lib.cc"],',
' win_def_file = "my_lib.def",',
')',
'',
'cc_binary(',
' name = "lib_dy.dll",',
' srcs = ["lib.cc"],',
' win_def_file = "my_lib.def",',
' linkshared = 1,',
')',
])
# Test exporting symbols using custom DEF file in cc_library.
# Auto-generating DEF file should be disabled when custom DEF file specified
exit_code, _, stderr = self.RunBazel([
'build', '//:lib', '-s', '--output_groups=dynamic_library',
'--features=windows_export_all_symbols'
])
self.AssertExitCode(exit_code, 0, stderr)
bazel_bin = self.getBazelInfo('bazel-bin')
lib_if = os.path.join(bazel_bin, 'lib.if.lib')
lib_def = os.path.join(bazel_bin, 'lib.gen.def')
self.assertTrue(os.path.exists(lib_if))
self.assertFalse(os.path.exists(lib_def))
# Test specifying DEF file in cc_binary
exit_code, _, stderr = self.RunBazel(['build', '//:lib_dy.dll', '-s'])
self.AssertExitCode(exit_code, 0, stderr)
filepath = bazel_bin + '/lib_dy.dll-2.params'
with open(filepath, 'r', encoding='latin-1') as param_file:
self.assertIn('/DEF:my_lib.def', param_file.read())
def testCcImportRule(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_import(',
' name = "a_import",',
' static_library = "A.lib",',
' shared_library = "A.dll",',
' interface_library = "A.if.lib",',
' hdrs = ["a.h"],',
' alwayslink = 1,',
')',
])
exit_code, _, stderr = self.RunBazel([
'build', '//:a_import',
])
self.AssertExitCode(exit_code, 0, stderr)
def testCopyDLLAsSource(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_import(',
' name = "a_import",',
' shared_library = "A.dll",',
')',
'',
'cc_binary(',
' name = "bin",',
' srcs = ["bin.cc"],',
' deps = ["//:a_import"],',
')',
])
self.ScratchFile('A.dll')
self.ScratchFile('bin.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel([
'build',
'//:bin',
])
self.AssertExitCode(exit_code, 0, stderr)
bazel_bin = self.getBazelInfo('bazel-bin')
a_dll = os.path.join(bazel_bin, 'A.dll')
# Even though A.dll is in the same package as bin.exe, but it still should
# be copied to the output directory of bin.exe.
self.assertTrue(os.path.exists(a_dll))
def testCppErrorShouldBeVisible(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "bad",',
' srcs = ["bad.cc"],',
')',
])
self.ScratchFile('bad.cc', [
'int main(int argc, char** argv) {',
' this_is_an_error();',
'}',
])
exit_code, stdout, stderr = self.RunBazel(['build', '//:bad'])
self.AssertExitCode(exit_code, 1, stderr)
self.assertIn('this_is_an_error', ''.join(stdout))
def testBuildWithClangClByCompilerFlag(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel([
'build', '-s', '--compiler=clang-cl',
'--incompatible_enable_cc_toolchain_resolution=false', '//:main'
])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('clang-cl.exe', ''.join(stderr))
def testBuildWithClangClByToolchainResolution(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE', [
'register_execution_platforms(',
' ":windows_clang"',
')',
'',
'register_toolchains(',
' "@local_config_cc//:cc-toolchain-x64_windows-clang-cl",',
')',
])
self.ScratchFile('BUILD', [
'platform(',
' name = "windows_clang",',
' constraint_values = [',
' "@platforms//cpu:x86_64",',
' "@platforms//os:windows",',
' "@bazel_tools//tools/cpp:clang-cl",',
' ]',
')',
'',
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel([
'build', '-s', '--incompatible_enable_cc_toolchain_resolution=true',
'//:main'
])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('clang-cl.exe', ''.join(stderr))
def createSimpleCppWorkspace(self, name):
work_dir = self.ScratchDir(name)
self.ScratchFile(name + '/WORKSPACE', ['workspace(name = "%s")' % name])
self.ScratchFile(
name + '/BUILD',
['cc_library(name = "lib", srcs = ["lib.cc"], hdrs = ["lib.h"])'])
self.ScratchFile(name + '/lib.h', ['void hello();'])
self.ScratchFile(name + '/lib.cc', ['#include "lib.h"', 'void hello() {}'])
return work_dir
# Regression test for https://github.com/bazelbuild/bazel/issues/9172
def testCacheBetweenWorkspaceWithDifferentNames(self):
cache_dir = self.ScratchDir('cache')
dir_a = self.createSimpleCppWorkspace('A')
dir_b = self.createSimpleCppWorkspace('B')
exit_code, _, stderr = self.RunBazel(
['build', '--disk_cache=' + cache_dir, ':lib'], cwd=dir_a)
self.AssertExitCode(exit_code, 0, stderr)
exit_code, _, stderr = self.RunBazel(
['build', '--disk_cache=' + cache_dir, ':lib'], cwd=dir_b)
self.AssertExitCode(exit_code, 0, stderr)
# Regression test for https://github.com/bazelbuild/bazel/issues/9321
def testCcCompileWithTreeArtifactAsSource(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'load(":genccs.bzl", "genccs")',
'',
'genccs(',
' name = "gen_tree",',
')',
'',
'cc_library(',
' name = "main",',
' srcs = [ "gen_tree" ]',
')',
'',
'cc_binary(',
' name = "genccs",',
' srcs = [ "genccs.cpp" ],',
')',
])
self.ScratchFile('genccs.bzl', [
'def _impl(ctx):',
' tree = ctx.actions.declare_directory(ctx.attr.name + ".cc")',
' ctx.actions.run(',
' inputs = [],',
' outputs = [ tree ],',
' arguments = [ tree.path ],',
' progress_message = "Generating cc files into \'%s\'" % tree.path,',
' executable = ctx.executable._tool,',
' )',
'',
' return [ DefaultInfo(files = depset([ tree ])) ]',
'',
'genccs = rule(',
' implementation = _impl,',
' attrs = {',
' "_tool": attr.label(',
' executable = True,',
' cfg = "host",',
' allow_files = True,',
' default = Label("//:genccs"),',
' )',
' }',
')',
])
self.ScratchFile('genccs.cpp', [
'#include <fstream>',
'#include <Windows.h>',
'using namespace std;',
'',
'int main (int argc, char *argv[]) {',
' CreateDirectory(argv[1], NULL);',
' ofstream myfile;',
' myfile.open(string(argv[1]) + string("/foo.cpp"));',
' myfile << "int main() { return 42; }";',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel(['build', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
def testBuild32BitCppBinaryWithMsvcCL(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel(
['build', '-s', '--cpu=x64_x86_windows', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('x86/cl.exe', ''.join(stderr))
def testBuildArmCppBinaryWithMsvcCL(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel(
['build', '-s', '--cpu=x64_arm_windows', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('arm/cl.exe', ''.join(stderr))
def testBuildArm64CppBinaryWithMsvcCL(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel(
['build', '-s', '--cpu=x64_arm64_windows', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('arm64/cl.exe', ''.join(stderr))
if __name__ == '__main__':
unittest.main()
| werkt/bazel | src/test/py/bazel/bazel_windows_cpp_test.py | Python | apache-2.0 | 32,128 | 0.001276 |
from datetime import datetime
class store:
def __init__(self, delta):
self.delta = delta
self.dataDict = {}
self.ordList = []
def store(self, data, info):
ob2store = [data,info]
if data in self.dataDict:
try:
self.ordList.remove(self.dataDict[data])
except ValueError:
pass
self.dataDict[data] = ob2store
self.ordList.append(ob2store)
def flush(self):
self.ordList = []
self.dataDict = {}
def getIndex(self, pivot):
endIndex = len(self.ordList)
if endIndex == 0:
return 0
(d0,i0) = self.ordList[0]
(dE,iE) = self.ordList[-1]
if i0 > pivot:
return 0
if iE < pivot:
return endIndex
return self.getIndexRec(pivot, 0, endIndex)
def getIndexRec(self, pivot, startIndex, endIndex):
if startIndex == endIndex:
return startIndex
median = (endIndex-startIndex)/2 +startIndex
(data, info) = self.ordList[median]
if info > pivot:
return self.getIndexRec( pivot, startIndex, max(0,median-1) )
if info < pivot:
return self.getIndexRec( pivot, min(median+1,endIndex), endIndex )
return median
def getData(self, ref):
self.ordList = self.ordList[self.getIndex(ref-self.delta):]
if len(self.ordList) == 0:
self.dataDict = {}
return [ x for (x,y) in self.ordList ]
| jlzirani/cache-storing | store.py | Python | gpl-3.0 | 1,439 | 0.039611 |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except jin 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 ..layers import collective
from ..framework import Parameter
__parallel_ctx__clz__ = None
def _is_data_parallel_mode():
global __parallel_ctx__clz__
return __parallel_ctx__clz__ is not None and int(
os.getenv("PADDLE_TRAINERS_NUM", "1")) > 1
def _set_parallel_ctx(nccl_parallel_context):
global __parallel_ctx__clz__
assert __parallel_ctx__clz__ is None, \
"ParallelContext can only be initialized once."
__parallel_ctx__clz__ = nccl_parallel_context
def _init_parallel_ctx():
global __parallel_ctx__clz__
assert __parallel_ctx__clz__ is not None, \
"ParallelContext should be initialized."
__parallel_ctx__clz__.init()
def _broadcast_parameters(parameters):
for param in parameters:
if isinstance(param, Parameter) and param.trainable:
collective._broadcast(param, 0, sync_mode=True)
| chengduoZH/Paddle | python/paddle/fluid/dygraph/parallel_helper.py | Python | apache-2.0 | 1,499 | 0 |
#! /usr/bin/env python
##############################################################################
#
# Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is installed.
#
##############################################################################
__doc__ = """Monitor Java Management eXtension (JMX) mbeans
Dispatches calls to a java server process to collect JMX values for a device.
"""
import logging
import sys
import os
import socket
import Globals
import zope
from twisted.internet.defer import Deferred
from twisted.web import xmlrpc
from twisted.internet.protocol import ProcessProtocol
from twisted.internet import defer, reactor, error
from Products.ZenCollector.daemon import CollectorDaemon
from Products.ZenCollector.interfaces import ICollectorPreferences,\
IDataService,\
IEventService,\
IScheduledTask
from Products.ZenCollector.tasks import SimpleTaskFactory,\
SimpleTaskSplitter,\
TaskStates
from Products.ZenEvents import Event
from Products.ZenHub.XmlRpcService import XmlRpcService
from Products.ZenUtils.NJobs import NJobs
from Products.ZenUtils.Utils import unused
from Products.ZenUtils.observable import ObservableMixin
import ZenPacks.zenoss.ZenJMX
from ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService import JMXDataSourceConfig
unused(JMXDataSourceConfig)
log = logging.getLogger( "zen.zenjmx" )
DEFAULT_HEARTBEAT_TIME = 5 * 60
WARNING_EVENT = dict(eventClass='/Status/JMX', component='JMX',
device=socket.getfqdn(), severity=Event.Warning)
class ZenJMXPreferences(object):
"""
Configuration values for the zenjmx daemon.
"""
zope.interface.implements(ICollectorPreferences)
def __init__(self):
"""
Construct a new ZenJMXPreferences instance and provide default
values for needed attributes.
"""
self.collectorName = "zenjmx"
self.defaultRRDCreateCommand = None
self.cycleInterval = 5 * 60 # seconds
self.configCycleInterval = 20 # minutes
self.options = None
# the configurationService attribute is the fully qualified class-name
# of our configuration service that runs within ZenHub
self.configurationService = 'ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService'
def buildOptions(self, parser):
parser.add_option('-j','--zenjmxjavaport',
dest='zenjmxjavaport',
default=9988,
type='int',
help='Port for zenjmxjava process; default 9988. '+\
'Tries 5 consecutive ports if there is a conflict',
)
parser.add_option('--concurrentJMXCalls',
dest='concurrentJMXCalls',
action='store_true', default=False,
help='Enable concurrent calls to a JMX server'
)
parser.add_option('--parallel', dest='parallel',
default=200, type='int',
help='Number of devices to collect from at one time'
)
parser.add_option('--cycleInterval', dest='cycleInterval',
default=300, type='int',
help='Cycle time, in seconds, to run collection'
)
parser.add_option('--portRange', dest='portRange',
default=5, type='int',
help='Number of ports to attempt when starting' +
'Java jmx client')
parser.add_option('--javaheap',
dest="maxHeap",type="int", default=512,
help="Max heap, in MB, to use for java process")
def postStartup(self):
pass
def getJavaClientArgs(self):
args = None
if self.options.configfile:
args = ('--configfile', self.options.configfile)
if self.options.logseverity:
args = args + ('-v', str(self.options.logseverity))
if self.options.concurrentJMXCalls:
args = args + ('-concurrentJMXCalls', )
return args
def getStartingPort(self):
return self.options.zenjmxjavaport
def getAttemptedPortRange(self):
return self.options.portRange
class IZenJMXJavaClient(zope.interface.Interface):
listenPort = zope.interface.Attribute("listenPort")
class ZenJMXJavaClientImpl(ProcessProtocol):
"""
Protocol to control the zenjmxjava process
"""
zope.interface.implements(IZenJMXJavaClient)
def __init__(
self,
args,
cycle=True,
zenjmxjavaport=9988,
maxHeap=512
):
"""
Initializer
@param args: argument list for zenjmx
@type args: list of strings
@param cycle: whether to run once or repeat
@type cycle: boolean
@param zenjmxjavaport: port on which java process
will listen for queries
@type zenjmxjavaport: int
"""
self.deferred = Deferred()
self.stopCalled = False
self.process = None
self.outReceived = sys.stdout.write
self.errReceived = sys.stderr.write
self.log = logging.getLogger('zen.ZenJMXJavaClient')
self.args = args
self.cycle = cycle
self.listenPort = zenjmxjavaport
self._maxHeap = maxHeap
self.restartEnabled = False
self._eventService = zope.component.queryUtility(IEventService)
self._preferences = zope.component.queryUtility(ICollectorPreferences,
'zenjmx')
def processEnded(self, reason):
"""
Twisted reactor function called when the process ends.
@param reason: message from the process
@type reason: string
"""
self.process = None
if not self.stopCalled:
procEndEvent = {
'eventClass': '/Status/JMX',
'summary': 'zenjmxjava ended unexpectedly: %s'\
% reason.getErrorMessage(),
'severity': Event.Warning,
'component': 'zenjmx',
'device': self._preferences.options.monitor,
}
self._eventService.sendEvent(procEndEvent)
self.log.warn('processEnded():zenjmxjava process ended %s'
% reason)
if self.deferred:
msg = reason.getErrorMessage()
exitCode = reason.value.exitCode
if exitCode == 10:
msg = 'Could not start up Java web server, '+\
'possible port conflict'
self.deferred.callback((exitCode,msg))
self.deferred = None
elif self.restartEnabled:
self.log.info('processEnded():restarting zenjmxjava')
reactor.callLater(1, self.run)
def stop(self):
"""
Twisted reactor function called when we are shutting down.
"""
import signal
self.log.info('stop():stopping zenjmxjava')
self.stopCalled = True
if not self.process:
self.log.debug('stop():no zenjmxjava process to stop')
return
try:
self.process.signalProcess(signal.SIGKILL)
except error.ProcessExitedAlready:
self.log.info('stop():zenjmxjava process already exited')
pass
try:
self.process.loseConnection()
except Exception:
pass
self.process = None
def connectionMade(self):
"""
Called when the Twisted reactor starts up
"""
self.log.debug('connectionMade():zenjmxjava started')
def doCallback():
"""
doCallback
"""
msg = \
'doCallback(): callback on deferred zenjmxjava proc is up'
self.log.debug(msg)
if self.deferred:
self.deferred.callback((True,'zenjmx java started'))
if self.process:
procStartEvent = {
'eventClass': '/Status/JMX',
'summary': 'zenjmxjava started',
'severity': Event.Clear,
'component': 'zenjmx',
'device': self._preferences.options.monitor,
}
self._eventService.sendEvent(procStartEvent)
self.deferred = None
if self.deferred:
self.log.debug('connectionMade():scheduling callback')
# give the java service a chance to startup
reactor.callLater(3, doCallback)
self.log.debug('connectionMade(): done')
def run(self):
"""
Twisted function called when started
"""
if self.stopCalled:
return
self.log.info('run():starting zenjmxjava')
zenjmxjavacmd = os.path.join(ZenPacks.zenoss.ZenJMX.binDir,
'zenjmxjava')
if self.cycle:
args = ('runjmxenabled', )
else:
# don't want to start up with jmx server to avoid port conflicts
args = ('run', )
args = args + ('-zenjmxjavaport',
str(self.listenPort))
if self.args:
args = args + self.args
cmd = (zenjmxjavacmd, ) + args
self.log.debug('run():spawn process %s' % (cmd, ))
self.deferred = Deferred()
env = dict(os.environ)
env['JVM_MAX_HEAP'] = '-Xmx%sm'%self._maxHeap
self.process = reactor.spawnProcess(self, zenjmxjavacmd, cmd,
env=env)
return self.deferred
DEFAULT_JMX_JAVA_CLIENT_NAME = 'zenjmxjavaclient'
class ZenJMXJavaClientInitialization(object):
"""
Wrapper that continues to start the Java jmx client until
successful.
"""
def __init__(self,
registeredName=DEFAULT_JMX_JAVA_CLIENT_NAME):
"""
@param registeredName: the name with which this client
will be registered as a utility
"""
self._jmxClient = None
self._clientName = registeredName
def initialize(self):
"""
Begin the first attempt to start the Java jmx client. Note that
this method returns a Deferred that relies on the ZenJMXPreferences
being present when it is finally executed. This is meant to be
the Deferred that is given to the CollectorDaemon for
initialization before the first JMX task is scheduled.
@return the deferred that represents the loading of preferences
and the initial attempt to start the Java jmx client
@rtype defer.Deferred
"""
def loadPrefs():
log.debug( "Retrieving java client startup args")
preferences = zope.component.queryUtility(ICollectorPreferences,
'zenjmx')
self._args = preferences.getJavaClientArgs()
self._cycle = preferences.options.cycle
self._maxHeap = preferences.options.maxHeap
self._startingPort = preferences.getStartingPort()
self._rpcPort = self._startingPort
self._attemptedPortRange = preferences.getAttemptedPortRange()
def printProblem(result):
log.error( str(result) )
sys.exit(1)
d = defer.maybeDeferred( loadPrefs )
d.addCallback( self._startJavaProc )
d.addErrback( printProblem )
return d
def _tryClientOnCurrentPort( self ):
"""
Returns the Deferred for executing an attempt
to start the java jmx client on the current port.
"""
log.debug( 'Attempting java client startup on port %s',
self._rpcPort )
self._jmxClient = ZenJMXJavaClientImpl( self._args, self._cycle, self._rpcPort, self._maxHeap )
zope.component.provideUtility(
self._jmxClient,
IZenJMXJavaClient,
self._clientName
)
return self._jmxClient.run()
def _startJavaProc( self, result=None ):
"""
Checks whether startup of the java jmx client was successful. If
it was unsuccessful due to port conflict, increments the port and
tries to start the client again.
"""
# If the result is not None, that means this was called as a callback
# after an attempt to start the client
if result is not None:
# If result[0] is True, the client process started
if result[0] is True:
log.debug( 'Java jmx client started' )
self._jmxClient.restartEnabled = True
deferred = defer.succeed( True )
# If the result[0] is 10, there was a port conflict
elif result[0] == 10:
log.debug( 'Java client didn\'t start; port %s occupied',
self._rpcPort )
if self._rpcPort < ( self._startingPort +
self._attemptedPortRange ):
self._rpcPort += 1
deferred = self._tryClientOnCurrentPort()
deferred.addCallback( self._startJavaProc )
else:
raise RuntimeError(
"ZenJMXJavaClient could not be started, check ports")
else:
#unknown error
raise RuntimeError('ZenJMXJavaClient could not be started, '+\
'check JVM type and version: %s' % result[1])
# If there was no result passed in, then this is the first attempt
# to start the client
else:
deferred = self._tryClientOnCurrentPort()
deferred.addCallback( self._startJavaProc )
return deferred
class ZenJMXTask(ObservableMixin):
"""
The scheduled task for all the jmx datasources on an individual device.
"""
zope.interface.implements(IScheduledTask)
def __init__(self,
deviceId,
taskName,
scheduleIntervalSeconds,
taskConfig,
clientName=DEFAULT_JMX_JAVA_CLIENT_NAME ):
super( ZenJMXTask, self ).__init__()
self.name = taskName
self.configId = deviceId
self.state = TaskStates.STATE_IDLE
self._taskConfig = taskConfig
self._manageIp = self._taskConfig.manageIp
self._dataService = zope.component.queryUtility( IDataService )
self._eventService = zope.component.queryUtility( IEventService )
self._preferences = zope.component.queryUtility( ICollectorPreferences,
'zenjmx' )
self._client = zope.component.queryUtility( IZenJMXJavaClient,
clientName )
# At this time, do not use the interval passed from the device
# configuration. Use the value pulled from the daemon
# configuration.
unused( scheduleIntervalSeconds )
self.interval = self._preferences.options.cycleInterval
def createEvent(self, errorMap, component=None):
"""
Given an event dictionary, copy it and return the event
@param errorMap: errorMap
@type errorMap: s dictionarytring
@param component: component name
@type component: string
@return: updated event
@rtype: dictionary
"""
event = errorMap.copy()
if component:
event['component'] = component
if event.get('datasourceId') and not event.get('eventKey'):
event['eventKey'] = event.get('datasourceId')
return event
def sendEvent(self, event, **kw):
self._eventService.sendEvent(event, **kw)
def _collectJMX(self, dsConfigList):
"""
Call Java JMX process to collect JMX values
@param dsConfigList: DataSource configuration
@type dsConfigList: list of JMXDataSourceConfig
@return: Twisted deferred object
@rtype: Twisted deferred object
"""
def toDict(config):
"""
Marshall the fields from the datasource into a dictionary and
ignore everything that is not a primitive
@param config: dictionary of results
@type config: string
@return: results from remote device
@rtype: dictionary
"""
vals = {}
for (key, val) in config.__dict__.items():
if key != 'rrdConfig' and type(val)\
in XmlRpcService.PRIMITIVES:
vals[key] = val
rrdConfigs = config.rrdConfig.values()
rrdConfigs.sort(lambda x, y: cmp(x.dataPointId,
y.dataPointId))
vals['dps'] = []
vals['dptypes'] = []
for rrdConfig in rrdConfigs:
vals['dps'].append(rrdConfig.dataPointId)
vals['dptypes'].append(rrdConfig.rrdType)
vals['connectionKey'] = config.getConnectionPropsKey()
return vals
def rpcCall():
"""
Communicate with our local JMX process to collect results.
This is a generator function
@param driver: generator
@type driver: string
"""
port = self._client.listenPort
xmlRpcProxy = xmlrpc.Proxy('http://localhost:%s/' % port)
d = xmlRpcProxy.callRemote('zenjmx.collect', configMaps)
d.addCallbacks( processResults , processRpcError)
return d
def processRpcError(error):
log.debug("Could not make XML RPC call for device %s; content of call: %s", self._taskConfig, configMaps)
self.sendEvent({}, severity=Event.Error,
eventClass='/Status/JMX',
summary='unexpected error: %s' % error.getErrorMessage(),
eventKey='unexpected_xmlrpc_error',
device=self.configId)
return error
def processResults(jmxResults):
"""
Given the results from JMX, store them or send events.
@param jmxResults: jmxResults
@type jmxResults: string
"""
#Send clear for RPC error
self.sendEvent({}, severity=Event.Clear,
eventClass='/Status/JMX',
summary='unexpected error cleared',
eventKey='unexpected_xmlrpc_error',
device=self.configId)
result = {}
hasConnectionError = False
hasUnexpectedError = False
for result in jmxResults:
log.debug("JMX result -> %s", result)
evtSummary = result.get('summary')
deviceId = result.get('device')
evt = self.createEvent(result)
if not evtSummary:
rrdPath = result.get('rrdPath')
dsId = result.get('datasourceId')
dpId = result.get('dpId')
value = result.get('value')
try:
self.storeRRD(deviceId, rrdPath, dsId, dpId, value)
except ValueError:
pass
self.sendEvent(evt,summary="Clear",severity=Event.Clear)
else:
# send event
log.debug('processResults(): '
+ 'jmx error, sending event for %s'
% result)
if evt.get("eventClass", "") == '/Status/JMX/Connection':
hasConnectionError = True
if evt.get("eventKey", "") == 'unexpected_error':
hasUnexpectedError = True
self.sendEvent(evt, severity=Event.Error)
if not hasConnectionError:
self.sendEvent({}, severity=Event.Clear,
eventClass='/Status/JMX/Connection',
summary='Connection is up',
eventKey=connectionComponentKey,
device=self.configId)
if not hasUnexpectedError:
self.sendEvent({}, severity=Event.Clear,
eventClass='/Status/JMX',
summary='Unexpected error cleared',
eventKey='unexpected_error',
device=self.configId)
return jmxResults
connectionComponentKey = ''
configMaps = []
for config in dsConfigList:
connectionComponentKey = config.getConnectionPropsKey()
configMaps.append(toDict(config))
log.info('collectJMX(): for %s %s' % (config.device,
connectionComponentKey))
return rpcCall()
def storeRRD(
self,
deviceId,
rrdPath,
dataSourceId,
dataPointId,
dpValue,
):
"""
Store a value into an RRD file
@param deviceId: name of the remote device
@type deviceId: string
@param dataSourceId: name of the data source
@type dataSourceId: string
@param dataPointId: name of the data point
@type dataPointId: string
@param dpValue: dpValue
@type dpValue: number
"""
deviceConfig = self._taskConfig
dsConfig = deviceConfig.findDataSource(dataSourceId)
if not dsConfig:
log.info(
'No data source config found for device %s datasource %s' \
% (deviceId, dataSourceId))
return
rrdConf = dsConfig.rrdConfig.get(dataPointId)
type = rrdConf.rrdType
if(type in ('COUNTER', 'DERIVE')):
try:
# cast to float first because long('100.0') will fail with a
# ValueError
dpValue = long(float(dpValue))
except (TypeError, ValueError):
log.warning("value %s not valid for derive or counter data points", dpValue)
else:
try:
dpValue = float(dpValue)
except (TypeError, ValueError):
log.warning("value %s not valid for data point", dpValue)
if not rrdConf:
log.info(
'No RRD config found for device %s datasource %s datapoint %s' \
% (deviceId, dataSourceId, dataPointId))
return
dpPath = '/'.join((rrdPath, rrdConf.dpName))
min = rrdConf.min
max = rrdConf.max
self._dataService.writeRRD(dpPath, dpValue, rrdConf.rrdType,
rrdConf.command, min=min, max=max)
def _finished(self, results):
for result in results:
log.debug("Finished with result %s" % str( result ) )
return results
def doTask(self):
log.debug("Scanning device %s [%s]", self.configId, self._manageIp)
d = self._collectCallback()
d.addBoth(self._finished)
# returning a Deferred will keep the framework from assuming the task
# is done until the Deferred actually completes
return d
def _collectCallback(self):
jobs = NJobs(self._preferences.options.parallel,
self._collectJMX,
self._taskConfig.jmxDataSourceConfigs.values())
deferred = jobs.start()
return deferred
def cleanup(self):
pass
def stopJavaJmxClients():
# Currently only starting/stopping one.
clientName = DEFAULT_JMX_JAVA_CLIENT_NAME
client = zope.component.queryUtility( IZenJMXJavaClient,
clientName )
if client is not None:
log.debug( 'Shutting down JMX Java client %s' % clientName )
client.stop()
if __name__ == '__main__':
myPreferences = ZenJMXPreferences()
initialization = ZenJMXJavaClientInitialization()
myTaskFactory = SimpleTaskFactory(ZenJMXTask)
myTaskSplitter = SimpleTaskSplitter(myTaskFactory)
daemon = CollectorDaemon(myPreferences, myTaskSplitter,
initializationCallback=initialization.initialize,
stoppingCallback=stopJavaJmxClients)
daemon.run()
| krull/docker-zenoss4 | init_fs/usr/local/zenoss/ZenPacks/ZenPacks.zenoss.ZenJMX-3.12.1.egg/ZenPacks/zenoss/ZenJMX/zenjmx.py | Python | gpl-3.0 | 25,284 | 0.006051 |
import webapp2
from jinja2 import Environment, FileSystemLoader
from os.path import dirname, join
import os
import json
import base64
import hashlib
import StringIO
from google.appengine.api import users
import numpy as np
if not os.environ.get('SERVER_SOFTWARE','').startswith('Development'):
import PIL
import matplotlib.pyplot as plt
import matplotlib.cm as cm
#from scipy.ndimage.morphology import grey_dilation
import Image
local = False
else:
local = True
from lib_db import SeismicObject, PickrParent
# Jinja2 environment to load templates.
env = Environment(loader=FileSystemLoader(join(dirname(__file__),
'templates')))
# Data store set up.
db_parent = PickrParent.all().get()
if not db_parent:
db_parent = PickrParent()
db_parent.put()
class CommentHandler(webapp2.RequestHandler):
def get(self):
index = int(self.request.get("index"))
data = SeismicObject.all().ancestor(db_parent).sort("-date")
data = data.fetch(1000)[index]
self.response.write(json.dumps(data.comments))
def post(self):
index = int(self.request.get("index"))
comment = int(self.request.get("comment"))
data = SeismicObject.all().ancestor(db_parent).sort("-date")
data = data.fetch(1000)[index]
comments = data.comments
comments.append(comment)
data.comments = comments
data.put()
self.response.write(comment)
class VoteHandler(webapp2.RequestHandler):
def get(self):
index = int(self.request.get("index"))
data = SeismicObject.all().ancestor(db_parent).order("-date")
data = data.fetch(1000)[index]
self.response.write(data.votes)
def post(self):
index = int(self.request.get("index"))
vote = int(self.request.get("vote"))
data = SeismicObject.all().ancestor(db_parent).order("-date")
data = data.fetch(1000)[index]
if vote > 0:
vote = 1
else:
vote =-1
data.votes += vote
data.put()
self.response.write(data.votes)
class MainPage(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if not user:
login_url = users.create_login_url('/')
template = env.get_template("main.html")
html = template.render(login_url=login_url)
self.response.out.write(html)
else:
logout_url = users.create_logout_url('/')
login_url = None
email_hash = hashlib.md5(user.email()).hexdigest()
self.redirect('/pickr')
class ResultsHandler(webapp2.RequestHandler):
def get(self):
# connect the dots using one dimensional linear interpretation: np.interp()
def regularize(xarr, yarr, pxi, pxf):
# connect the dots of the horizon spanning the image
# pxi : is the first x pos.
# pyi : is the first y pos., and so on
horx = np.arange(pxi,pxf+1)
hory = np.interp(horx, xarr, yarr)
return horx, hory
# append all horizons into one big file
all_picks_x = np.array([])
all_picks_y = np.array([])
data = SeismicObject().all().fetch(1000)
count = len(data)
if not local:
fig = plt.figure(figsize=(15,8))
ax = fig.add_axes([0,0,1,1])
# Load the image to a variable
im = Image.open('brazil_ang_unc.png')
px, py = im.size
# plot the seismic image first
# im = plt.imshow(im)
# Make a modified version of rainbow colormap with some transparency
# in the bottom of the colormap.
hot = cm.hot
hot.set_under(alpha = 0.0) #anything that has value less than 0.5 goes transparent
for user in data:
try:
picks = np.array(json.loads(user.picks))
hx, hy = regularize(picks[:,0], picks[:,1], pxi, pyf)
all_picks_x = np.concatenate((all_picks_x,hx))
all_picks_y = np.concatenate((all_picks_y,hy))
ax.plot(picks[:,0], picks[:,1], 'g-', alpha=0.5, lw=2)
m = 1
x1, x2 = np.amin(all_picks_x), np.amax(all_picks_x)
y1, y2 = np.amin(all_picks_y),np.amax(all_picks_y)
heat_extent_im = [x1,x2,y2,y1] #flip extents of heatmap for image plot
# do 2d histogram to display heatmap
binsizex = m
binsizey = m
heatmap, yedges, xedges = np.histogram2d(all_picks_y, all_picks_x,
bins= ((y2-y1)/binsizey,(x2-x1)/binsizex),
range =np.array([[y1, y2],[x1, x2]])
)
# do dilation of picks in heatmap
from mmorph import dilate
n = 3 #should be odd integer
B = np.array((n,n)).astype(int)
heatmap_dil = dilate(heatmap, B=B)
#fig = plt.figure(figsize=(15,8))
#ax = fig.add_axes([0, 0, 1, 1])
heatim = ax.imshow(heatmap_dil,
cmap=cm.hot,
extent=heat_extent_im,
alpha=0.75)
heatim.set_clim(0.5, np.amax(heatmap))
ax.set_ylim((py,0))
ax.set_xlim((0,px))
#ax.invert_yaxis()
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
except:
pass
output = StringIO.StringIO()
plt.savefig(output)
image = base64.b64encode(output.getvalue())
user = users.get_current_user()
# User should exist, so this should fail otherwise.
logout_url = users.create_logout_url('/')
login_url = None
email_hash = hashlib.md5(user.email()).hexdigest()
template = env.get_template("results.html")
html = template.render(count=count,
logout_url=logout_url,
email_hash=email_hash,
image=image)
self.response.write(html)
else:
with open("alaska.b64", "r") as f:
image = f.read()
user = users.get_current_user()
# User should exist, so this should fail otherwise.
logout_url = users.create_logout_url('/')
login_url = None
email_hash = hashlib.md5(user.email()).hexdigest()
template = env.get_template("results.html")
html = template.render(count=count,
logout_url=logout_url,
email_hash=email_hash,
image=image)
self.response.write(html)
# Make composite image
class AboutHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
logout_url = users.create_logout_url('/')
login_url = None
email_hash = hashlib.md5(user.email()).hexdigest()
else:
logout_url = None
login_url = users.create_login_url('/')
email_hash = ''
# Write the page.
template = env.get_template('about.html')
html = template.render(logout_url=logout_url,
login_url=login_url,
email_hash=email_hash)
self.response.write(html)
class TermsHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
logout_url = users.create_logout_url('/')
login_url = None
email_hash = hashlib.md5(user.email()).hexdigest()
else:
logout_url = None
login_url = users.create_login_url('/')
email_hash = ''
# Write the page.
template = env.get_template('terms.html')
html = template.render(logout_url=logout_url,
login_url=login_url,
email_hash=email_hash)
self.response.write(html)
class PickerHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
# User should exist, so this should fail otherwise.
logout_url = users.create_logout_url('/')
login_url = None
email_hash = hashlib.md5(user.email()).hexdigest()
# Write the page.
template = env.get_template('pickpoint.html')
html = template.render(logout_url=logout_url,
login_url=login_url,
email_hash=email_hash)
self.response.write(html)
## class UploadHandler(blobstore_handlers.BlobstoreUploadHandler,
## webapp2.RequestHandler):
## def post(self):
## upload_file = self.get_uploads()
## blob_info = upload_files[0]
## # Read the image file
## reader = blobstore.BlobReader(blob_info.key())
## im = Image.open(reader, 'r')
## im = im.convert('RGB').resize((350,350))
## output = StringIO.StringIO()
## im.save(output, format='PNG')
## bucket = '/pickr_bucket/'
## output_filename = (bucket +'/2' + str(time.time()))
## gcsfile = gcs.open(output_filename, 'w')
## gcsfile.write(output.getvalue())
## output.close()
## gcsfile.close()
## # Make a blob reference
## bs_file = '/gs' + output_filename
## output_blob_key = blobstore.create_gs_key(bs_file)
## name = self.request.get("name")
## description = self.request.get("description")
## new_db = SeismicObject(name=name, description=description,
## image=output_blob_key)
## new_db.put()
## self.redirect('/')
class PickHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if self.request.get("user_picks"):
data = \
SeismicObject.all().ancestor(db_parent).filter("user =",
user).get()
if data:
picks = data.picks
else:
picks = json.dumps([])
self.response.write(picks)
return
if self.request.get("all"):
data = SeismicObject.all().fetch(1000)
picks = [i.picks for i in data]
self.response.write(data)
return
if self.request.get("pick_index"):
data = SeismicObject.all().ancestor(db_parent)
data = data.order("-date").fetch(1000)
index = int(self.request.get("pick_index"))
self.response.write(data[index].picks)
return
def post(self):
point = (int(self.request.get("x")),
int(self.request.get("y")))
user = users.get_current_user()
if not user:
self.redirect('/')
d = SeismicObject.all().ancestor(db_parent).filter("user =",
user).get()
if not d:
d = SeismicObject(picks=json.dumps([point]).encode(),
user=user, parent=db_parent,votes=0)
d.put()
else:
picks = json.loads(d.picks)
picks.append(point)
d.picks = json.dumps(picks).encode()
d.put()
self.response.write("Ok")
def delete(self):
user = users.get_current_user()
data = \
SeismicObject.all().ancestor(db_parent).filter("user =",
user).get()
points = json.loads(data.picks)
if self.request.get("clear"):
data.delete()
value = []
elif self.request.get("undo"):
value = points.pop()
data.picks = json.dumps(points).encode()
data.put()
self.response.write(json.dumps(value))
## class AddImageHandler(webapp2.RequestHandler):
## def get(self):
## upload_url = blobstore.create_upload_url('/upload')
## template = env.get_template("new_image.html")
## html = template.render(upload_url=upload_url))
## self.response.write(html)
# This is the app.
app = webapp2.WSGIApplication([
('/', MainPage),
#('/upload', UploadModel),
#('/new_image', AddImageHandler),
('/about', AboutHandler),
('/update_pick', PickHandler),
('/pickr', PickerHandler),
('/terms', TermsHandler),
('/results', ResultsHandler),
('/comment', CommentHandler),
('/vote', VoteHandler)],
debug=True)
| EvanBianco/pickr | main.py | Python | apache-2.0 | 13,664 | 0.009075 |
from elasticsearch_dsl import query
from kuma.core.tests import eq_, ok_
from kuma.wiki.search import WikiDocumentType
from . import ElasticTestCase
class WikiDocumentTypeTests(ElasticTestCase):
fixtures = ElasticTestCase.fixtures + ['wiki/documents.json']
def test_get_excerpt_strips_html(self):
self.refresh()
results = WikiDocumentType.search().query('match', content='audio')
ok_(results.count() > 0)
for doc in results.execute():
excerpt = doc.get_excerpt()
ok_('audio' in excerpt)
ok_('<strong>' not in excerpt)
def test_current_locale_results(self):
self.refresh()
results = (WikiDocumentType.search()
.query(query.Match(title='article') |
query.Match(content='article'))
.filter('term', locale='en-US'))
for doc in results.execute():
eq_('en-US', doc.locale)
def test_get_excerpt_uses_summary(self):
self.refresh()
results = WikiDocumentType.search().query('match', content='audio')
ok_(results.count() > 0)
for doc in results.execute():
excerpt = doc.get_excerpt()
ok_('the word for tough things' in excerpt)
ok_('extra content' not in excerpt)
def test_hidden_slugs_get_indexable(self):
self.refresh()
title_list = WikiDocumentType.get_indexable().values_list('title',
flat=True)
ok_('User:jezdez' not in title_list)
| safwanrahman/kuma | kuma/search/tests/test_types.py | Python | mpl-2.0 | 1,629 | 0 |
"""config URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^cards/', include('cards.urls')),
url(r'^tournaments/', include('tournaments.urls')),
url(r'^stats/', include('stats.urls'))
]
| thomasperrot/MTGTrader | mtg/config/urls.py | Python | mit | 915 | 0 |
# Copyright 2020 D-Wave Systems 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.
from collections.abc import Sequence, Set
from dimod.bqm.adjvectorbqm import AdjVectorBQM
from dimod.core.bqm import BQM
from dimod.vartypes import as_vartype
__all__ = ['as_bqm']
def as_bqm(*args, cls=None, copy=False):
"""Convert the input to a binary quadratic model.
Converts the following input formats to a binary quadratic model (BQM):
as_bqm(vartype)
Creates an empty binary quadratic model.
as_bqm(bqm)
Creates a BQM from another BQM. See `copy` and `cls` kwargs below.
as_bqm(bqm, vartype)
Creates a BQM from another BQM, changing to the appropriate
`vartype` if necessary. See `copy` and `cls` kwargs below.
as_bqm(n, vartype)
Creates a BQM with `n` variables, indexed linearly from zero,
setting all biases to zero.
as_bqm(quadratic, vartype)
Creates a BQM from quadratic biases given as a square array_like_
or a dictionary of the form `{(u, v): b, ...}`. Note that when
formed with SPIN-variables, biases on the diagonal are added to the
offset.
as_bqm(linear, quadratic, vartype)
Creates a BQM from linear and quadratic biases, where `linear` is a
one-dimensional array_like_ or a dictionary of the form
`{v: b, ...}`, and `quadratic` is a square array_like_ or a
dictionary of the form `{(u, v): b, ...}`. Note that when formed
with SPIN-variables, biases on the diagonal are added to the offset.
as_bqm(linear, quadratic, offset, vartype)
Creates a BQM from linear and quadratic biases, where `linear` is a
one-dimensional array_like_ or a dictionary of the form
`{v: b, ...}`, and `quadratic` is a square array_like_ or a
dictionary of the form `{(u, v): b, ...}`, and `offset` is a
numerical offset. Note that when formed with SPIN-variables, biases
on the diagonal are added to the offset.
Args:
*args:
See above.
cls (type/list, optional):
Class of the returned BQM. If given as a list,
the returned BQM is of one of the types in the list. Default is
:class:`.AdjVectorBQM`.
copy (bool, optional, default=False):
If False, a new BQM is only constructed when
necessary.
Returns:
A binary quadratic model.
.. _array_like: https://numpy.org/doc/stable/user/basics.creation.html
"""
if cls is None:
if isinstance(args[0], BQM):
cls = type(args[0])
else:
cls = AdjVectorBQM
elif isinstance(cls, (Sequence, Set)): # want Collection, but not in 3.5
classes = tuple(cls)
if not classes:
raise ValueError("cls kwarg should be a type or a list of types")
if type(args[0]) in classes:
cls = type(args[0])
else:
# otherwise just pick the first one
cls = classes[0]
if isinstance(args[0], cls) and not copy:
# this is the only case (currently) in which copy matters
if len(args) == 1:
return args[0]
elif len(args) == 2:
bqm, vartype = args
if bqm.vartype is as_vartype(vartype):
return bqm
# otherwise we're doing a copy
# otherwise we don't have a well-formed bqm input so pass off the check
# to cls(*args)
return cls(*args)
| dwavesystems/dimod | dimod/bqm/construction.py | Python | apache-2.0 | 4,145 | 0.000241 |
#!/bin/false
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
#
# 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/.
#
# ----------------------------------------------------------------------------------------
# This file contains information for a specific board - the available pins, and where LEDs,
# Buttons, and other in-built peripherals are. It is used to build documentation as well
# as various source and header files for Espruino.
# ----------------------------------------------------------------------------------------
import pinutils;
info = {
'name' : "ESP32",
'espruino_page_link' : 'ESP32',
'default_console' : "EV_SERIAL1",
'default_console_baudrate' : "115200",
'variables' : 5000,
'binary_name' : 'espruino_%v_esp32.bin',
'build' : {
'optimizeflags' : '-Og',
'libraries' : [
'ESP32',
'NET',
'GRAPHICS',
'CRYPTO',
'TLS',
'TELNET',
'NEOPIXEL',
'FILESYSTEM',
'FLASHFS'
],
'makefile' : [
'DEFINES+=-DESP_PLATFORM -DESP32=1'
]
}
};
chip = {
'part' : "ESP32",
'family' : "ESP32",
'package' : "",
'ram' : 512,
'flash' : 0,
'speed' : 160,
'usart' : 3,
'spi' : 2,
'i2c' : 2,
'adc' : 1,
'dac' : 0,
'saved_code' : {
'address' : 0x100000,
'page_size' : 4096,
'pages' : 16,
'flash_available' : 960, # firmware can be up to this size
},
};
devices = {
};
# left-right, or top-bottom order
board_esp32 = {
'top' : ['GND','D23','D22','D1','D3','D21','D20','D19','D18','D5','D17','D16','D4','D0'],
'bottom' : ['D12','D14','D27','D26','D25','D33','D32','D35','D34','D39','D36','EN','3V3','GND'],
'right' : [ 'GND','D13','D9','D10','D11','D6','D7','D8','D15','D2']
};
board_esp32["bottom"].reverse()
board_esp32["right"].reverse()
board_esp32["_css"] = """
#board {
width: 600px;
height: 435px;
left: 50px;
top: 170px;
background-image: url(img/ESP32.jpg);
}
#boardcontainer {
height: 700px;
}
#board #right {
top: 80px;
left: 600px;
}
#board #top {
bottom: 440px;
left: 155px;
}
#board #bottom {
top: 435px;
left: 155px;
}
#board .rightpin {
height: 28px;
}
#board .toppin, #board .bottompin {
width: 24px;
}
""";
boards = [ board_esp32 ];
def get_pins():
# { "name":"PD20", "sortingname":"D20", "port":"D", "num":"30", "functions":{ "I2C1_SDA":0 }, "csv":{} },
# pins = pinutils.generate_pins(0,5);
##6-11 are used by Flash chip
# pins.extend(pinutils.generate_pins(12,23));
# pins.extend(pinutils.generate_pins(25,27));
##32-33 are routed to rtc for xtal
# pins.extend(pinutils.generate_pins(34,39));
# pins = pinutils.fill_gaps_in_pin_list(pins);
pins = pinutils.generate_pins(0,39) # 40 General Purpose I/O Pins.
pinutils.findpin(pins, "PD36", True)["functions"]["ADC1_IN0"]=0;
pinutils.findpin(pins, "PD37", True)["functions"]["ADC1_IN1"]=0;
pinutils.findpin(pins, "PD38", True)["functions"]["ADC1_IN2"]=0;
pinutils.findpin(pins, "PD39", True)["functions"]["ADC1_IN3"]=0;
pinutils.findpin(pins, "PD32", True)["functions"]["ADC1_IN4"]=0;
pinutils.findpin(pins, "PD33", True)["functions"]["ADC1_IN5"]=0;
pinutils.findpin(pins, "PD34", True)["functions"]["ADC1_IN6"]=0;
pinutils.findpin(pins, "PD35", True)["functions"]["ADC1_IN7"]=0;
#ADC2 not supported yet, waiting for driver from espressif
pinutils.findpin(pins, "PD4", True)["functions"]["ADC2_IN0"]=0;
pinutils.findpin(pins, "PD0", True)["functions"]["ADC2_IN1"]=0;
pinutils.findpin(pins, "PD2", True)["functions"]["ADC2_IN2"]=0;
pinutils.findpin(pins, "PD15", True)["functions"]["ADC2_IN3"]=0;
pinutils.findpin(pins, "PD13", True)["functions"]["ADC2_IN4"]=0;
pinutils.findpin(pins, "PD12", True)["functions"]["ADC2_IN5"]=0;
pinutils.findpin(pins, "PD14", True)["functions"]["ADC2_IN6"]=0;
pinutils.findpin(pins, "PD27", True)["functions"]["ADC2_IN7"]=0;
pinutils.findpin(pins, "PD25", True)["functions"]["DAC_OUT1"]=0;
pinutils.findpin(pins, "PD26", True)["functions"]["DAC_OUT2"]=0;
pinutils.findpin(pins, "PD0", True)["functions"]["LED_1"]=0;
pinutils.findpin(pins, "PD10", True)["functions"]["USART0_TX"]=0;
pinutils.findpin(pins, "PD16", True)["functions"]["USART2_RX"]=0;
pinutils.findpin(pins, "PD17", True)["functions"]["USART2_TX"]=0;
pinutils.findpin(pins, "PD32", True)["functions"]["USART0_RX"]=0;
# everything is non-5v tolerant
#for pin in pins:
# pin["functions"]["3.3"]=0;
return pins
| luetgendorf/Espruino | boards/ESP32.py | Python | mpl-2.0 | 4,723 | 0.035994 |
# -*- coding: utf-8 -*-
#
# This file is part of Istex_Mental_Rotation.
# Copyright (C) 2016 3ST ERIC Laboratory.
#
# This is a free software; you can redistribute it and/or modify it
# under the terms of the Revised BSD License; see LICENSE file for
# more details.
# Load and transform ISTEX and wiki articles into bag_of_words decomposed by SVD.
# co-author : Lucie Martinet <lucie.martinet@univ-lorraine.fr>
# co-author : Hussein AL-NATSHEH <hussein.al-natsheh@ish-lyon.cnrs.fr.>
# Affiliation: University of Lyon, ERIC Laboratory, Lyon2
# Thanks to ISTEX project for the funding
import os, argparse, pickle, json
import numpy as np
def get_article_by_istex_id(istex_ids, istex_dir):
size = len(istex_ids)
res = np.array(range(size), dtype=np.object)
i = 0
for fname in os.listdir(istex_dir):
for doc in json.load(open(os.path.join(istex_dir, fname))):
istex_id = doc["istex_id"]
if istex_id in istex_ids :
article = dict()
article['text'] = doc["title"] + " __ " + doc["abstract"]
article['publicationDate'] = doc["publicationDate"]
article["istex_id"] = doc["istex_id"]
res[i] = article
i += 1
res = res.tolist()
res = res[:i]
return res
if __name__ == "__main__" :
parser = argparse.ArgumentParser()
parser.add_argument("--results_file", default='results/istex_mr_top10k_vec150results.pickle', type=str)
parser.add_argument("--istex_dir", default='sample_data/ISTEX/', type=str)
parser.add_argument("--out_file", default="chart_input.json", type=str) # name of the output file
parser.add_argument("--out_dir", default="results", type=str) # name of the output directory
args = parser.parse_args()
results_file = args.results_file
istex_dir = args.istex_dir
out_file = args.out_file
out_dir = args.out_dir
if not os.path.exists(out_dir):
os.makedirs(out_dir)
results = pickle.load(open(results_file,'rb'))
istex_ids = results.keys()
print "length of the results keys (istex_ids): ", len(istex_ids)
articles = get_article_by_istex_id(istex_ids, istex_dir)
json.dump(articles, open(os.path.join(out_dir, out_file), "w"), indent=2)
print 'length of response file: ', len(articles)
print 'response file could be found at: ', os.path.join(out_dir, out_file)
| ERICUdL/ISTEX_MentalRotation | ids2docs_years.py | Python | bsd-3-clause | 2,227 | 0.021105 |
# -*- coding: utf-8 -*-
from pulp.server.db.model.base import Model
class Role(Model):
"""
Represents a role and a set of permissions associated with that role.
Users that are added to this role will inherit all the permissions associated
with the role.
@ivar id: role's id, must be unique for each role
@type id: str
@ivar display_name: user-readable name of the role
@type display_name: str
@ivar description: free form text used to describe the role
@type description: str
@ivar permissions: dictionary of resource: tuple of allowed operations
@type permissions: dict
"""
collection_name = 'roles'
unique_indices = ('id',)
def __init__(self, id, display_name=None, description=None, permissions=None):
super(Role, self).__init__()
self.id = id
self.display_name = display_name or id
self.description = description
self.permissions = permissions or {}
class Permission(Model):
"""
Represents the user permissions associated with a pulp resource.
@ivar resource: uri path of resource
@type resource: str
@ivar users: list of dictionaries of user logins and permissions
@type users: list
"""
collection_name = 'permissions'
unique_indices = ('resource',)
def __init__(self, resource, users=None):
super(Permission, self).__init__()
self.resource = resource
self.users = users or []
| ulif/pulp | server/pulp/server/db/model/auth.py | Python | gpl-2.0 | 1,467 | 0.001363 |
#: one
x = 1
print(x)
import time
time.sleep(10)
#: two
#x = 2
print(x)
| lemon24/intercessor | examples/book.py | Python | bsd-3-clause | 78 | 0.038462 |
from selenium import webdriver
from selenium.webdriver import ActionChains
from os import path
import time
#NOTE: this demo uses images under images subfolder to find by name.
# Be sure to configure AutoPyDriverServer to use that folder for images by name
# start up both Firefox & AutoPyDriver for demo
browser = webdriver.Firefox()
autopy_driver = webdriver.Remote( command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities={'browserName':'AutoPy','imageRecognitionToleranceValue':0.0})
print "Desired Capabilities returned by server:\n"
print autopy_driver.desired_capabilities
print ""
# launch browser to Drag & drop page for demo test
browser.get("http://html5demos.com/drag")
if len(browser.find_elements_by_tag_name("li")) != 5:
print "Drag & drop test page not in correct state for demo test"
time.sleep(5)
src = autopy_driver.find_element_by_name('drag_src_html5.png')
target = autopy_driver.find_element_by_name('drop_target_html5.png')
actions = ActionChains(autopy_driver)
actions.drag_and_drop(src,target).perform()
# check results, drag & drop reduced items by 1 from 5 to 4
result = len(browser.find_elements_by_tag_name('li'))
if result != 4:
print 'Drag & drop failed. There are %d items when there should be 4.\n' % result
else:
print 'Drag & drop success.\n'
browser.quit()
autopy_driver.quit()
# Now imagine from this integration demo, you could use AutoPy with browser via
# WebDriver to do stuff like file download, HTTP authentication and other stuff
# like drag item from desktop into browser, that you could not do w/ WebDriver
# alone, or w/ executing shell commands and other external stuff. Now can do all
# with WebDriver APIs against 2+ WebDriver instances. | daluu/AutoPyDriverServer | sample-code/webdriver_integration_demo.py | Python | apache-2.0 | 1,719 | 0.007563 |
# encoding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
float_or_none,
parse_age_limit,
)
class TvigleIE(InfoExtractor):
IE_NAME = 'tvigle'
IE_DESC = 'Интернет-телевидение Tvigle.ru'
_VALID_URL = r'http://(?:www\.)?tvigle\.ru/(?:[^/]+/)+(?P<id>[^/]+)/$'
_TESTS = [
{
'url': 'http://www.tvigle.ru/video/sokrat/',
'md5': '36514aed3657d4f70b4b2cef8eb520cd',
'info_dict': {
'id': '1848932',
'display_id': 'sokrat',
'ext': 'flv',
'title': 'Сократ',
'description': 'md5:a05bd01be310074d5833efc6743be95e',
'duration': 6586,
'age_limit': 0,
},
},
{
'url': 'http://www.tvigle.ru/video/vladimir-vysotskii/vedushchii-teleprogrammy-60-minut-ssha-o-vladimire-vysotskom/',
'md5': 'd9012d7c7c598fe7a11d7fb46dc1f574',
'info_dict': {
'id': '5142516',
'ext': 'mp4',
'title': 'Ведущий телепрограммы «60 минут» (США) о Владимире Высоцком',
'description': 'md5:027f7dc872948f14c96d19b4178428a4',
'duration': 186.080,
'age_limit': 0,
},
},
]
def _real_extract(self, url):
display_id = self._match_id(url)
webpage = self._download_webpage(url, display_id)
video_id = self._html_search_regex(
r'<li class="video-preview current_playing" id="(\d+)">', webpage, 'video id')
video_data = self._download_json(
'http://cloud.tvigle.ru/api/play/video/%s/' % video_id, display_id)
item = video_data['playlist']['items'][0]
title = item['title']
description = item['description']
thumbnail = item['thumbnail']
duration = float_or_none(item.get('durationMilliseconds'), 1000)
age_limit = parse_age_limit(item.get('ageRestrictions'))
formats = []
for vcodec, fmts in item['videos'].items():
for quality, video_url in fmts.items():
formats.append({
'url': video_url,
'format_id': '%s-%s' % (vcodec, quality),
'vcodec': vcodec,
'height': int(quality[:-1]),
'filesize': item['video_files_size'][vcodec][quality],
})
self._sort_formats(formats)
return {
'id': video_id,
'display_id': display_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'duration': duration,
'age_limit': age_limit,
'formats': formats,
}
| 0x7678/youtube-dl | youtube_dl/extractor/tvigle.py | Python | unlicense | 2,889 | 0.001065 |
def count_moves(a, x, y):
character = a[x][y]
if character == ".":
count = 0
rows = len(a)
columns = len(a[x])
# Top Check
if ((x - 2) >= 0) and (a[x - 1][y] == "o") and (a[x - 2][y] == "o"):
count += 1
# Bottom Check
if ((x + 2) < rows) and (a[x + 1][y] == "o") and (a[x + 2][y] == "o"):
count += 1
# Left Check
if ((y - 2) >= 0) and (a[x][y - 1] == "o") and (a[x][y - 2] == "o"):
count += 1
# Right Check
if ((y + 2) < columns) and (a[x][y + 1] == "o") and (a[x][y + 2] == "o"):
count += 1
return count
else:
return 0
moves = 0
size = 7
board = [input() for _ in range(size)]
for cx in range(size):
for cy in range(size):
moves += count_moves(board, cx, cy)
print(moves)
| ehouarn-perret/EhouarnPerret.Python.Kattis | Trivial/Peg.py | Python | mit | 719 | 0.030598 |
from decimal import Decimal as D
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template.defaultfilters import striptags, truncatechars
from django.utils.translation import gettext_lazy as _
from paypalcheckoutsdk.core import LiveEnvironment, PayPalHttpClient, SandboxEnvironment
from paypalcheckoutsdk.orders import (
OrdersAuthorizeRequest, OrdersCaptureRequest, OrdersCreateRequest, OrdersGetRequest)
from paypalcheckoutsdk.payments import AuthorizationsCaptureRequest, AuthorizationsVoidRequest, CapturesRefundRequest
INTENT_AUTHORIZE = 'AUTHORIZE'
INTENT_CAPTURE = 'CAPTURE'
INTENT_REQUEST_MAPPING = {
INTENT_AUTHORIZE: AuthorizationsCaptureRequest,
INTENT_CAPTURE: OrdersCaptureRequest,
}
LANDING_PAGE_LOGIN = 'LOGIN'
LANDING_PAGE_BILLING = 'BILLING'
LANDING_PAGE_NO_PREFERENCE = 'NO_PREFERENCE'
USER_ACTION_CONTINUE = 'CONTINUE'
USER_ACTION_PAY_NOW = 'PAY_NOW'
buyer_pays_on_paypal = lambda: getattr(settings, 'PAYPAL_BUYER_PAYS_ON_PAYPAL', False)
def format_description(description):
return truncatechars(striptags(description), 127) if description else ''
def format_amount(amount):
return str(amount.quantize(D('0.01')))
def get_landing_page():
landing_page = getattr(settings, 'PAYPAL_LANDING_PAGE', LANDING_PAGE_NO_PREFERENCE)
if landing_page not in (LANDING_PAGE_LOGIN, LANDING_PAGE_BILLING, LANDING_PAGE_NO_PREFERENCE):
message = _("'%s' is not a valid landing page") % landing_page
raise ImproperlyConfigured(message)
return landing_page
class PaymentProcessor:
client = None
def __init__(self):
credentials = {
'client_id': settings.PAYPAL_CLIENT_ID,
'client_secret': settings.PAYPAL_CLIENT_SECRET,
}
if getattr(settings, 'PAYPAL_SANDBOX_MODE', True):
environment = SandboxEnvironment(**credentials)
else:
environment = LiveEnvironment(**credentials)
self.client = PayPalHttpClient(environment)
def build_order_create_request_body(
self, basket, currency, return_url, cancel_url, order_total,
address=None, shipping_charge=None, intent=None,
):
application_context = {
'return_url': return_url,
'cancel_url': cancel_url,
'landing_page': get_landing_page(),
'shipping_preference': 'SET_PROVIDED_ADDRESS' if address is not None else 'NO_SHIPPING', # TODO: ???
'user_action': 'PAY_NOW' if buyer_pays_on_paypal() else 'CONTINUE',
}
if getattr(settings, 'PAYPAL_BRAND_NAME', None) is not None:
application_context['brand_name'] = settings.PAYPAL_BRAND_NAME
breakdown = {
'item_total': {
'currency_code': currency,
'value': format_amount(basket.total_incl_tax_excl_discounts),
},
'discount': {
'currency_code': currency,
'value': format_amount(sum([
discount['discount']
for discount
in basket.offer_discounts + basket.voucher_discounts
], D(0))),
},
'shipping_discount': {
'currency_code': currency,
'value': format_amount(sum([
discount['discount']
for discount
in basket.shipping_discounts
], D(0))),
}
}
if shipping_charge is not None:
breakdown['shipping'] = {
'currency_code': currency,
'value': format_amount(shipping_charge),
}
purchase_unit = {
'amount': {
'currency_code': currency,
'value': format_amount(order_total),
'breakdown': breakdown,
}
}
items = []
for line in basket.all_lines():
product = line.product
item = {
'name': product.get_title(),
'description': format_description(product.description),
'sku': product.upc if product.upc else '',
'unit_amount': {
'currency_code': currency,
'value': format_amount(line.unit_price_incl_tax)
},
'quantity': line.quantity,
'category': 'PHYSICAL_GOODS' if product.is_shipping_required else 'DIGITAL_GOODS'
}
items.append(item)
purchase_unit['items'] = items
if address is not None:
purchase_unit['shipping'] = {
'name': {
'full_name': address.name
},
'address': {
'address_line_1': address.line1,
'address_line_2': address.line2,
'admin_area_2': address.line4,
'admin_area_1': address.state,
'postal_code': address.postcode,
'country_code': address.country.iso_3166_1_a2
}
}
body = {
'intent': intent,
'application_context': application_context,
'purchase_units': [purchase_unit]
}
return body
def build_refund_order_request_body(self, amount, currency):
return {
'amount': {
'value': format_amount(amount),
'currency_code': currency
}
}
def create_order(
self, basket, currency, return_url, cancel_url, order_total,
address=None, shipping_charge=None, intent=None, preferred_response='minimal',
):
request = OrdersCreateRequest()
request.prefer(f'return={preferred_response}')
request.request_body(self.build_order_create_request_body(
basket=basket,
currency=currency,
return_url=return_url,
cancel_url=cancel_url,
order_total=order_total,
intent=intent,
address=address,
shipping_charge=shipping_charge,
))
response = self.client.execute(request)
return response.result
def get_order(self, token):
request = OrdersGetRequest(token)
response = self.client.execute(request)
return response.result
def get_authorize_request_body(self):
return {}
def authorize_order(self, order_id, preferred_response='minimal'):
request = OrdersAuthorizeRequest(order_id)
request.prefer(f'return={preferred_response}')
request.request_body(self.get_authorize_request_body())
response = self.client.execute(request)
return response.result
def void_authorized_order(self, authorization_id):
request = AuthorizationsVoidRequest(authorization_id)
self.client.execute(request)
def refund_order(self, capture_id, amount, currency, preferred_response='minimal'):
request = CapturesRefundRequest(capture_id)
request.prefer(f'return={preferred_response}')
request.request_body(self.build_refund_order_request_body(amount, currency))
response = self.client.execute(request)
return response.result
def capture_order(self, token, intent, preferred_response='minimal'):
capture_request = INTENT_REQUEST_MAPPING[intent]
request = capture_request(token)
request.prefer(f'return={preferred_response}')
response = self.client.execute(request)
return response.result
| lpakula/django-oscar-paypal | paypal/express_checkout/gateway.py | Python | bsd-3-clause | 7,616 | 0.001576 |
# Copyright 2015 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.
# ==============================================================================
"""Connects all half, float and double tensors to CheckNumericsOp."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.util.tf_export import tf_export
@tf_export("verify_tensor_all_finite")
def verify_tensor_all_finite(t, msg, name=None):
"""Assert that the tensor does not contain any NaN's or Inf's.
Args:
t: Tensor to check.
msg: Message to log on failure.
name: A name for this operation (optional).
Returns:
Same tensor as `t`.
"""
with ops.name_scope(name, "VerifyFinite", [t]) as name:
t = ops.convert_to_tensor(t, name="t")
with ops.colocate_with(t):
verify_input = array_ops.check_numerics(t, message=msg)
out = control_flow_ops.with_dependencies([verify_input], t)
return out
@tf_export("add_check_numerics_ops")
def add_check_numerics_ops():
"""Connect a `check_numerics` to every floating point tensor.
`check_numerics` operations themselves are added for each `half`, `float`,
or `double` tensor in the graph. For all ops in the graph, the
`check_numerics` op for all of its (`half`, `float`, or `double`) inputs
is guaranteed to run before the `check_numerics` op on any of its outputs.
Note: This API is not compatible with the use of `tf.cond` or
`tf.while_loop`, and will raise a `ValueError` if you attempt to call it
in such a graph.
Returns:
A `group` op depending on all `check_numerics` ops added.
Raises:
ValueError: If the graph contains any numeric operations in a control flow
structure.
RuntimeError: If called with eager execution enabled.
@compatibility(eager)
Not compatible with eager execution. To check for `Inf`s and `NaN`s under
eager execution, call tfe.seterr(inf_or_nan='raise') once before executing
the checked operations.
@enc_compatibility
"""
if context.executing_eagerly():
raise RuntimeError(
"add_check_numerics_ops() is not compatible with eager execution. "
"To check for Inf's and NaN's under eager execution, call "
"tfe.seterr(inf_or_nan='raise') once before executing the "
"checked operations.")
check_op = []
# This code relies on the ordering of ops in get_operations().
# The producer of a tensor always comes before that tensor's consumer in
# this list. This is true because get_operations() returns ops in the order
# added, and an op can only be added after its inputs are added.
for op in ops.get_default_graph().get_operations():
for output in op.outputs:
if output.dtype in [dtypes.float16, dtypes.float32, dtypes.float64]:
if op._get_control_flow_context() is not None: # pylint: disable=protected-access
raise ValueError("`tf.add_check_numerics_ops() is not compatible "
"with TensorFlow control flow operations such as "
"`tf.cond()` or `tf.while_loop()`.")
message = op.name + ":" + str(output.value_index)
with ops.control_dependencies(check_op):
check_op = [array_ops.check_numerics(output, message=message)]
return control_flow_ops.group(*check_op)
| kobejean/tensorflow | tensorflow/python/ops/numerics.py | Python | apache-2.0 | 4,096 | 0.004395 |
#
#
# Copyright (C) 2012 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
"""Module for object related utils."""
#: Supported container types for serialization/de-serialization (must be a
#: tuple as it's used as a parameter for C{isinstance})
_SEQUENCE_TYPES = (list, tuple, set, frozenset)
class AutoSlots(type):
"""Meta base class for __slots__ definitions.
"""
def __new__(mcs, name, bases, attrs):
"""Called when a class should be created.
@param mcs: The meta class
@param name: Name of created class
@param bases: Base classes
@type attrs: dict
@param attrs: Class attributes
"""
assert "__slots__" not in attrs, \
"Class '%s' defines __slots__ when it should not" % name
attrs["__slots__"] = mcs._GetSlots(attrs)
return type.__new__(mcs, name, bases, attrs)
@classmethod
def _GetSlots(mcs, attrs):
"""Used to get the list of defined slots.
@param attrs: The attributes of the class
"""
raise NotImplementedError
class ValidatedSlots(object):
"""Sets and validates slots.
"""
__slots__ = []
def __init__(self, **kwargs):
"""Constructor for BaseOpCode.
The constructor takes only keyword arguments and will set
attributes on this object based on the passed arguments. As such,
it means that you should not pass arguments which are not in the
__slots__ attribute for this class.
"""
slots = self.GetAllSlots()
for (key, value) in kwargs.items():
if key not in slots:
raise TypeError("Object %s doesn't support the parameter '%s'" %
(self.__class__.__name__, key))
setattr(self, key, value)
@classmethod
def GetAllSlots(cls):
"""Compute the list of all declared slots for a class.
"""
slots = []
for parent in cls.__mro__:
slots.extend(getattr(parent, "__slots__", []))
return slots
def Validate(self):
"""Validates the slots.
This method must be implemented by the child classes.
"""
raise NotImplementedError
def ContainerToDicts(container):
"""Convert the elements of a container to standard Python types.
This method converts a container with elements to standard Python types. If
the input container is of the type C{dict}, only its values are touched.
Those values, as well as all elements of input sequences, must support a
C{ToDict} method returning a serialized version.
@type container: dict or sequence (see L{_SEQUENCE_TYPES})
"""
if isinstance(container, dict):
ret = dict([(k, v.ToDict()) for k, v in container.items()])
elif isinstance(container, _SEQUENCE_TYPES):
ret = [elem.ToDict() for elem in container]
else:
raise TypeError("Unknown container type '%s'" % type(container))
return ret
def ContainerFromDicts(source, c_type, e_type):
"""Convert a container from standard python types.
This method converts a container with standard Python types to objects. If
the container is a dict, we don't touch the keys, only the values.
@type source: None, dict or sequence (see L{_SEQUENCE_TYPES})
@param source: Input data
@type c_type: type class
@param c_type: Desired type for returned container
@type e_type: element type class
@param e_type: Item type for elements in returned container (must have a
C{FromDict} class method)
"""
if not isinstance(c_type, type):
raise TypeError("Container type '%s' is not a type" % type(c_type))
if source is None:
source = c_type()
if c_type is dict:
ret = dict([(k, e_type.FromDict(v)) for k, v in source.items()])
elif c_type in _SEQUENCE_TYPES:
ret = c_type(map(e_type.FromDict, source))
else:
raise TypeError("Unknown container type '%s'" % c_type)
return ret
| vladimir-ipatov/ganeti | lib/outils.py | Python | gpl-2.0 | 4,426 | 0.005874 |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
from measurements import media
from telemetry import test
class Media(test.Test):
"""Obtains media metrics for key user scenarios."""
test = media.Media
page_set = 'page_sets/tough_video_cases.json'
class MediaNetworkSimulation(test.Test):
"""Obtains media metrics under different network simulations."""
test = media.Media
enabled = not sys.platform.startswith('linux')
page_set = 'page_sets/media_cns_cases.json'
class MediaAndroid(test.Test):
"""Obtains media metrics for key user scenarios on Android."""
test = media.Media
tag = 'android'
page_set = 'page_sets/tough_video_cases.json'
# Exclude crowd* media files (50fps 2160p).
options = {
'page_filter_exclude': '.*crowd.*'
}
def CustomizeBrowserOptions(self, options):
# Needed to run media actions in JS in Android.
options.AppendExtraBrowserArgs(
'--disable-gesture-requirement-for-media-playback')
class MediaSourceExtensions(test.Test):
"""Obtains media metrics for key media source extensions functions."""
test = media.Media
enabled = not sys.platform.startswith('linux')
page_set = 'page_sets/mse_cases.json'
def CustomizeBrowserOptions(self, options):
# Needed to allow XHR requests to return stream objects.
options.AppendExtraBrowserArgs(
'--enable-experimental-web-platform-features')
| DirtyUnicorns/android_external_chromium-org | tools/perf/benchmarks/media.py | Python | bsd-3-clause | 1,514 | 0.015852 |
from numpy.linalg import norm
from numpy import zeros, array, any as npany
import new
from copy import copy
# local imports
from ..identity_quadratic import identity_quadratic as sq
from ..algorithms import FISTA
from ..objdoctemplates import objective_doc_templater
from ..doctemplates import (doc_template_user, doc_template_provider)
@objective_doc_templater()
class composite(object):
"""
A generic way to specify a problem in composite form.
"""
objective_template = r"""f(%(var)s)"""
objective_vars = {'var': r'\beta', 'shape':'p', 'offset':r'\alpha'}
def __init__(self, shape, offset=None,
quadratic=None, initial=None):
self.offset = offset
if offset is not None:
self.offset = array(offset)
if type(shape) == type(1):
self.shape = (shape,)
else:
self.shape = shape
if quadratic is not None:
self.quadratic = quadratic
else:
self.quadratic = sq(0,0,0,0)
if initial is None:
self.coefs = zeros(self.shape)
else:
self.coefs = initial.copy()
def latexify(self, var=None, idx=''):
template_dict = self.objective_vars.copy()
template_dict['idx'] = idx
if var is not None:
template_dict['var'] = var
if hasattr(self, 'offset') and self.offset is not None and npany(self.offset != 0):
template_dict['var'] = var + (r' - %(offset)s_{%(idx)s}' % template_dict)
obj = self.objective_template % template_dict
template_dict['obj'] = obj
if not self.quadratic.iszero:
return ' + '.join([obj, self.quadratic.latexify(var=var, idx=idx)])
return obj
def _repr_latex_(self):
return self.latexify('x')
def nonsmooth_objective(self, x, check_feasibility=False):
return self.quadratic.objective(x, 'func')
def smooth_objective(self, x, mode='both', check_feasibility=False):
'''
The smooth_objective and the quadratic_objective combined.
'''
raise NotImplementedError
def objective(self, x, check_feasibility=False):
return self.smooth_objective(x,mode='func', check_feasibility=check_feasibility) + self.nonsmooth_objective(x, check_feasibility=check_feasibility)
@doc_template_provider
def proximal_optimum(self, quadratic):
r"""
Returns
.. math::
\inf_{x \in \mathbb{R}^p} Q(x)
+ h(x)
where $p$ = ``x.shape[0]``, $Q(x)=$ `self.quadratic` and
.. math::
h(%(var)s) = %(ns_objective)s
"""
argmin = self.proximal(quadratic)
if self.quadratic is None:
return argmin, lipschitz * norm(x-argmin)**2 / 2. + self.nonsmooth_objective(argmin)
else:
return argmin, lipschitz * norm(x-argmin)**2 / 2. + self.nonsmooth_objective(argmin) + self.quadratic.objective(argmin, 'func')
def proximal_step(self, quadratic, prox_control=None):
"""
Compute the proximal optimization
prox_control: If not None, then a dictionary of parameters for the prox procedure
"""
# This seems like a null op -- if all proximals accept optional prox_control
if prox_control is None:
return self.proximal(quadratic)
else:
return self.proximal(quadratic, prox_control=prox_control)
def apply_offset(self, x):
"""
If self.offset is not None, return x-self.offset, else return x.
"""
if self.offset is not None:
return x - self.offset
return x
def set_quadratic(self, quadratic):
"""
Set the quadratic part of the composite.
"""
self._quadratic = quadratic
def get_quadratic(self):
"""
Get the quadratic part of the composite.
"""
if not hasattr(self, "_quadratic"):
self._quadratic = sq(None, None, None, None)
return self._quadratic
quadratic = property(get_quadratic, set_quadratic)
def smoothed(self, smoothing_quadratic):
'''
Add quadratic smoothing term
'''
conjugate_atom = copy(self.conjugate)
sq = smoothing_quadratic
if sq.coef in [None, 0]:
raise ValueError('quadratic term of smoothing_quadratic must be non 0')
total_q = sq
if conjugate_atom.quadratic is not None:
total_q = sq + conjugate_atom.quadratic
conjugate_atom.set_quadratic(total_q)
smoothed_atom = conjugate_atom.conjugate
return smoothed_atom
def solve(self, quadratic=None, return_optimum=False, **fit_args):
raise NotImplementedError('subclasses must implement their own solve methods')
class nonsmooth(composite):
"""
A composite subclass that explicitly returns 0
as smooth_objective.
"""
def smooth_objective(self, x, mode='both', check_feasibility=False):
if mode == 'both':
return 0., zeros(x.shape)
elif mode == 'func':
return 0.
elif mode == 'grad':
return zeros(x.shape)
raise ValueError("Mode not specified correctly")
def solve(self, quadratic=None, return_optimum=False, **fit_args):
if quadratic is None:
quadratic = sq(0,0,0,0)
self.coefs = self.proximal(quadratic)
if return_optimum:
return self.objective(self.coefs) + quadratic.objective(self.coefs, 'func'), self.coefs
else:
return self.coefs
class smooth(composite):
"""
A composite subclass that has 0 as
nonsmooth_objective and the proximal
is a null-op.
"""
objective_vars = composite.objective_vars.copy()
objective_vars['coef'] = 'C'
def get_lipschitz(self):
if hasattr(self, '_lipschitz'):
return self._lipschitz + self.quadratic.coef
return self.quadratic.coef
def set_lipschitz(self, value):
if value < 0:
raise ValueError('Lipschitz constant must be non-negative')
self._lipschitz = value
lipschitz = property(get_lipschitz, set_lipschitz)
def smooth_objective(self, x, mode='func', check_feasibility=False):
return self._smooth_objective(x, mode=mode, check_feasibility=check_feasibility)
def proximal(self, quadratic):
totalq = self.quadratic + quadratic
return -totalq.linear_term / totalq.coef
def solve(self, quadratic=None, return_optimum=False, **fit_args):
if quadratic is None:
quadratic = sq(0,0,0,0)
oldq, self.quadratic = self.quadratic, self.quadratic + quadratic
self.solver = FISTA(self)
self.solver.fit(**fit_args)
self.quadratic = oldq
if return_optimum:
return self.objective(self.coefs), self.coefs
else:
return self.coefs
class smooth_conjugate(smooth):
def __init__(self, atom, quadratic=None):
"""
Given an atom,
compute the conjugate of this atom plus
an identity_quadratic which will be
a smooth version of the conjugate of the atom.
should we have an argument "collapse" that makes a copy?
"""
# this holds a pointer to the original atom,
# but will be replaced later
self.atom = atom
if quadratic is None:
quadratic = sq(0,0,0,0)
self.smoothing_quadratic = quadratic
self.total_quadratic = self.atom.quadratic + self.smoothing_quadratic
if self.total_quadratic.coef in [0,None]:
raise ValueError('the atom must have non-zero quadratic term to compute ensure smooth conjugate')
self.shape = atom.shape
# A smooth conjugate is the conjugate of some $f$ with an identity quadratic added to it, or
# $$
# h(u) = \sup_x \left( u^Tx - \frac{\kappa}{2} \|x\|^2_2 - \beta^Tx-c-f(x) \right).
# $$
# Suppose we add a quadratic to $h$ to get
# $$
# \tilde{h}(u) = \frac{r}{2} \|u\|^2_2 + u^T\gamma + a + h(u)$$
# and take the conjugate again:
# $$
# \begin{aligned}
# g(v) &= \sup_{u} u^Tv - \tilde{h}(u) \\
# &= \sup_u u^Tv - \frac{r}{2} \|u\|^2_2 - u^T\gamma-a - h(u) \\
# &= \sup_u u^Tv - \frac{r}{2} \|u\|^2_2 - u^T\gamma-a - \sup_x \left( u^Tx - \frac{\kappa}{2} \|x\|^2_2 - \beta^Tx-c-f(x) \right)\\
# &= \sup_u u^Tv - \frac{r}{2} \|u\|^2_2 - u^T\gamma-a + \inf_x \left( \frac{\kappa}{2} \|x\|^2_2 +\beta^Tx + c +f(x) - u^Tx \right)\\
# &= \sup_u \inf_x u^Tv - \frac{r}{2} \|u\|^2_2 - u^T\gamma-a + \frac{\kappa}{2} \|x\|^2_2 + \beta^Tx + c +f(x) - u^Tx \\
# &= \inf_x \sup_u u^Tv - \frac{r}{2} \|u\|^2_2 - u^T\gamma-a + \frac{\kappa}{2} \|x\|^2_2 + \beta^Tx + c +f(x) - u^Tx \\
# &= \inf_x \sup_u \left(u^Tv - \frac{r}{2} \|u\|^2_2 - u^T\gamma- u^Tx\right)-a + \frac{\kappa}{2} \|x\|^2_2 + \beta^Tx + c +f(x) \\
# &= \inf_x \frac{1}{2r} \|x+\gamma-v\|^2_2 -a + \frac{\kappa}{2} \|x\|^2_2 + \beta^Tx + c +f(x) \\
# &= c-a + \frac{1}{2r} \|\gamma-v\|^2_2 - \sup_x \left((v/r)^Tx - \left(\frac{1}{r} + \kappa\right) \|x\|^2_2 - x^T(\beta+\gamma/r) - f(x) \right) \\
# \end{aligned}
# $$
# This says that for $r > 0$ the conjugate of a smooth conjugate with a quadratic added to it is a quadratic plus a modified smooth conjugate evaluated at $v/r$.
# What if $r=0$? Well,
# then
# $$
# \begin{aligned}
# g(v) &= \sup_{u} u^Tv - \tilde{h}(u) \\
# &= \sup_u u^Tv - u^T\gamma-a - h(u) \\
# &= \sup_u u^Tv - u^T\gamma-a - \sup_x \left( u^Tx - \frac{\kappa}{2} \|x\|^2_2 - \beta^Tx-c-f(x) \right)\\
# &= \sup_u u^Tv - u^T\gamma-a + \inf_x \left( \frac{\kappa}{2} \|x\|^2_2 +\beta^Tx + c +f(x) - u^Tx \right)\\
# &= \sup_u \inf_x u^Tv - u^T\gamma-a + \frac{\kappa}{2} \|x\|^2_2 + \beta^Tx + c +f(x) - u^Tx \\
# &= \inf_x \sup_u u^Tv - u^T\gamma-a + \frac{\kappa}{2} \|x\|^2_2 + \beta^Tx + c +f(x) - u^Tx \\
# &= \frac{\kappa}{2} \|v-\gamma\|^2_2 + \beta^T(v-\gamma) + c-a +f(v-\gamma) \\
# \end{aligned}
# $$
# where, in the last line we have used the fact that the $\sup$ over $u$ in the second to last line is infinite unless $x=v-\gamma$.
def get_conjugate(self):
if self.quadratic.iszero:
if self.smoothing_quadratic.iszero:
return self.atom
else:
atom = copy(self.atom)
atom.quadratic = atom.quadratic + self.smoothing_quadratic
return atom
else:
q = self.quadratic.collapsed()
if q.coef == 0:
newq = copy(atom.quadratic)
newq.constant_term -= q.constant_term
offset = -q.linear_term
if atom.offset is not None:
offset += atom.offset
atom = copy(atom)
atom.offset = offset
atom.quadratic=newq
return atom
if q.coef != 0:
r = q.coef
sq_ = self.smoothing_quadratic
newq = sq_ + q.conjugate
new_smooth = smooth_conjugate(self.atom, quadratic=newq)
output = smooth(self.atom.shape,
offset=None,
quadratic=sq(1./r, q.linear_term, 0, 0),
initial=None)
output.smoothed_atom = new_smooth
def smooth_objective(self, x, mode='func', check_feasibility=False):
# what if self.quadratic is later changed? hmm..
r = 1. / self.quadratic.coef
if mode == 'func':
v = self.smoothed_atom.smooth_objective(x/r, mode=mode,
check_feasibility=check_feasibility)
return self.smoothing_quadratic.objective(x, 'func') - v
elif mode == 'both':
v1, g1 = self.smoothed_atom.smooth_objective(x/r, mode=mode,
check_feasibility=check_feasibility)
v2, g2 = self.smoothing_quadratic.objective(x, mode=mode,
check_feasibility=check_feasibility)
return v2-v1, g2-g1/r
elif mode == 'grad':
g1 = self.smoothed_atom.smooth_objective(x/r, mode='grad',
check_feasibility=check_feasibility)
g2 = self.smoothing_quadratic.objective(x, mode='grad',
check_feasibility=check_feasibility)
return g2-g1/r
else:
raise ValueError("mode incorrectly specified")
output.smooth_objective = type(output.smooth_objective)(smooth_objective,
output,
smooth)
return output
conjugate = property(get_conjugate)
def __repr__(self):
return 'smooth_conjugate(%s,%s)' % (str(self.atom), str(self.quadratic))
def smooth_objective(self, x, mode='both', check_feasibility=False):
"""
Evaluate a smooth function and/or its gradient
if mode == 'both', return both function value and gradient
if mode == 'grad', return only the gradient
if mode == 'func', return only the function value
"""
q = self.smoothing_quadratic + sq(0,0,-x,0)
if mode == 'both':
optimal_value, argmin = self.atom.solve(quadratic=q, return_optimum=True)
objective = -optimal_value
# retain a reference
self.grad = argmin
return objective, self.grad
elif mode == 'grad':
argmin = self.atom.solve(quadratic=q)
# retain a reference
self.grad = argmin
return self.grad
elif mode == 'func':
optimal_value, argmin = self.atom.solve(quadratic=q, return_optimum=True)
objective = -optimal_value
# retain a reference
self.grad = argmin
return objective
else:
raise ValueError("mode incorrectly specified")
def proximal(self, proxq, prox_control=None):
raise ValueError('no proximal defined')
| klingebj/regreg | code/regreg/problems/composite.py | Python | bsd-3-clause | 14,743 | 0.005698 |
# -*- coding: utf-8 -*-
#
# Copyright 2014-2022 BigML
#
# 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.
"""Base class for evaluations' REST calls
https://bigml.com/api/evaluations
"""
try:
import simplejson as json
except ImportError:
import json
from bigml.api_handlers.resourcehandler import ResourceHandlerMixin
from bigml.api_handlers.resourcehandler import check_resource_type
from bigml.constants import SUPERVISED_PATHS, TIME_SERIES_PATH, EVALUATION_PATH
class EvaluationHandlerMixin(ResourceHandlerMixin):
"""This class is used by the BigML class as
a mixin that provides the REST calls models. It should not
be instantiated independently.
"""
def __init__(self):
"""Initializes the EvaluationHandler. This class is intended to be
used as a mixin on ResourceHandler, that inherits its
attributes and basic method from BigMLConnection, and must not be
instantiated independently.
"""
self.evaluation_url = self.url + EVALUATION_PATH
def create_evaluation(self, model, dataset,
args=None, wait_time=3, retries=10):
"""Creates a new evaluation.
"""
create_args = {}
if args is not None:
create_args.update(args)
model_types = SUPERVISED_PATHS[:]
model_types.append(TIME_SERIES_PATH)
origin_resources_checked = self.check_origins(
dataset, model, create_args, model_types=model_types,
wait_time=wait_time, retries=retries)
if origin_resources_checked:
body = json.dumps(create_args)
return self._create(self.evaluation_url, body)
return
def get_evaluation(self, evaluation, query_string=''):
"""Retrieves an evaluation.
The evaluation parameter should be a string containing the
evaluation id or the dict returned by create_evaluation.
As evaluation is an evolving object that is processed
until it reaches the FINISHED or FAULTY state, the function will
return a dict that encloses the evaluation values and state info
available at the time it is called.
"""
check_resource_type(evaluation, EVALUATION_PATH,
message="An evaluation id is needed.")
return self.get_resource(evaluation, query_string=query_string)
def list_evaluations(self, query_string=''):
"""Lists all your evaluations.
"""
return self._list(self.evaluation_url, query_string)
def update_evaluation(self, evaluation, changes):
"""Updates an evaluation.
"""
check_resource_type(evaluation, EVALUATION_PATH,
message="An evaluation id is needed.")
return self.update_resource(evaluation, changes)
def delete_evaluation(self, evaluation):
"""Deletes an evaluation.
"""
check_resource_type(evaluation, EVALUATION_PATH,
message="An evaluation id is needed.")
return self.delete_resource(evaluation)
| bigmlcom/python | bigml/api_handlers/evaluationhandler.py | Python | apache-2.0 | 3,626 | 0 |
# Copyright (c) 2015, Matt Layman
import gettext
import os
localedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'locale')
translate = gettext.translation('tappy', localedir, fallback=True)
_ = translate.gettext
| blakev/tappy | tap/i18n.py | Python | bsd-2-clause | 229 | 0 |
from .. import BASE_SCHEMA_URL, BASE_DATA_URL
from rdflib.namespace import Namespace
TRANS_NS = Namespace(BASE_SCHEMA_URL + '/translators/')
TRANS_DATA_NS = Namespace(BASE_DATA_URL + '/translators/')
DS_NS = Namespace(BASE_SCHEMA_URL + '/data_sources/')
DS_DATA_NS = Namespace(BASE_DATA_URL + '/data_sources/')
class DSMixin(object):
base_namespace = DS_NS
base_data_namespace = DS_DATA_NS
class DTMixin(object):
base_namespace = TRANS_NS
base_data_namespace = TRANS_DATA_NS
| openworm/PyOpenWorm | owmeta/data_trans/common_data.py | Python | mit | 496 | 0 |
# $Id$
# Copyright 2013 Matthew Wall
# See the file LICENSE.txt for your full rights.
#
# Thanks to Eddie De Pieri for the first Python implementation for WS-28xx.
# Eddie did the difficult work of decompiling HeavyWeather then converting
# and reverse engineering into a functional Python implementation. Eddie's
# work was based on reverse engineering of HeavyWeather 2800 v 1.54
#
# Thanks to Lucas Heijst for enumerating the console message types and for
# debugging the transceiver/console communication timing issues.
"""Classes and functions for interfacing with WS-28xx weather stations.
LaCrosse makes a number of stations in the 28xx series, including:
WS-2810, WS-2810U-IT
WS-2811, WS-2811SAL-IT, WS-2811BRN-IT, WS-2811OAK-IT
WS-2812, WS-2812U-IT
WS-2813
WS-2814, WS-2814U-IT
WS-2815, WS-2815U-IT
C86234
The station is also sold as the TFA Primus, TFA Opus, and TechnoLine.
HeavyWeather is the software provided by LaCrosse.
There are two versions of HeavyWeather for the WS-28xx series: 1.5.4 and 1.5.4b
Apparently there is a difference between TX59UN-1-IT and TX59U-IT models (this
identifier is printed on the thermo-hygro sensor).
HeavyWeather Version Firmware Version Thermo-Hygro Model
1.54 333 or 332 TX59UN-1-IT
1.54b 288, 262, 222 TX59U-IT
HeavyWeather provides the following weather station settings:
time display: 12|24 hour
temperature display: C|F
air pressure display: inhg|hpa
wind speed display: m/s|knots|bft|km/h|mph
rain display: mm|inch
recording interval: 1m
keep weather station in hi-speed communication mode: true/false
According to the HeavyWeatherPro User Manual (1.54, rev2), "Hi speed mode wears
down batteries on your display much faster, and similarly consumes more power
on the PC. We do not believe most users need to enable this setting. It was
provided at the request of users who prefer ultra-frequent uploads."
The HeavyWeatherPro 'CurrentWeather' view is updated as data arrive from the
console. The console sends current weather data approximately every 13
seconds.
Historical data are updated less frequently - every 2 hours in the default
HeavyWeatherPro configuration.
According to the User Manual, "The 2800 series weather station uses the
'original' wind chill calculation rather than the 2001 'North American'
formula because the original formula is international."
Apparently the station console determines when data will be sent, and, once
paired, the transceiver is always listening. The station console sends a
broadcast on the hour. If the transceiver responds, the station console may
continue to broadcast data, depending on the transceiver response and the
timing of the transceiver response.
According to the C86234 Operations Manual (Revision 7):
- Temperature and humidity data are sent to the console every 13 seconds.
- Wind data are sent to the temperature/humidity sensor every 17 seconds.
- Rain data are sent to the temperature/humidity sensor every 19 seconds.
- Air pressure is measured every 15 seconds.
Each tip of the rain bucket is 0.26 mm of rain.
The following information was obtained by logging messages from the ws28xx.py
driver in weewx and by capturing USB messages between Heavy Weather Pro for
ws2800 and the TFA Primus Weather Station via windows program USB sniffer
busdog64_v0.2.1.
Pairing
The transceiver must be paired with a console before it can receive data. Each
frame sent by the console includes the device identifier of the transceiver
with which it is paired.
Synchronizing
When the console and transceiver stop communicating, they can be synchronized
by one of the following methods:
- Push the SET button on the console
- Wait till the next full hour when the console sends a clock message
In each case a Request Time message is received by the transceiver from the
console. The 'Send Time to WS' message should be sent within ms (10 ms
typical). The transceiver should handle the 'Time SET' message then send a
'Time/Config written' message about 85 ms after the 'Send Time to WS' message.
When complete, the console and transceiver will have been synchronized.
Timing
Current Weather messages, History messages, getConfig/setConfig messages, and
setTime messages each have their own timing. Missed History messages - as a
result of bad timing - result in console and transceiver becoming out of synch.
Current Weather
The console periodically sends Current Weather messages, each with the latest
values from the sensors. The CommModeInterval determines how often the console
will send Current Weather messages.
History
The console records data periodically at an interval defined by the
HistoryInterval parameter. The factory default setting is 2 hours.
Each history record contains a timestamp. Timestamps use the time from the
console clock. The console can record up to 1797 history records.
Reading 1795 history records took about 110 minutes on a raspberry pi, for
an average of 3.6 seconds per history record.
Reading 1795 history records took 65 minutes on a synology ds209+ii, for
an average of 2.2 seconds per history record.
Reading 1750 history records took 19 minutes using HeavyWeatherPro on a
Windows 7 64-bit laptop.
Message Types
The first byte of a message determines the message type.
ID Type Length
01 ? 0x0f (15)
d0 SetRX 0x15 (21)
d1 SetTX 0x15 (21)
d5 SetFrame 0x111 (273)
d6 GetFrame 0x111 (273)
d7 SetState 0x15 (21)
d8 SetPreamblePattern 0x15 (21)
d9 Execute 0x0f (15)
dc ReadConfigFlash< 0x15 (21)
dd ReadConfigFlash> 0x15 (21)
de GetState 0x0a (10)
f0 WriteReg 0x05 (5)
In the following sections, some messages are decomposed using the following
structure:
start position in message buffer
hi-lo data starts on first (hi) or second (lo) nibble
chars data length in characters (nibbles)
rem remark
name variable
-------------------------------------------------------------------------------
1. 01 message (15 bytes)
000: 01 15 00 0b 08 58 3f 53 00 00 00 00 ff 15 0b (detected via USB sniffer)
000: 01 15 00 57 01 92 3f 53 00 00 00 00 ff 15 0a (detected via USB sniffer)
00: messageID
02-15: ??
-------------------------------------------------------------------------------
2. SetRX message (21 bytes)
000: d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
020: 00
00: messageID
01-20: 00
-------------------------------------------------------------------------------
3. SetTX message (21 bytes)
000: d1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
020: 00
00: messageID
01-20: 00
-------------------------------------------------------------------------------
4. SetFrame message (273 bytes)
Action:
00: rtGetHistory - Ask for History message
01: rtSetTime - Ask for Send Time to weather station message
02: rtSetConfig - Ask for Send Config to weather station message
03: rtGetConfig - Ask for Config message
05: rtGetCurrent - Ask for Current Weather message
c0: Send Time - Send Time to WS
40: Send Config - Send Config to WS
000: d5 00 09 DevID 00 CfgCS cIntThisAdr xx xx xx rtGetHistory
000: d5 00 09 DevID 01 CfgCS cIntThisAdr xx xx xx rtReqSetTime
000: d5 00 09 f0 f0 02 CfgCS cIntThisAdr xx xx xx rtReqFirstConfig
000: d5 00 09 DevID 02 CfgCS cIntThisAdr xx xx xx rtReqSetConfig
000: d5 00 09 DevID 03 CfgCS cIntThisAdr xx xx xx rtGetConfig
000: d5 00 09 DevID 05 CfgCS cIntThisAdr xx xx xx rtGetCurrent
000: d5 00 0c DevID c0 CfgCS [TimeData . .. .. .. Send Time
000: d5 00 30 DevID 40 CfgCS [ConfigData .. .. .. Send Config
All SetFrame messages:
00: messageID
01: 00
02: Message Length (starting with next byte)
03-04: DeviceID [DevID]
05: Action
06-07: Config checksum [CfgCS]
Additional bytes rtGetCurrent, rtGetHistory, rtSetTime messages:
08-09hi: ComInt [cINT] 1.5 bytes (high byte first)
09lo-11: ThisHistoryAddress [ThisAdr] 2.5 bytes (high byte first)
Additional bytes Send Time message:
08: seconds
09: minutes
10: hours
11hi: DayOfWeek
11lo: day_lo (low byte)
12hi: month_lo (low byte)
12lo: day_hi (high byte)
13hi: (year-2000)_lo (low byte)
13lo: month_hi (high byte)
14lo: (year-2000)_hi (high byte)
-------------------------------------------------------------------------------
5. GetFrame message
Response type:
20: WS SetTime / SetConfig - Data written
40: GetConfig
60: Current Weather
80: Actual / Outstanding History
a1: Request First-Time Config
a2: Request SetConfig
a3: Request SetTime
000: 00 00 06 DevID 20 64 CfgCS xx xx xx xx xx xx xx xx xx Time/Config written
000: 00 00 30 DevID 40 64 [ConfigData .. .. .. .. .. .. .. GetConfig
000: 00 00 d7 DevID 60 64 CfgCS [CurData .. .. .. .. .. .. Current Weather
000: 00 00 1e DevID 80 64 CfgCS 0LateAdr 0ThisAdr [HisData Outstanding History
000: 00 00 1e DevID 80 64 CfgCS 0LateAdr 0ThisAdr [HisData Actual History
000: 00 00 06 DevID a1 64 CfgCS xx xx xx xx xx xx xx xx xx Request FirstConfig
000: 00 00 06 DevID a2 64 CfgCS xx xx xx xx xx xx xx xx xx Request SetConfig
000: 00 00 06 DevID a3 64 CfgCS xx xx xx xx xx xx xx xx xx Request SetTime
ReadConfig example:
000: 01 2e 40 5f 36 53 02 00 00 00 00 81 00 04 10 00 82 00 04 20
020: 00 71 41 72 42 00 05 00 00 00 27 10 00 02 83 60 96 01 03 07
040: 21 04 01 00 00 00 CfgCS
WriteConfig example:
000: 01 2e 40 64 36 53 02 00 00 00 00 00 10 04 00 81 00 20 04 00
020: 82 41 71 42 72 00 00 05 00 00 00 10 27 01 96 60 83 02 01 04
040: 21 07 03 10 00 00 CfgCS
00: messageID
01: 00
02: Message Length (starting with next byte)
03-04: DeviceID [devID]
05hi: responseType
06: Quality (in steps of 5)
Additional byte GetFrame messages except Request SetConfig and Request SetTime:
05lo: BatteryStat 8=WS bat low; 4=TMP bat low; 2=RAIN bat low; 1=WIND bat low
Additional byte Request SetConfig and Request SetTime:
05lo: RequestID
Additional bytes all GetFrame messages except ReadConfig and WriteConfig
07-08: Config checksum [CfgCS]
Additional bytes Outstanding History:
09lo-11: LatestHistoryAddress [LateAdr] 2.5 bytes (Latest to sent)
12lo-14: ThisHistoryAddress [ThisAdr] 2.5 bytes (Outstanding)
Additional bytes Actual History:
09lo-11: LatestHistoryAddress [ThisAdr] 2.5 bytes (LatestHistoryAddress is the)
12lo-14: ThisHistoryAddress [ThisAdr] 2.5 bytes (same as ThisHistoryAddress)
Additional bytes ReadConfig and WriteConfig
43-45: ResetMinMaxFlags (Output only; not included in checksum calculation)
46-47: Config checksum [CfgCS] (CheckSum = sum of bytes (00-42) + 7)
-------------------------------------------------------------------------------
6. SetState message
000: d7 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00: messageID
01-14: 00
-------------------------------------------------------------------------------
7. SetPreamblePattern message
000: d8 aa 00 00 00 00 00 00 00 00 00 00 00 00 00
00: messageID
01: ??
02-14: 00
-------------------------------------------------------------------------------
8. Execute message
000: d9 05 00 00 00 00 00 00 00 00 00 00 00 00 00
00: messageID
01: ??
02-14: 00
-------------------------------------------------------------------------------
9. ReadConfigFlash in - receive data
000: dc 0a 01 f5 00 01 78 a0 01 02 0a 0c 0c 01 2e ff ff ff ff ff - freq correction
000: dc 0a 01 f9 01 02 0a 0c 0c 01 2e ff ff ff ff ff ff ff ff ff - transceiver data
00: messageID
01: length
02-03: address
Additional bytes frequency correction
05lo-07hi: frequency correction
Additional bytes transceiver data
05-10: serial number
09-10: DeviceID [devID]
-------------------------------------------------------------------------------
10. ReadConfigFlash out - ask for data
000: dd 0a 01 f5 cc cc cc cc cc cc cc cc cc cc cc - Ask for freq correction
000: dd 0a 01 f9 cc cc cc cc cc cc cc cc cc cc cc - Ask for transceiver data
00: messageID
01: length
02-03: address
04-14: cc
-------------------------------------------------------------------------------
11. GetState message
000: de 14 00 00 00 00 (between SetPreamblePattern and first de16 message)
000: de 15 00 00 00 00 Idle message
000: de 16 00 00 00 00 Normal message
000: de 0b 00 00 00 00 (detected via USB sniffer)
00: messageID
01: stateID
02-05: 00
-------------------------------------------------------------------------------
12. Writereg message
000: f0 08 01 00 00 - AX5051RegisterNames.IFMODE
000: f0 10 01 41 00 - AX5051RegisterNames.MODULATION
000: f0 11 01 07 00 - AX5051RegisterNames.ENCODING
...
000: f0 7b 01 88 00 - AX5051RegisterNames.TXRATEMID
000: f0 7c 01 23 00 - AX5051RegisterNames.TXRATELO
000: f0 7d 01 35 00 - AX5051RegisterNames.TXDRIVER
00: messageID
01: register address
02: 01
03: AX5051RegisterName
04: 00
-------------------------------------------------------------------------------
13. Current Weather message
start hi-lo chars rem name
0 hi 4 DevID
2 hi 2 Action
3 hi 2 Quality
4 hi 4 DeviceCS
6 hi 4 6 _AlarmRingingFlags
8 hi 1 _WeatherTendency
8 lo 1 _WeatherState
9 hi 1 not used
9 lo 10 _TempIndoorMinMax._Max._Time
14 lo 10 _TempIndoorMinMax._Min._Time
19 lo 5 _TempIndoorMinMax._Max._Value
22 hi 5 _TempIndoorMinMax._Min._Value
24 lo 5 _TempIndoor (C)
27 lo 10 _TempOutdoorMinMax._Max._Time
32 lo 10 _TempOutdoorMinMax._Min._Time
37 lo 5 _TempOutdoorMinMax._Max._Value
40 hi 5 _TempOutdoorMinMax._Min._Value
42 lo 5 _TempOutdoor (C)
45 hi 1 not used
45 lo 10 1 _WindchillMinMax._Max._Time
50 lo 10 2 _WindchillMinMax._Min._Time
55 lo 5 1 _WindchillMinMax._Max._Value
57 hi 5 1 _WindchillMinMax._Min._Value
60 lo 6 _Windchill (C)
63 hi 1 not used
63 lo 10 _DewpointMinMax._Max._Time
68 lo 10 _DewpointMinMax._Min._Time
73 lo 5 _DewpointMinMax._Max._Value
76 hi 5 _DewpointMinMax._Min._Value
78 lo 5 _Dewpoint (C)
81 hi 10 _HumidityIndoorMinMax._Max._Time
86 hi 10 _HumidityIndoorMinMax._Min._Time
91 hi 2 _HumidityIndoorMinMax._Max._Value
92 hi 2 _HumidityIndoorMinMax._Min._Value
93 hi 2 _HumidityIndoor (%)
94 hi 10 _HumidityOutdoorMinMax._Max._Time
99 hi 10 _HumidityOutdoorMinMax._Min._Time
104 hi 2 _HumidityOutdoorMinMax._Max._Value
105 hi 2 _HumidityOutdoorMinMax._Min._Value
106 hi 2 _HumidityOutdoor (%)
107 hi 10 3 _RainLastMonthMax._Time
112 hi 6 3 _RainLastMonthMax._Max._Value
115 hi 6 _RainLastMonth (mm)
118 hi 10 3 _RainLastWeekMax._Time
123 hi 6 3 _RainLastWeekMax._Max._Value
126 hi 6 _RainLastWeek (mm)
129 hi 10 _Rain24HMax._Time
134 hi 6 _Rain24HMax._Max._Value
137 hi 6 _Rain24H (mm)
140 hi 10 _Rain24HMax._Time
145 hi 6 _Rain24HMax._Max._Value
148 hi 6 _Rain24H (mm)
151 hi 1 not used
152 lo 10 _LastRainReset
158 lo 7 _RainTotal (mm)
160 hi 1 _WindDirection5
160 lo 1 _WindDirection4
161 hi 1 _WindDirection3
161 lo 1 _WindDirection2
162 hi 1 _WindDirection1
162 lo 1 _WindDirection (0-15)
163 hi 18 unknown data
172 hi 6 _WindSpeed (km/h)
175 hi 1 _GustDirection5
175 lo 1 _GustDirection4
176 hi 1 _GustDirection3
176 lo 1 _GustDirection2
177 hi 1 _GustDirection1
177 lo 1 _GustDirection (0-15)
178 hi 2 not used
179 hi 10 _GustMax._Max._Time
184 hi 6 _GustMax._Max._Value
187 hi 6 _Gust (km/h)
190 hi 10 4 _PressureRelative_MinMax._Max/Min._Time
195 hi 5 5 _PressureRelative_inHgMinMax._Max._Value
197 lo 5 5 _PressureRelative_hPaMinMax._Max._Value
200 hi 5 _PressureRelative_inHgMinMax._Max._Value
202 lo 5 _PressureRelative_hPaMinMax._Max._Value
205 hi 5 _PressureRelative_inHgMinMax._Min._Value
207 lo 5 _PressureRelative_hPaMinMax._Min._Value
210 hi 5 _PressureRelative_inHg
212 lo 5 _PressureRelative_hPa
214 lo 430 end
Remarks
1 since factory reset
2 since software reset
3 not used?
4 should be: _PressureRelative_MinMax._Max._Time
5 should be: _PressureRelative_MinMax._Min._Time
6 _AlarmRingingFlags (values in hex)
80 00 = Hi Al Gust
40 00 = Al WindDir
20 00 = One or more WindDirs set
10 00 = Hi Al Rain24H
08 00 = Hi Al Outdoor Humidity
04 00 = Lo Al Outdoor Humidity
02 00 = Hi Al Indoor Humidity
01 00 = Lo Al Indoor Humidity
00 80 = Hi Al Outdoor Temp
00 40 = Lo Al Outdoor Temp
00 20 = Hi Al Indoor Temp
00 10 = Lo Al Indoor Temp
00 08 = Hi Al Pressure
00 04 = Lo Al Pressure
00 02 = not used
00 01 = not used
-------------------------------------------------------------------------------
14. History Message
start hi-lo chars rem name
0 hi 4 DevID
2 hi 2 Action
3 hi 2 Quality (%)
4 hi 4 DeviceCS
6 hi 6 LatestAddress
9 hi 6 ThisAddress
12 hi 1 not used
12 lo 3 Gust (m/s)
14 hi 1 WindDirection (0-15, also GustDirection)
14 lo 3 WindSpeed (m/s)
16 hi 3 RainCounterRaw (total in period in 0.1 inch)
17 lo 2 HumidityOutdoor (%)
18 lo 2 HumidityIndoor (%)
19 lo 5 PressureRelative (hPa)
22 hi 3 TempOutdoor (C)
23 lo 3 TempIndoor (C)
25 hi 10 Time
29 lo 60 end
-------------------------------------------------------------------------------
15. Set Config Message
start hi-lo chars rem name
0 hi 4 DevID
2 hi 2 Action
3 hi 2 Quality
4 hi 1 1 _WindspeedFormat
4 lo 0,25 2 _RainFormat
4 lo 0,25 3 _PressureFormat
4 lo 0,25 4 _TemperatureFormat
4 lo 0,25 5 _ClockMode
5 hi 1 _WeatherThreshold
5 lo 1 _StormThreshold
6 hi 1 _LowBatFlags
6 lo 1 6 _LCDContrast
7 hi 4 7 _WindDirAlarmFlags (reverse group 1)
9 hi 4 8 _OtherAlarmFlags (reverse group 1)
11 hi 10 _TempIndoorMinMax._Min._Value (reverse group 2)
_TempIndoorMinMax._Max._Value (reverse group 2)
16 hi 10 _TempOutdoorMinMax._Min._Value (reverse group 3)
_TempOutdoorMinMax._Max._Value (reverse group 3)
21 hi 2 _HumidityIndoorMinMax._Min._Value
22 hi 2 _HumidityIndoorMinMax._Max._Value
23 hi 2 _HumidityOutdoorMinMax._Min._Value
24 hi 2 _HumidityOutdoorMinMax._Max._Value
25 hi 1 not used
25 lo 7 _Rain24HMax._Max._Value (reverse bytes)
29 hi 2 _HistoryInterval
30 hi 1 not used
30 lo 5 _GustMax._Max._Value (reverse bytes)
33 hi 10 _PressureRelative_hPaMinMax._Min._Value (rev grp4)
_PressureRelative_inHgMinMax._Min._Value(rev grp4)
38 hi 10 _PressureRelative_hPaMinMax._Max._Value (rev grp5)
_PressureRelative_inHgMinMax._Max._Value(rev grp5)
43 hi 6 9 _ResetMinMaxFlags
46 hi 4 10 _InBufCS
47 lo 96 end
Remarks
1 0=m/s 1=knots 2=bft 3=km/h 4=mph
2 0=mm 1=inch
3 0=inHg 2=hPa
4 0=F 1=C
5 0=24h 1=12h
6 values 0-7 => LCD contrast 1-8
7 WindDir Alarms (not-reversed values in hex)
80 00 = NNW
40 00 = NW
20 00 = WNW
10 00 = W
08 00 = WSW
04 00 = SW
02 00 = SSW
01 00 = S
00 80 = SSE
00 40 = SE
00 20 = ESE
00 10 = E
00 08 = ENE
00 04 = NE
00 02 = NNE
00 01 = N
8 Other Alarms (not-reversed values in hex)
80 00 = Hi Al Gust
40 00 = Al WindDir
20 00 = One or more WindDirs set
10 00 = Hi Al Rain24H
08 00 = Hi Al Outdoor Humidity
04 00 = Lo Al Outdoor Humidity
02 00 = Hi Al Indoor Humidity
01 00 = Lo Al Indoor Humidity
00 80 = Hi Al Outdoor Temp
00 40 = Lo Al Outdoor Temp
00 20 = Hi Al Indoor Temp
00 10 = Lo Al Indoor Temp
00 08 = Hi Al Pressure
00 04 = Lo Al Pressure
00 02 = not used
00 01 = not used
9 ResetMinMaxFlags (not-reversed values in hex)
"Output only; not included in checksum calc"
80 00 00 = Reset DewpointMax
40 00 00 = Reset DewpointMin
20 00 00 = not used
10 00 00 = Reset WindchillMin*
"*Reset dateTime only; Min._Value is preserved"
08 00 00 = Reset TempOutMax
04 00 00 = Reset TempOutMin
02 00 00 = Reset TempInMax
01 00 00 = Reset TempInMin
00 80 00 = Reset Gust
00 40 00 = not used
00 20 00 = not used
00 10 00 = not used
00 08 00 = Reset HumOutMax
00 04 00 = Reset HumOutMin
00 02 00 = Reset HumInMax
00 01 00 = Reset HumInMin
00 00 80 = not used
00 00 40 = Reset Rain Total
00 00 20 = Reset last month?
00 00 10 = Reset lastweek?
00 00 08 = Reset Rain24H
00 00 04 = Reset Rain1H
00 00 02 = Reset PresRelMax
00 00 01 = Reset PresRelMin
10 Checksum = sum bytes (0-42) + 7
-------------------------------------------------------------------------------
16. Get Config Message
start hi-lo chars rem name
0 hi 4 DevID
2 hi 2 Action
3 hi 2 Quality
4 hi 1 1 _WindspeedFormat
4 lo 0,25 2 _RainFormat
4 lo 0,25 3 _PressureFormat
4 lo 0,25 4 _TemperatureFormat
4 lo 0,25 5 _ClockMode
5 hi 1 _WeatherThreshold
5 lo 1 _StormThreshold
6 hi 1 _LowBatFlags
6 lo 1 6 _LCDContrast
7 hi 4 7 _WindDirAlarmFlags
9 hi 4 8 _OtherAlarmFlags
11 hi 5 _TempIndoorMinMax._Min._Value
13 lo 5 _TempIndoorMinMax._Max._Value
16 hi 5 _TempOutdoorMinMax._Min._Value
18 lo 5 _TempOutdoorMinMax._Max._Value
21 hi 2 _HumidityIndoorMinMax._Max._Value
22 hi 2 _HumidityIndoorMinMax._Min._Value
23 hi 2 _HumidityOutdoorMinMax._Max._Value
24 hi 2 _HumidityOutdoorMinMax._Min._Value
25 hi 1 not used
25 lo 7 _Rain24HMax._Max._Value
29 hi 2 _HistoryInterval
30 hi 5 _GustMax._Max._Value
32 lo 1 not used
33 hi 5 _PressureRelative_hPaMinMax._Min._Value
35 lo 5 _PressureRelative_inHgMinMax._Min._Value
38 hi 5 _PressureRelative_hPaMinMax._Max._Value
40 lo 5 _PressureRelative_inHgMinMax._Max._Value
43 hi 6 9 _ResetMinMaxFlags
46 hi 4 10 _InBufCS
47 lo 96 end
Remarks
1 0=m/s 1=knots 2=bft 3=km/h 4=mph
2 0=mm 1=inch
3 0=inHg 2=hPa
4 0=F 1=C
5 0=24h 1=12h
6 values 0-7 => LCD contrast 1-8
7 WindDir Alarms (values in hex)
80 00 = NNW
40 00 = NW
20 00 = WNW
10 00 = W
08 00 = WSW
04 00 = SW
02 00 = SSW
01 00 = S
00 80 = SSE
00 40 = SE
00 20 = ESE
00 10 = E
00 08 = ENE
00 04 = NE
00 02 = NNE
00 01 = N
8 Other Alarms (values in hex)
80 00 = Hi Al Gust
40 00 = Al WindDir
20 00 = One or more WindDirs set
10 00 = Hi Al Rain24H
08 00 = Hi Al Outdoor Humidity
04 00 = Lo Al Outdoor Humidity
02 00 = Hi Al Indoor Humidity
01 00 = Lo Al Indoor Humidity
00 80 = Hi Al Outdoor Temp
00 40 = Lo Al Outdoor Temp
00 20 = Hi Al Indoor Temp
00 10 = Lo Al Indoor Temp
00 08 = Hi Al Pressure
00 04 = Lo Al Pressure
00 02 = not used
00 01 = not used
9 ResetMinMaxFlags (values in hex)
"Output only; input = 00 00 00"
10 Checksum = sum bytes (0-42) + 7
-------------------------------------------------------------------------------
Examples of messages
readCurrentWeather
Cur 000: 01 2e 60 5f 05 1b 00 00 12 01 30 62 21 54 41 30 62 40 75 36
Cur 020: 59 00 60 70 06 35 00 01 30 62 31 61 21 30 62 30 55 95 92 00
Cur 040: 53 10 05 37 00 01 30 62 01 90 81 30 62 40 90 66 38 00 49 00
Cur 060: 05 37 00 01 30 62 21 53 01 30 62 22 31 75 51 11 50 40 05 13
Cur 080: 80 13 06 22 21 40 13 06 23 19 37 67 52 59 13 06 23 06 09 13
Cur 100: 06 23 16 19 91 65 86 00 00 00 00 00 00 00 00 00 00 00 00 00
Cur 120: 00 00 00 00 00 00 00 00 00 13 06 23 09 59 00 06 19 00 00 51
Cur 140: 13 06 22 20 43 00 01 54 00 00 00 01 30 62 21 51 00 00 38 70
Cur 160: a7 cc 7b 50 09 01 01 00 00 00 00 00 00 fc 00 a7 cc 7b 14 13
Cur 180: 06 23 14 06 0e a0 00 01 b0 00 13 06 23 06 34 03 00 91 01 92
Cur 200: 03 00 91 01 92 02 97 41 00 74 03 00 91 01 92
WeatherState: Sunny(Good) WeatherTendency: Rising(Up) AlarmRingingFlags: 0000
TempIndoor 23.500 Min:20.700 2013-06-24 07:53 Max:25.900 2013-06-22 15:44
HumidityIndoor 59.000 Min:52.000 2013-06-23 19:37 Max:67.000 2013-06-22 21:40
TempOutdoor 13.700 Min:13.100 2013-06-23 05:59 Max:19.200 2013-06-23 16:12
HumidityOutdoor 86.000 Min:65.000 2013-06-23 16:19 Max:91.000 2013-06-23 06:09
Windchill 13.700 Min: 9.000 2013-06-24 09:06 Max:23.800 2013-06-20 19:08
Dewpoint 11.380 Min:10.400 2013-06-22 23:17 Max:15.111 2013-06-22 15:30
WindSpeed 2.520
Gust 4.320 Max:37.440 2013-06-23 14:06
WindDirection WSW GustDirection WSW
WindDirection1 SSE GustDirection1 SSE
WindDirection2 W GustDirection2 W
WindDirection3 W GustDirection3 W
WindDirection4 SSE GustDirection4 SSE
WindDirection5 SW GustDirection5 SW
RainLastMonth 0.000 Max: 0.000 1900-01-01 00:00
RainLastWeek 0.000 Max: 0.000 1900-01-01 00:00
Rain24H 0.510 Max: 6.190 2013-06-23 09:59
Rain1H 0.000 Max: 1.540 2013-06-22 20:43
RainTotal 3.870 LastRainReset 2013-06-22 15:10
PresRelhPa 1019.200 Min:1007.400 2013-06-23 06:34 Max:1019.200 2013-06-23 06:34
PresRel_inHg 30.090 Min: 29.740 2013-06-23 06:34 Max: 30.090 2013-06-23 06:34
Bytes with unknown meaning at 157-165: 50 09 01 01 00 00 00 00 00
-------------------------------------------------------------------------------
readHistory
His 000: 01 2e 80 5f 05 1b 00 7b 32 00 7b 32 00 0c 70 0a 00 08 65 91
His 020: 01 92 53 76 35 13 06 24 09 10
Time 2013-06-24 09:10:00
TempIndoor= 23.5
HumidityIndoor= 59
TempOutdoor= 13.7
HumidityOutdoor= 86
PressureRelative= 1019.2
RainCounterRaw= 0.0
WindDirection= SSE
WindSpeed= 1.0
Gust= 1.2
-------------------------------------------------------------------------------
readConfig
In 000: 01 2e 40 5f 36 53 02 00 00 00 00 81 00 04 10 00 82 00 04 20
In 020: 00 71 41 72 42 00 05 00 00 00 27 10 00 02 83 60 96 01 03 07
In 040: 21 04 01 00 00 00 05 1b
-------------------------------------------------------------------------------
writeConfig
Out 000: 01 2e 40 64 36 53 02 00 00 00 00 00 10 04 00 81 00 20 04 00
Out 020: 82 41 71 42 72 00 00 05 00 00 00 10 27 01 96 60 83 02 01 04
Out 040: 21 07 03 10 00 00 05 1b
OutBufCS= 051b
ClockMode= 0
TemperatureFormat= 1
PressureFormat= 1
RainFormat= 0
WindspeedFormat= 3
WeatherThreshold= 3
StormThreshold= 5
LCDContrast= 2
LowBatFlags= 0
WindDirAlarmFlags= 0000
OtherAlarmFlags= 0000
HistoryInterval= 0
TempIndoor_Min= 1.0
TempIndoor_Max= 41.0
TempOutdoor_Min= 2.0
TempOutdoor_Max= 42.0
HumidityIndoor_Min= 41
HumidityIndoor_Max= 71
HumidityOutdoor_Min= 42
HumidityOutdoor_Max= 72
Rain24HMax= 50.0
GustMax= 100.0
PressureRel_hPa_Min= 960.1
PressureRel_inHg_Min= 28.36
PressureRel_hPa_Max= 1040.1
PressureRel_inHg_Max= 30.72
ResetMinMaxFlags= 100000 (Output only; Input always 00 00 00)
-------------------------------------------------------------------------------
class EHistoryInterval:
Constant Value Message received at
hi01Min = 0 00:00, 00:01, 00:02, 00:03 ... 23:59
hi05Min = 1 00:00, 00:05, 00:10, 00:15 ... 23:55
hi10Min = 2 00:00, 00:10, 00:20, 00:30 ... 23:50
hi15Min = 3 00:00, 00:15, 00:30, 00:45 ... 23:45
hi20Min = 4 00:00, 00:20, 00:40, 01:00 ... 23:40
hi30Min = 5 00:00, 00:30, 01:00, 01:30 ... 23:30
hi60Min = 6 00:00, 01:00, 02:00, 03:00 ... 23:00
hi02Std = 7 00:00, 02:00, 04:00, 06:00 ... 22:00
hi04Std = 8 00:00, 04:00, 08:00, 12:00 ... 20:00
hi06Std = 9 00:00, 06:00, 12:00, 18:00
hi08Std = 0xA 00:00, 08:00, 16:00
hi12Std = 0xB 00:00, 12:00
hi24Std = 0xC 00:00
-------------------------------------------------------------------------------
WS SetTime - Send time to WS
Time 000: 01 2e c0 05 1b 19 14 12 40 62 30 01
time sent: 2013-06-24 12:14:19
-------------------------------------------------------------------------------
ReadConfigFlash data
Ask for frequency correction
rcfo 000: dd 0a 01 f5 cc cc cc cc cc cc cc cc cc cc cc
readConfigFlash frequency correction
rcfi 000: dc 0a 01 f5 00 01 78 a0 01 02 0a 0c 0c 01 2e ff ff ff ff ff
frequency correction: 96416 (0x178a0)
adjusted frequency: 910574957 (3646456d)
Ask for transceiver data
rcfo 000: dd 0a 01 f9 cc cc cc cc cc cc cc cc cc cc cc
readConfigFlash serial number and DevID
rcfi 000: dc 0a 01 f9 01 02 0a 0c 0c 01 2e ff ff ff ff ff ff ff ff ff
transceiver ID: 302 (0x012e)
transceiver serial: 01021012120146
Program Logic
The RF communication thread uses the following logic to communicate with the
weather station console:
Step 1. Perform in a while loop getState commands until state 0xde16
is received.
Step 2. Perform a getFrame command to read the message data.
Step 3. Handle the contents of the message. The type of message depends on
the response type:
Response type (hex):
20: WS SetTime / SetConfig - Data written
confirmation the setTime/setConfig setFrame message has been received
by the console
40: GetConfig
save the contents of the configuration for later use (i.e. a setConfig
message with one ore more parameters changed)
60: Current Weather
handle the weather data of the current weather message
80: Actual / Outstanding History
ignore the data of the actual history record when there is no data gap;
handle the data of a (one) requested history record (note: in step 4 we
can decide to request another history record).
a1: Request First-Time Config
prepare a setFrame first time message
a2: Request SetConfig
prepare a setFrame setConfig message
a3: Request SetTime
prepare a setFrame setTime message
Step 4. When you didn't receive the message in step 3 you asked for (see
step 5 how to request a certain type of message), decide if you want
to ignore or handle the received message. Then go to step 5 to
request for a certain type of message unless the received message
has response type a1, a2 or a3, then prepare first the setFrame
message the wireless console asked for.
Step 5. Decide what kind of message you want to receive next time. The
request is done via a setFrame message (see step 6). It is
not guaranteed that you will receive that kind of message the next
time but setting the proper timing parameters of firstSleep and
nextSleep increase the chance you will get the requested type of
message.
Step 6. The action parameter in the setFrame message sets the type of the
next to receive message.
Action (hex):
00: rtGetHistory - Ask for History message
setSleep(0.300,0.010)
01: rtSetTime - Ask for Send Time to weather station message
setSleep(0.085,0.005)
02: rtSetConfig - Ask for Send Config to weather station message
setSleep(0.300,0.010)
03: rtGetConfig - Ask for Config message
setSleep(0.400,0.400)
05: rtGetCurrent - Ask for Current Weather message
setSleep(0.300,0.010)
c0: Send Time - Send Time to WS
setSleep(0.085,0.005)
40: Send Config - Send Config to WS
setSleep(0.085,0.005)
Note: after the Request First-Time Config message (response type = 0xa1)
perform a rtGetConfig with setSleep(0.085,0.005)
Step 7. Perform a setTX command
Step 8. Go to step 1 to wait for state 0xde16 again.
"""
# TODO: how often is currdat.lst modified with/without hi-speed mode?
# TODO: thread locking around observation data
# TODO: eliminate polling, make MainThread get data as soon as RFThread updates
# TODO: get rid of Length/Buffer construct, replace with a Buffer class or obj
# FIXME: the history retrieval assumes a constant archive interval across all
# history records. this means anything that modifies the archive
# interval should clear the history.
from datetime import datetime
import StringIO
import sys
import syslog
import threading
import time
import traceback
import usb
import weewx.drivers
import weewx.wxformulas
import weeutil.weeutil
DRIVER_NAME = 'WS28xx'
DRIVER_VERSION = '0.33'
def loader(config_dict, engine):
return WS28xxDriver(**config_dict[DRIVER_NAME])
def configurator_loader(config_dict):
return WS28xxConfigurator()
def confeditor_loader():
return WS28xxConfEditor()
# flags for enabling/disabling debug verbosity
DEBUG_COMM = 0
DEBUG_CONFIG_DATA = 0
DEBUG_WEATHER_DATA = 0
DEBUG_HISTORY_DATA = 0
DEBUG_DUMP_FORMAT = 'auto'
def logmsg(dst, msg):
syslog.syslog(dst, 'ws28xx: %s: %s' %
(threading.currentThread().getName(), msg))
def logdbg(msg):
logmsg(syslog.LOG_DEBUG, msg)
def loginf(msg):
logmsg(syslog.LOG_INFO, msg)
def logcrt(msg):
logmsg(syslog.LOG_CRIT, msg)
def logerr(msg):
logmsg(syslog.LOG_ERR, msg)
def log_traceback(dst=syslog.LOG_INFO, prefix='**** '):
sfd = StringIO.StringIO()
traceback.print_exc(file=sfd)
sfd.seek(0)
for line in sfd:
logmsg(dst, prefix + line)
del sfd
def log_frame(n, buf):
logdbg('frame length is %d' % n)
strbuf = ''
for i in xrange(0,n):
strbuf += str('%02x ' % buf[i])
if (i + 1) % 16 == 0:
logdbg(strbuf)
strbuf = ''
if strbuf:
logdbg(strbuf)
def get_datum_diff(v, np, ofl):
if abs(np - v) < 0.001 or abs(ofl - v) < 0.001:
return None
return v
def get_datum_match(v, np, ofl):
if np == v or ofl == v:
return None
return v
def calc_checksum(buf, start, end=None):
if end is None:
end = len(buf[0]) - start
cs = 0
for i in xrange(0, end):
cs += buf[0][i+start]
return cs
def get_next_index(idx):
return get_index(idx + 1)
def get_index(idx):
if idx < 0:
return idx + WS28xxDriver.max_records
elif idx >= WS28xxDriver.max_records:
return idx - WS28xxDriver.max_records
return idx
def tstr_to_ts(tstr):
try:
return int(time.mktime(time.strptime(tstr, "%Y-%m-%d %H:%M:%S")))
except (OverflowError, ValueError, TypeError):
pass
return None
def bytes_to_addr(a, b, c):
return ((((a & 0xF) << 8) | b) << 8) | c
def addr_to_index(addr):
return (addr - 416) / 18
def index_to_addr(idx):
return 18 * idx + 416
def print_dict(data):
for x in sorted(data.keys()):
if x == 'dateTime':
print '%s: %s' % (x, weeutil.weeutil.timestamp_to_string(data[x]))
else:
print '%s: %s' % (x, data[x])
class WS28xxConfEditor(weewx.drivers.AbstractConfEditor):
@property
def default_stanza(self):
return """
[WS28xx]
# This section is for the La Crosse WS-2800 series of weather stations.
# Radio frequency to use between USB transceiver and console: US or EU
# US uses 915 MHz, EU uses 868.3 MHz. Default is US.
transceiver_frequency = US
# The station model, e.g., 'LaCrosse C86234' or 'TFA Primus'
model = LaCrosse WS28xx
# The driver to use:
driver = weewx.drivers.ws28xx
"""
def prompt_for_settings(self):
print "Specify the frequency used between the station and the"
print "transceiver, either 'US' (915 MHz) or 'EU' (868.3 MHz)."
freq = self._prompt('frequency', 'US', ['US', 'EU'])
return {'transceiver_frequency': freq}
class WS28xxConfigurator(weewx.drivers.AbstractConfigurator):
def add_options(self, parser):
super(WS28xxConfigurator, self).add_options(parser)
parser.add_option("--check-transceiver", dest="check",
action="store_true",
help="check USB transceiver")
parser.add_option("--pair", dest="pair", action="store_true",
help="pair the USB transceiver with station console")
parser.add_option("--info", dest="info", action="store_true",
help="display weather station configuration")
parser.add_option("--set-interval", dest="interval",
type=int, metavar="N",
help="set logging interval to N minutes")
parser.add_option("--current", dest="current", action="store_true",
help="get the current weather conditions")
parser.add_option("--history", dest="nrecords", type=int, metavar="N",
help="display N history records")
parser.add_option("--history-since", dest="recmin",
type=int, metavar="N",
help="display history records since N minutes ago")
parser.add_option("--maxtries", dest="maxtries", type=int,
help="maximum number of retries, 0 indicates no max")
def do_options(self, options, parser, config_dict, prompt):
maxtries = 3 if options.maxtries is None else int(options.maxtries)
self.station = WS28xxDriver(**config_dict[DRIVER_NAME])
if options.check:
self.check_transceiver(maxtries)
elif options.pair:
self.pair(maxtries)
elif options.interval is not None:
self.set_interval(maxtries, options.interval, prompt)
elif options.current:
self.show_current(maxtries)
elif options.nrecords is not None:
self.show_history(maxtries, count=options.nrecords)
elif options.recmin is not None:
ts = int(time.time()) - options.recmin * 60
self.show_history(maxtries, ts=ts)
else:
self.show_info(maxtries)
self.station.closePort()
def check_transceiver(self, maxtries):
"""See if the transceiver is installed and operational."""
print 'Checking for transceiver...'
ntries = 0
while ntries < maxtries:
ntries += 1
if self.station.transceiver_is_present():
print 'Transceiver is present'
sn = self.station.get_transceiver_serial()
print 'serial: %s' % sn
tid = self.station.get_transceiver_id()
print 'id: %d (0x%04x)' % (tid, tid)
break
print 'Not found (attempt %d of %d) ...' % (ntries, maxtries)
time.sleep(5)
else:
print 'Transceiver not responding.'
def pair(self, maxtries):
"""Pair the transceiver with the station console."""
print 'Pairing transceiver with console...'
maxwait = 90 # how long to wait between button presses, in seconds
ntries = 0
while ntries < maxtries or maxtries == 0:
if self.station.transceiver_is_paired():
print 'Transceiver is paired to console'
break
ntries += 1
msg = 'Press and hold the [v] key until "PC" appears'
if maxtries > 0:
msg += ' (attempt %d of %d)' % (ntries, maxtries)
else:
msg += ' (attempt %d)' % ntries
print msg
now = start_ts = int(time.time())
while (now - start_ts < maxwait and
not self.station.transceiver_is_paired()):
time.sleep(5)
now = int(time.time())
else:
print 'Transceiver not paired to console.'
def get_interval(self, maxtries):
cfg = self.get_config(maxtries)
if cfg is None:
return None
return getHistoryInterval(cfg['history_interval'])
def get_config(self, maxtries):
start_ts = None
ntries = 0
while ntries < maxtries or maxtries == 0:
cfg = self.station.get_config()
if cfg is not None:
return cfg
ntries += 1
if start_ts is None:
start_ts = int(time.time())
else:
dur = int(time.time()) - start_ts
print 'No data after %d seconds (press SET to sync)' % dur
time.sleep(30)
return None
def set_interval(self, maxtries, interval, prompt):
"""Set the station archive interval"""
print "This feature is not yet implemented"
def show_info(self, maxtries):
"""Query the station then display the settings."""
print 'Querying the station for the configuration...'
cfg = self.get_config(maxtries)
if cfg is not None:
print_dict(cfg)
def show_current(self, maxtries):
"""Get current weather observation."""
print 'Querying the station for current weather data...'
start_ts = None
ntries = 0
while ntries < maxtries or maxtries == 0:
packet = self.station.get_observation()
if packet is not None:
print_dict(packet)
break
ntries += 1
if start_ts is None:
start_ts = int(time.time())
else:
dur = int(time.time()) - start_ts
print 'No data after %d seconds (press SET to sync)' % dur
time.sleep(30)
def show_history(self, maxtries, ts=0, count=0):
"""Display the indicated number of records or the records since the
specified timestamp (local time, in seconds)"""
print "Querying the station for historical records..."
ntries = 0
last_n = nrem = None
last_ts = int(time.time())
self.station.start_caching_history(since_ts=ts, num_rec=count)
while nrem is None or nrem > 0:
if ntries >= maxtries:
print 'Giving up after %d tries' % ntries
break
time.sleep(30)
ntries += 1
now = int(time.time())
n = self.station.get_num_history_scanned()
if n == last_n:
dur = now - last_ts
print 'No data after %d seconds (press SET to sync)' % dur
else:
ntries = 0
last_ts = now
last_n = n
nrem = self.station.get_uncached_history_count()
ni = self.station.get_next_history_index()
li = self.station.get_latest_history_index()
msg = " scanned %s records: current=%s latest=%s remaining=%s\r" % (n, ni, li, nrem)
sys.stdout.write(msg)
sys.stdout.flush()
self.station.stop_caching_history()
records = self.station.get_history_cache_records()
self.station.clear_history_cache()
print
print 'Found %d records' % len(records)
for r in records:
print r
class WS28xxDriver(weewx.drivers.AbstractDevice):
"""Driver for LaCrosse WS28xx stations."""
max_records = 1797
def __init__(self, **stn_dict) :
"""Initialize the station object.
model: Which station model is this?
[Optional. Default is 'LaCrosse WS28xx']
transceiver_frequency: Frequency for transceiver-to-console. Specify
either US or EU.
[Required. Default is US]
polling_interval: How often to sample the USB interface for data.
[Optional. Default is 30 seconds]
comm_interval: Communications mode interval
[Optional. Default is 3]
device_id: The USB device ID for the transceiver. If there are
multiple devices with the same vendor and product IDs on the bus,
each will have a unique device identifier. Use this identifier
to indicate which device should be used.
[Optional. Default is None]
serial: The transceiver serial number. If there are multiple
devices with the same vendor and product IDs on the bus, each will
have a unique serial number. Use the serial number to indicate which
transceiver should be used.
[Optional. Default is None]
"""
self.model = stn_dict.get('model', 'LaCrosse WS28xx')
self.polling_interval = int(stn_dict.get('polling_interval', 30))
self.comm_interval = int(stn_dict.get('comm_interval', 3))
self.frequency = stn_dict.get('transceiver_frequency', 'US')
self.device_id = stn_dict.get('device_id', None)
self.serial = stn_dict.get('serial', None)
self.vendor_id = 0x6666
self.product_id = 0x5555
now = int(time.time())
self._service = None
self._last_rain = None
self._last_obs_ts = None
self._last_nodata_log_ts = now
self._nodata_interval = 300 # how often to check for no data
self._last_contact_log_ts = now
self._nocontact_interval = 300 # how often to check for no contact
self._log_interval = 600 # how often to log
global DEBUG_COMM
DEBUG_COMM = int(stn_dict.get('debug_comm', 0))
global DEBUG_CONFIG_DATA
DEBUG_CONFIG_DATA = int(stn_dict.get('debug_config_data', 0))
global DEBUG_WEATHER_DATA
DEBUG_WEATHER_DATA = int(stn_dict.get('debug_weather_data', 0))
global DEBUG_HISTORY_DATA
DEBUG_HISTORY_DATA = int(stn_dict.get('debug_history_data', 0))
global DEBUG_DUMP_FORMAT
DEBUG_DUMP_FORMAT = stn_dict.get('debug_dump_format', 'auto')
loginf('driver version is %s' % DRIVER_VERSION)
loginf('frequency is %s' % self.frequency)
self.startUp()
@property
def hardware_name(self):
return self.model
# this is invoked by StdEngine as it shuts down
def closePort(self):
self.shutDown()
def genLoopPackets(self):
"""Generator function that continuously returns decoded packets."""
while True:
now = int(time.time()+0.5)
packet = self.get_observation()
if packet is not None:
ts = packet['dateTime']
if self._last_obs_ts is None or self._last_obs_ts != ts:
self._last_obs_ts = ts
self._last_nodata_log_ts = now
self._last_contact_log_ts = now
else:
packet = None
# if no new weather data, return an empty packet
if packet is None:
packet = {'usUnits': weewx.METRIC, 'dateTime': now}
# if no new weather data for awhile, log it
if self._last_obs_ts is None or \
now - self._last_obs_ts > self._nodata_interval:
if now - self._last_nodata_log_ts > self._log_interval:
msg = 'no new weather data'
if self._last_obs_ts is not None:
msg += ' after %d seconds' % (
now - self._last_obs_ts)
loginf(msg)
self._last_nodata_log_ts = now
# if no contact with console for awhile, log it
ts = self.get_last_contact()
if ts is None or now - ts > self._nocontact_interval:
if now - self._last_contact_log_ts > self._log_interval:
msg = 'no contact with console'
if ts is not None:
msg += ' after %d seconds' % (now - ts)
msg += ': press [SET] to sync'
loginf(msg)
self._last_contact_log_ts = now
yield packet
time.sleep(self.polling_interval)
def genStartupRecords(self, ts):
loginf('Scanning historical records')
maxtries = 65
ntries = 0
last_n = n = nrem = None
last_ts = now = int(time.time())
self.start_caching_history(since_ts=ts)
while nrem is None or nrem > 0:
if ntries >= maxtries:
logerr('No historical data after %d tries' % ntries)
return
time.sleep(60)
ntries += 1
now = int(time.time())
n = self.get_num_history_scanned()
if n == last_n:
dur = now - last_ts
loginf('No data after %d seconds (press SET to sync)' % dur)
else:
ntries = 0
last_ts = now
last_n = n
nrem = self.get_uncached_history_count()
ni = self.get_next_history_index()
li = self.get_latest_history_index()
loginf("Scanned %s records: current=%s latest=%s remaining=%s" %
(n, ni, li, nrem))
self.stop_caching_history()
records = self.get_history_cache_records()
self.clear_history_cache()
loginf('Found %d historical records' % len(records))
last_ts = None
for r in records:
if last_ts is not None and r['dateTime'] is not None:
r['usUnits'] = weewx.METRIC
r['interval'] = (r['dateTime'] - last_ts) / 60
yield r
last_ts = r['dateTime']
# FIXME: do not implement hardware record generation until we figure
# out how to query the historical records faster.
# def genArchiveRecords(self, since_ts):
# pass
# FIXME: implement retries for this so that rf thread has time to get
# configuration data from the station
# @property
# def archive_interval(self):
# cfg = self.get_config()
# return getHistoryInterval(cfg['history_interval']) * 60
# FIXME: implement set/get time
# def setTime(self):
# pass
# def getTime(self):
# pass
def startUp(self):
if self._service is not None:
return
self._service = CCommunicationService()
self._service.setup(self.frequency,
self.vendor_id, self.product_id, self.device_id,
self.serial, comm_interval=self.comm_interval)
self._service.startRFThread()
def shutDown(self):
self._service.stopRFThread()
self._service.teardown()
self._service = None
def transceiver_is_present(self):
return self._service.DataStore.getTransceiverPresent()
def transceiver_is_paired(self):
return self._service.DataStore.getDeviceRegistered()
def get_transceiver_serial(self):
return self._service.DataStore.getTransceiverSerNo()
def get_transceiver_id(self):
return self._service.DataStore.getDeviceID()
def get_last_contact(self):
return self._service.getLastStat().last_seen_ts
def get_observation(self):
data = self._service.getWeatherData()
ts = data._timestamp
if ts is None:
return None
# add elements required for weewx LOOP packets
packet = {}
packet['usUnits'] = weewx.METRIC
packet['dateTime'] = ts
# data from the station sensors
packet['inTemp'] = get_datum_diff(data._TempIndoor,
CWeatherTraits.TemperatureNP(),
CWeatherTraits.TemperatureOFL())
packet['inHumidity'] = get_datum_diff(data._HumidityIndoor,
CWeatherTraits.HumidityNP(),
CWeatherTraits.HumidityOFL())
packet['outTemp'] = get_datum_diff(data._TempOutdoor,
CWeatherTraits.TemperatureNP(),
CWeatherTraits.TemperatureOFL())
packet['outHumidity'] = get_datum_diff(data._HumidityOutdoor,
CWeatherTraits.HumidityNP(),
CWeatherTraits.HumidityOFL())
packet['pressure'] = get_datum_diff(data._PressureRelative_hPa,
CWeatherTraits.PressureNP(),
CWeatherTraits.PressureOFL())
packet['windSpeed'] = get_datum_diff(data._WindSpeed,
CWeatherTraits.WindNP(),
CWeatherTraits.WindOFL())
packet['windGust'] = get_datum_diff(data._Gust,
CWeatherTraits.WindNP(),
CWeatherTraits.WindOFL())
packet['windDir'] = getWindDir(data._WindDirection,
packet['windSpeed'])
packet['windGustDir'] = getWindDir(data._GustDirection,
packet['windGust'])
# calculated elements not directly reported by station
packet['rainRate'] = get_datum_match(data._Rain1H,
CWeatherTraits.RainNP(),
CWeatherTraits.RainOFL())
if packet['rainRate'] is not None:
packet['rainRate'] /= 10 # weewx wants cm/hr
rain_total = get_datum_match(data._RainTotal,
CWeatherTraits.RainNP(),
CWeatherTraits.RainOFL())
delta = weewx.wxformulas.calculate_rain(rain_total, self._last_rain)
self._last_rain = rain_total
packet['rain'] = delta
if packet['rain'] is not None:
packet['rain'] /= 10 # weewx wants cm
# track the signal strength and battery levels
laststat = self._service.getLastStat()
packet['rxCheckPercent'] = laststat.LastLinkQuality
packet['windBatteryStatus'] = getBatteryStatus(
laststat.LastBatteryStatus, 'wind')
packet['rainBatteryStatus'] = getBatteryStatus(
laststat.LastBatteryStatus, 'rain')
packet['outTempBatteryStatus'] = getBatteryStatus(
laststat.LastBatteryStatus, 'th')
packet['inTempBatteryStatus'] = getBatteryStatus(
laststat.LastBatteryStatus, 'console')
return packet
def get_config(self):
logdbg('get station configuration')
cfg = self._service.getConfigData().asDict()
cs = cfg.get('checksum_out')
if cs is None or cs == 0:
return None
return cfg
def start_caching_history(self, since_ts=0, num_rec=0):
self._service.startCachingHistory(since_ts, num_rec)
def stop_caching_history(self):
self._service.stopCachingHistory()
def get_uncached_history_count(self):
return self._service.getUncachedHistoryCount()
def get_next_history_index(self):
return self._service.getNextHistoryIndex()
def get_latest_history_index(self):
return self._service.getLatestHistoryIndex()
def get_num_history_scanned(self):
return self._service.getNumHistoryScanned()
def get_history_cache_records(self):
return self._service.getHistoryCacheRecords()
def clear_history_cache(self):
self._service.clearHistoryCache()
def set_interval(self, interval):
# FIXME: set the archive interval
pass
# The following classes and methods are adapted from the implementation by
# eddie de pieri, which is in turn based on the HeavyWeather implementation.
class BadResponse(Exception):
"""raised when unexpected data found in frame buffer"""
pass
class DataWritten(Exception):
"""raised when message 'data written' in frame buffer"""
pass
class BitHandling:
# return a nonzero result, 2**offset, if the bit at 'offset' is one.
@staticmethod
def testBit(int_type, offset):
mask = 1 << offset
return int_type & mask
# return an integer with the bit at 'offset' set to 1.
@staticmethod
def setBit(int_type, offset):
mask = 1 << offset
return int_type | mask
# return an integer with the bit at 'offset' set to 1.
@staticmethod
def setBitVal(int_type, offset, val):
mask = val << offset
return int_type | mask
# return an integer with the bit at 'offset' cleared.
@staticmethod
def clearBit(int_type, offset):
mask = ~(1 << offset)
return int_type & mask
# return an integer with the bit at 'offset' inverted, 0->1 and 1->0.
@staticmethod
def toggleBit(int_type, offset):
mask = 1 << offset
return int_type ^ mask
class EHistoryInterval:
hi01Min = 0
hi05Min = 1
hi10Min = 2
hi15Min = 3
hi20Min = 4
hi30Min = 5
hi60Min = 6
hi02Std = 7
hi04Std = 8
hi06Std = 9
hi08Std = 0xA
hi12Std = 0xB
hi24Std = 0xC
class EWindspeedFormat:
wfMs = 0
wfKnots = 1
wfBFT = 2
wfKmh = 3
wfMph = 4
class ERainFormat:
rfMm = 0
rfInch = 1
class EPressureFormat:
pfinHg = 0
pfHPa = 1
class ETemperatureFormat:
tfFahrenheit = 0
tfCelsius = 1
class EClockMode:
ct24H = 0
ctAmPm = 1
class EWeatherTendency:
TREND_NEUTRAL = 0
TREND_UP = 1
TREND_DOWN = 2
TREND_ERR = 3
class EWeatherState:
WEATHER_BAD = 0
WEATHER_NEUTRAL = 1
WEATHER_GOOD = 2
WEATHER_ERR = 3
class EWindDirection:
wdN = 0
wdNNE = 1
wdNE = 2
wdENE = 3
wdE = 4
wdESE = 5
wdSE = 6
wdSSE = 7
wdS = 8
wdSSW = 9
wdSW = 0x0A
wdWSW = 0x0B
wdW = 0x0C
wdWNW = 0x0D
wdNW = 0x0E
wdNNW = 0x0F
wdERR = 0x10
wdInvalid = 0x11
wdNone = 0x12
def getWindDir(wdir, wspeed):
if wspeed is None or wspeed == 0:
return None
if wdir < 0 or wdir >= 16:
return None
return wdir * 360 / 16
class EResetMinMaxFlags:
rmTempIndoorHi = 0
rmTempIndoorLo = 1
rmTempOutdoorHi = 2
rmTempOutdoorLo = 3
rmWindchillHi = 4
rmWindchillLo = 5
rmDewpointHi = 6
rmDewpointLo = 7
rmHumidityIndoorLo = 8
rmHumidityIndoorHi = 9
rmHumidityOutdoorLo = 0x0A
rmHumidityOutdoorHi = 0x0B
rmWindspeedHi = 0x0C
rmWindspeedLo = 0x0D
rmGustHi = 0x0E
rmGustLo = 0x0F
rmPressureLo = 0x10
rmPressureHi = 0x11
rmRain1hHi = 0x12
rmRain24hHi = 0x13
rmRainLastWeekHi = 0x14
rmRainLastMonthHi = 0x15
rmRainTotal = 0x16
rmInvalid = 0x17
class ERequestType:
rtGetCurrent = 0
rtGetHistory = 1
rtGetConfig = 2
rtSetConfig = 3
rtSetTime = 4
rtFirstConfig = 5
rtINVALID = 6
class EAction:
aGetHistory = 0
aReqSetTime = 1
aReqSetConfig = 2
aGetConfig = 3
aGetCurrent = 5
aSendTime = 0xc0
aSendConfig = 0x40
class ERequestState:
rsQueued = 0
rsRunning = 1
rsFinished = 2
rsPreamble = 3
rsWaitDevice = 4
rsWaitConfig = 5
rsError = 6
rsChanged = 7
rsINVALID = 8
class EResponseType:
rtDataWritten = 0x20
rtGetConfig = 0x40
rtGetCurrentWeather = 0x60
rtGetHistory = 0x80
rtRequest = 0xa0
rtReqFirstConfig = 0xa1
rtReqSetConfig = 0xa2
rtReqSetTime = 0xa3
# frequency standards and their associated transmission frequencies
class EFrequency:
fsUS = 'US'
tfUS = 905000000
fsEU = 'EU'
tfEU = 868300000
def getFrequency(standard):
if standard == EFrequency.fsUS:
return EFrequency.tfUS
elif standard == EFrequency.fsEU:
return EFrequency.tfEU
logerr("unknown frequency standard '%s', using US" % standard)
return EFrequency.tfUS
def getFrequencyStandard(frequency):
if frequency == EFrequency.tfUS:
return EFrequency.fsUS
elif frequency == EFrequency.tfEU:
return EFrequency.fsEU
logerr("unknown frequency '%s', using US" % frequency)
return EFrequency.fsUS
# HWPro presents battery flags as WS/TH/RAIN/WIND
# 0 - wind
# 1 - rain
# 2 - thermo-hygro
# 3 - console
batterybits = {'wind':0, 'rain':1, 'th':2, 'console':3}
def getBatteryStatus(status, flag):
"""Return 1 if bit is set, 0 otherwise"""
bit = batterybits.get(flag)
if bit is None:
return None
if BitHandling.testBit(status, bit):
return 1
return 0
history_intervals = {
EHistoryInterval.hi01Min: 1,
EHistoryInterval.hi05Min: 5,
EHistoryInterval.hi10Min: 10,
EHistoryInterval.hi20Min: 20,
EHistoryInterval.hi30Min: 30,
EHistoryInterval.hi60Min: 60,
EHistoryInterval.hi02Std: 120,
EHistoryInterval.hi04Std: 240,
EHistoryInterval.hi06Std: 360,
EHistoryInterval.hi08Std: 480,
EHistoryInterval.hi12Std: 720,
EHistoryInterval.hi24Std: 1440,
}
def getHistoryInterval(i):
return history_intervals.get(i)
# NP - not present
# OFL - outside factory limits
class CWeatherTraits(object):
windDirMap = {
0: "N", 1: "NNE", 2: "NE", 3: "ENE", 4: "E", 5: "ESE", 6: "SE",
7: "SSE", 8: "S", 9: "SSW", 10: "SW", 11: "WSW", 12: "W",
13: "WNW", 14: "NW", 15: "NWN", 16: "err", 17: "inv", 18: "None" }
forecastMap = {
0: "Rainy(Bad)", 1: "Cloudy(Neutral)", 2: "Sunny(Good)", 3: "Error" }
trendMap = {
0: "Stable(Neutral)", 1: "Rising(Up)", 2: "Falling(Down)", 3: "Error" }
@staticmethod
def TemperatureNP():
return 81.099998
@staticmethod
def TemperatureOFL():
return 136.0
@staticmethod
def PressureNP():
return 10101010.0
@staticmethod
def PressureOFL():
return 16666.5
@staticmethod
def HumidityNP():
return 110.0
@staticmethod
def HumidityOFL():
return 121.0
@staticmethod
def RainNP():
return -0.2
@staticmethod
def RainOFL():
return 16666.664
@staticmethod
def WindNP():
return 183.6 # km/h = 51.0 m/s
@staticmethod
def WindOFL():
return 183.96 # km/h = 51.099998 m/s
@staticmethod
def TemperatureOffset():
return 40.0
class CMeasurement:
_Value = 0.0
_ResetFlag = 23
_IsError = 1
_IsOverflow = 1
_Time = None
def Reset(self):
self._Value = 0.0
self._ResetFlag = 23
self._IsError = 1
self._IsOverflow = 1
class CMinMaxMeasurement(object):
def __init__(self):
self._Min = CMeasurement()
self._Max = CMeasurement()
# firmware XXX has bogus date values for these fields
_bad_labels = ['RainLastMonthMax','RainLastWeekMax','PressureRelativeMin']
class USBHardware(object):
@staticmethod
def isOFL2(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) == 15 \
or (buf[0][start+0] & 0xF) == 15
else:
result = (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15
return result
@staticmethod
def isOFL3(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) == 15 \
or (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15
else:
result = (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15 \
or (buf[0][start+1] & 0xF) == 15
return result
@staticmethod
def isOFL5(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) == 15 \
or (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15 \
or (buf[0][start+1] & 0xF) == 15 \
or (buf[0][start+2] >> 4) == 15
else:
result = (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15 \
or (buf[0][start+1] & 0xF) == 15 \
or (buf[0][start+2] >> 4) == 15 \
or (buf[0][start+2] & 0xF) == 15
return result
@staticmethod
def isErr2(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) >= 10 \
and (buf[0][start+0] >> 4) != 15 \
or (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15
else:
result = (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15
return result
@staticmethod
def isErr3(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) >= 10 \
and (buf[0][start+0] >> 4) != 15 \
or (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15
else:
result = (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15 \
or (buf[0][start+1] & 0xF) >= 10 \
and (buf[0][start+1] & 0xF) != 15
return result
@staticmethod
def isErr5(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) >= 10 \
and (buf[0][start+0] >> 4) != 15 \
or (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15 \
or (buf[0][start+1] & 0xF) >= 10 \
and (buf[0][start+1] & 0xF) != 15 \
or (buf[0][start+2] >> 4) >= 10 \
and (buf[0][start+2] >> 4) != 15
else:
result = (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15 \
or (buf[0][start+1] & 0xF) >= 10 \
and (buf[0][start+1] & 0xF) != 15 \
or (buf[0][start+2] >> 4) >= 10 \
and (buf[0][start+2] >> 4) != 15 \
or (buf[0][start+2] & 0xF) >= 10 \
and (buf[0][start+2] & 0xF) != 15
return result
@staticmethod
def reverseByteOrder(buf, start, Count):
nbuf=buf[0]
for i in xrange(0, Count >> 1):
tmp = nbuf[start + i]
nbuf[start + i] = nbuf[start + Count - i - 1]
nbuf[start + Count - i - 1 ] = tmp
buf[0]=nbuf
@staticmethod
def readWindDirectionShared(buf, start):
return (buf[0][0+start] & 0xF, buf[0][start] >> 4)
@staticmethod
def toInt_2(buf, start, StartOnHiNibble):
"""read 2 nibbles"""
if StartOnHiNibble:
rawpre = (buf[0][start+0] >> 4)* 10 \
+ (buf[0][start+0] & 0xF)* 1
else:
rawpre = (buf[0][start+0] & 0xF)* 10 \
+ (buf[0][start+1] >> 4)* 1
return rawpre
@staticmethod
def toRain_7_3(buf, start, StartOnHiNibble):
"""read 7 nibbles, presentation with 3 decimals; units of mm"""
if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or
USBHardware.isErr5(buf, start+1, StartOnHiNibble)):
result = CWeatherTraits.RainNP()
elif (USBHardware.isOFL2(buf, start+0, StartOnHiNibble) or
USBHardware.isOFL5(buf, start+1, StartOnHiNibble)):
result = CWeatherTraits.RainOFL()
elif StartOnHiNibble:
result = (buf[0][start+0] >> 4)* 1000 \
+ (buf[0][start+0] & 0xF)* 100 \
+ (buf[0][start+1] >> 4)* 10 \
+ (buf[0][start+1] & 0xF)* 1 \
+ (buf[0][start+2] >> 4)* 0.1 \
+ (buf[0][start+2] & 0xF)* 0.01 \
+ (buf[0][start+3] >> 4)* 0.001
else:
result = (buf[0][start+0] & 0xF)* 1000 \
+ (buf[0][start+1] >> 4)* 100 \
+ (buf[0][start+1] & 0xF)* 10 \
+ (buf[0][start+2] >> 4)* 1 \
+ (buf[0][start+2] & 0xF)* 0.1 \
+ (buf[0][start+3] >> 4)* 0.01 \
+ (buf[0][start+3] & 0xF)* 0.001
return result
@staticmethod
def toRain_6_2(buf, start, StartOnHiNibble):
'''read 6 nibbles, presentation with 2 decimals; units of mm'''
if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or
USBHardware.isErr2(buf, start+1, StartOnHiNibble) or
USBHardware.isErr2(buf, start+2, StartOnHiNibble) ):
result = CWeatherTraits.RainNP()
elif (USBHardware.isOFL2(buf, start+0, StartOnHiNibble) or
USBHardware.isOFL2(buf, start+1, StartOnHiNibble) or
USBHardware.isOFL2(buf, start+2, StartOnHiNibble)):
result = CWeatherTraits.RainOFL()
elif StartOnHiNibble:
result = (buf[0][start+0] >> 4)* 1000 \
+ (buf[0][start+0] & 0xF)* 100 \
+ (buf[0][start+1] >> 4)* 10 \
+ (buf[0][start+1] & 0xF)* 1 \
+ (buf[0][start+2] >> 4)* 0.1 \
+ (buf[0][start+2] & 0xF)* 0.01
else:
result = (buf[0][start+0] & 0xF)* 1000 \
+ (buf[0][start+1] >> 4)* 100 \
+ (buf[0][start+1] & 0xF)* 10 \
+ (buf[0][start+2] >> 4)* 1 \
+ (buf[0][start+2] & 0xF)* 0.1 \
+ (buf[0][start+3] >> 4)* 0.01
return result
@staticmethod
def toRain_3_1(buf, start, StartOnHiNibble):
"""read 3 nibbles, presentation with 1 decimal; units of 0.1 inch"""
if StartOnHiNibble:
hibyte = buf[0][start+0]
lobyte = (buf[0][start+1] >> 4) & 0xF
else:
hibyte = 16*(buf[0][start+0] & 0xF) + ((buf[0][start+1] >> 4) & 0xF)
lobyte = buf[0][start+1] & 0xF
if hibyte == 0xFF and lobyte == 0xE :
result = CWeatherTraits.RainNP()
elif hibyte == 0xFF and lobyte == 0xF :
result = CWeatherTraits.RainOFL()
else:
val = USBHardware.toFloat_3_1(buf, start, StartOnHiNibble) # 0.1 inch
result = val * 2.54 # mm
return result
@staticmethod
def toFloat_3_1(buf, start, StartOnHiNibble):
"""read 3 nibbles, presentation with 1 decimal"""
if StartOnHiNibble:
result = (buf[0][start+0] >> 4)*16**2 \
+ (buf[0][start+0] & 0xF)* 16**1 \
+ (buf[0][start+1] >> 4)* 16**0
else:
result = (buf[0][start+0] & 0xF)*16**2 \
+ (buf[0][start+1] >> 4)* 16**1 \
+ (buf[0][start+1] & 0xF)* 16**0
result = result / 10.0
return result
@staticmethod
def toDateTime(buf, start, StartOnHiNibble, label):
"""read 10 nibbles, presentation as DateTime"""
result = None
if (USBHardware.isErr2(buf, start+0, StartOnHiNibble)
or USBHardware.isErr2(buf, start+1, StartOnHiNibble)
or USBHardware.isErr2(buf, start+2, StartOnHiNibble)
or USBHardware.isErr2(buf, start+3, StartOnHiNibble)
or USBHardware.isErr2(buf, start+4, StartOnHiNibble)):
logerr('ToDateTime: bogus date for %s: error status in buffer' %
label)
else:
year = USBHardware.toInt_2(buf, start+0, StartOnHiNibble) + 2000
month = USBHardware.toInt_2(buf, start+1, StartOnHiNibble)
days = USBHardware.toInt_2(buf, start+2, StartOnHiNibble)
hours = USBHardware.toInt_2(buf, start+3, StartOnHiNibble)
minutes = USBHardware.toInt_2(buf, start+4, StartOnHiNibble)
try:
result = datetime(year, month, days, hours, minutes)
except ValueError:
if label not in _bad_labels:
logerr(('ToDateTime: bogus date for %s:'
' bad date conversion from'
' %s %s %s %s %s') %
(label, minutes, hours, days, month, year))
if result is None:
# FIXME: use None instead of a really old date to indicate invalid
result = datetime(1900, 01, 01, 00, 00)
return result
@staticmethod
def toHumidity_2_0(buf, start, StartOnHiNibble):
"""read 2 nibbles, presentation with 0 decimal"""
if USBHardware.isErr2(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.HumidityNP()
elif USBHardware.isOFL2(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.HumidityOFL()
else:
result = USBHardware.toInt_2(buf, start, StartOnHiNibble)
return result
@staticmethod
def toTemperature_5_3(buf, start, StartOnHiNibble):
"""read 5 nibbles, presentation with 3 decimals; units of degree C"""
if USBHardware.isErr5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.TemperatureNP()
elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.TemperatureOFL()
else:
if StartOnHiNibble:
rawtemp = (buf[0][start+0] >> 4)* 10 \
+ (buf[0][start+0] & 0xF)* 1 \
+ (buf[0][start+1] >> 4)* 0.1 \
+ (buf[0][start+1] & 0xF)* 0.01 \
+ (buf[0][start+2] >> 4)* 0.001
else:
rawtemp = (buf[0][start+0] & 0xF)* 10 \
+ (buf[0][start+1] >> 4)* 1 \
+ (buf[0][start+1] & 0xF)* 0.1 \
+ (buf[0][start+2] >> 4)* 0.01 \
+ (buf[0][start+2] & 0xF)* 0.001
result = rawtemp - CWeatherTraits.TemperatureOffset()
return result
@staticmethod
def toTemperature_3_1(buf, start, StartOnHiNibble):
"""read 3 nibbles, presentation with 1 decimal; units of degree C"""
if USBHardware.isErr3(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.TemperatureNP()
elif USBHardware.isOFL3(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.TemperatureOFL()
else:
if StartOnHiNibble :
rawtemp = (buf[0][start+0] >> 4)* 10 \
+ (buf[0][start+0] & 0xF)* 1 \
+ (buf[0][start+1] >> 4)* 0.1
else:
rawtemp = (buf[0][start+0] & 0xF)* 10 \
+ (buf[0][start+1] >> 4)* 1 \
+ (buf[0][start+1] & 0xF)* 0.1
result = rawtemp - CWeatherTraits.TemperatureOffset()
return result
@staticmethod
def toWindspeed_6_2(buf, start):
"""read 6 nibbles, presentation with 2 decimals; units of km/h"""
result = (buf[0][start+0] >> 4)* 16**5 \
+ (buf[0][start+0] & 0xF)* 16**4 \
+ (buf[0][start+1] >> 4)* 16**3 \
+ (buf[0][start+1] & 0xF)* 16**2 \
+ (buf[0][start+2] >> 4)* 16**1 \
+ (buf[0][start+2] & 0xF)
result /= 256.0
result /= 100.0 # km/h
return result
@staticmethod
def toWindspeed_3_1(buf, start, StartOnHiNibble):
"""read 3 nibbles, presentation with 1 decimal; units of m/s"""
if StartOnHiNibble :
hibyte = buf[0][start+0]
lobyte = (buf[0][start+1] >> 4) & 0xF
else:
hibyte = 16*(buf[0][start+0] & 0xF) + ((buf[0][start+1] >> 4) & 0xF)
lobyte = buf[0][start+1] & 0xF
if hibyte == 0xFF and lobyte == 0xE:
result = CWeatherTraits.WindNP()
elif hibyte == 0xFF and lobyte == 0xF:
result = CWeatherTraits.WindOFL()
else:
result = USBHardware.toFloat_3_1(buf, start, StartOnHiNibble) # m/s
result *= 3.6 # km/h
return result
@staticmethod
def readPressureShared(buf, start, StartOnHiNibble):
return (USBHardware.toPressure_hPa_5_1(buf,start+2,1-StartOnHiNibble),
USBHardware.toPressure_inHg_5_2(buf,start,StartOnHiNibble))
@staticmethod
def toPressure_hPa_5_1(buf, start, StartOnHiNibble):
"""read 5 nibbles, presentation with 1 decimal; units of hPa (mbar)"""
if USBHardware.isErr5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.PressureNP()
elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.PressureOFL()
elif StartOnHiNibble :
result = (buf[0][start+0] >> 4)* 1000 \
+ (buf[0][start+0] & 0xF)* 100 \
+ (buf[0][start+1] >> 4)* 10 \
+ (buf[0][start+1] & 0xF)* 1 \
+ (buf[0][start+2] >> 4)* 0.1
else:
result = (buf[0][start+0] & 0xF)* 1000 \
+ (buf[0][start+1] >> 4)* 100 \
+ (buf[0][start+1] & 0xF)* 10 \
+ (buf[0][start+2] >> 4)* 1 \
+ (buf[0][start+2] & 0xF)* 0.1
return result
@staticmethod
def toPressure_inHg_5_2(buf, start, StartOnHiNibble):
"""read 5 nibbles, presentation with 2 decimals; units of inHg"""
if USBHardware.isErr5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.PressureNP()
elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.PressureOFL()
elif StartOnHiNibble :
result = (buf[0][start+0] >> 4)* 100 \
+ (buf[0][start+0] & 0xF)* 10 \
+ (buf[0][start+1] >> 4)* 1 \
+ (buf[0][start+1] & 0xF)* 0.1 \
+ (buf[0][start+2] >> 4)* 0.01
else:
result = (buf[0][start+0] & 0xF)* 100 \
+ (buf[0][start+1] >> 4)* 10 \
+ (buf[0][start+1] & 0xF)* 1 \
+ (buf[0][start+2] >> 4)* 0.1 \
+ (buf[0][start+2] & 0xF)* 0.01
return result
class CCurrentWeatherData(object):
def __init__(self):
self._timestamp = None
self._checksum = None
self._PressureRelative_hPa = CWeatherTraits.PressureNP()
self._PressureRelative_hPaMinMax = CMinMaxMeasurement()
self._PressureRelative_inHg = CWeatherTraits.PressureNP()
self._PressureRelative_inHgMinMax = CMinMaxMeasurement()
self._WindSpeed = CWeatherTraits.WindNP()
self._WindDirection = EWindDirection.wdNone
self._WindDirection1 = EWindDirection.wdNone
self._WindDirection2 = EWindDirection.wdNone
self._WindDirection3 = EWindDirection.wdNone
self._WindDirection4 = EWindDirection.wdNone
self._WindDirection5 = EWindDirection.wdNone
self._Gust = CWeatherTraits.WindNP()
self._GustMax = CMinMaxMeasurement()
self._GustDirection = EWindDirection.wdNone
self._GustDirection1 = EWindDirection.wdNone
self._GustDirection2 = EWindDirection.wdNone
self._GustDirection3 = EWindDirection.wdNone
self._GustDirection4 = EWindDirection.wdNone
self._GustDirection5 = EWindDirection.wdNone
self._Rain1H = CWeatherTraits.RainNP()
self._Rain1HMax = CMinMaxMeasurement()
self._Rain24H = CWeatherTraits.RainNP()
self._Rain24HMax = CMinMaxMeasurement()
self._RainLastWeek = CWeatherTraits.RainNP()
self._RainLastWeekMax = CMinMaxMeasurement()
self._RainLastMonth = CWeatherTraits.RainNP()
self._RainLastMonthMax = CMinMaxMeasurement()
self._RainTotal = CWeatherTraits.RainNP()
self._LastRainReset = None
self._TempIndoor = CWeatherTraits.TemperatureNP()
self._TempIndoorMinMax = CMinMaxMeasurement()
self._TempOutdoor = CWeatherTraits.TemperatureNP()
self._TempOutdoorMinMax = CMinMaxMeasurement()
self._HumidityIndoor = CWeatherTraits.HumidityNP()
self._HumidityIndoorMinMax = CMinMaxMeasurement()
self._HumidityOutdoor = CWeatherTraits.HumidityNP()
self._HumidityOutdoorMinMax = CMinMaxMeasurement()
self._Dewpoint = CWeatherTraits.TemperatureNP()
self._DewpointMinMax = CMinMaxMeasurement()
self._Windchill = CWeatherTraits.TemperatureNP()
self._WindchillMinMax = CMinMaxMeasurement()
self._WeatherState = EWeatherState.WEATHER_ERR
self._WeatherTendency = EWeatherTendency.TREND_ERR
self._AlarmRingingFlags = 0
self._AlarmMarkedFlags = 0
self._PresRel_hPa_Max = 0.0
self._PresRel_inHg_Max = 0.0
@staticmethod
def calcChecksum(buf):
return calc_checksum(buf, 6)
def checksum(self):
return self._checksum
def read(self, buf):
self._timestamp = int(time.time() + 0.5)
self._checksum = CCurrentWeatherData.calcChecksum(buf)
nbuf = [0]
nbuf[0] = buf[0]
self._StartBytes = nbuf[0][6]*0xF + nbuf[0][7] # FIXME: what is this?
self._WeatherTendency = (nbuf[0][8] >> 4) & 0xF
if self._WeatherTendency > 3:
self._WeatherTendency = 3
self._WeatherState = nbuf[0][8] & 0xF
if self._WeatherState > 3:
self._WeatherState = 3
self._TempIndoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 19, 0)
self._TempIndoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 22, 1)
self._TempIndoor = USBHardware.toTemperature_5_3(nbuf, 24, 0)
self._TempIndoorMinMax._Min._IsError = (self._TempIndoorMinMax._Min._Value == CWeatherTraits.TemperatureNP())
self._TempIndoorMinMax._Min._IsOverflow = (self._TempIndoorMinMax._Min._Value == CWeatherTraits.TemperatureOFL())
self._TempIndoorMinMax._Max._IsError = (self._TempIndoorMinMax._Max._Value == CWeatherTraits.TemperatureNP())
self._TempIndoorMinMax._Max._IsOverflow = (self._TempIndoorMinMax._Max._Value == CWeatherTraits.TemperatureOFL())
self._TempIndoorMinMax._Max._Time = None if self._TempIndoorMinMax._Max._IsError or self._TempIndoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 9, 0, 'TempIndoorMax')
self._TempIndoorMinMax._Min._Time = None if self._TempIndoorMinMax._Min._IsError or self._TempIndoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 14, 0, 'TempIndoorMin')
self._TempOutdoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 37, 0)
self._TempOutdoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 40, 1)
self._TempOutdoor = USBHardware.toTemperature_5_3(nbuf, 42, 0)
self._TempOutdoorMinMax._Min._IsError = (self._TempOutdoorMinMax._Min._Value == CWeatherTraits.TemperatureNP())
self._TempOutdoorMinMax._Min._IsOverflow = (self._TempOutdoorMinMax._Min._Value == CWeatherTraits.TemperatureOFL())
self._TempOutdoorMinMax._Max._IsError = (self._TempOutdoorMinMax._Max._Value == CWeatherTraits.TemperatureNP())
self._TempOutdoorMinMax._Max._IsOverflow = (self._TempOutdoorMinMax._Max._Value == CWeatherTraits.TemperatureOFL())
self._TempOutdoorMinMax._Max._Time = None if self._TempOutdoorMinMax._Max._IsError or self._TempOutdoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 27, 0, 'TempOutdoorMax')
self._TempOutdoorMinMax._Min._Time = None if self._TempOutdoorMinMax._Min._IsError or self._TempOutdoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 32, 0, 'TempOutdoorMin')
self._WindchillMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 55, 0)
self._WindchillMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 58, 1)
self._Windchill = USBHardware.toTemperature_5_3(nbuf, 60, 0)
self._WindchillMinMax._Min._IsError = (self._WindchillMinMax._Min._Value == CWeatherTraits.TemperatureNP())
self._WindchillMinMax._Min._IsOverflow = (self._WindchillMinMax._Min._Value == CWeatherTraits.TemperatureOFL())
self._WindchillMinMax._Max._IsError = (self._WindchillMinMax._Max._Value == CWeatherTraits.TemperatureNP())
self._WindchillMinMax._Max._IsOverflow = (self._WindchillMinMax._Max._Value == CWeatherTraits.TemperatureOFL())
self._WindchillMinMax._Max._Time = None if self._WindchillMinMax._Max._IsError or self._WindchillMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 45, 0, 'WindchillMax')
self._WindchillMinMax._Min._Time = None if self._WindchillMinMax._Min._IsError or self._WindchillMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 50, 0, 'WindchillMin')
self._DewpointMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 73, 0)
self._DewpointMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 76, 1)
self._Dewpoint = USBHardware.toTemperature_5_3(nbuf, 78, 0)
self._DewpointMinMax._Min._IsError = (self._DewpointMinMax._Min._Value == CWeatherTraits.TemperatureNP())
self._DewpointMinMax._Min._IsOverflow = (self._DewpointMinMax._Min._Value == CWeatherTraits.TemperatureOFL())
self._DewpointMinMax._Max._IsError = (self._DewpointMinMax._Max._Value == CWeatherTraits.TemperatureNP())
self._DewpointMinMax._Max._IsOverflow = (self._DewpointMinMax._Max._Value == CWeatherTraits.TemperatureOFL())
self._DewpointMinMax._Min._Time = None if self._DewpointMinMax._Min._IsError or self._DewpointMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 68, 0, 'DewpointMin')
self._DewpointMinMax._Max._Time = None if self._DewpointMinMax._Max._IsError or self._DewpointMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 63, 0, 'DewpointMax')
self._HumidityIndoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 91, 1)
self._HumidityIndoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 92, 1)
self._HumidityIndoor = USBHardware.toHumidity_2_0(nbuf, 93, 1)
self._HumidityIndoorMinMax._Min._IsError = (self._HumidityIndoorMinMax._Min._Value == CWeatherTraits.HumidityNP())
self._HumidityIndoorMinMax._Min._IsOverflow = (self._HumidityIndoorMinMax._Min._Value == CWeatherTraits.HumidityOFL())
self._HumidityIndoorMinMax._Max._IsError = (self._HumidityIndoorMinMax._Max._Value == CWeatherTraits.HumidityNP())
self._HumidityIndoorMinMax._Max._IsOverflow = (self._HumidityIndoorMinMax._Max._Value == CWeatherTraits.HumidityOFL())
self._HumidityIndoorMinMax._Max._Time = None if self._HumidityIndoorMinMax._Max._IsError or self._HumidityIndoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 81, 1, 'HumidityIndoorMax')
self._HumidityIndoorMinMax._Min._Time = None if self._HumidityIndoorMinMax._Min._IsError or self._HumidityIndoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 86, 1, 'HumidityIndoorMin')
self._HumidityOutdoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 104, 1)
self._HumidityOutdoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 105, 1)
self._HumidityOutdoor = USBHardware.toHumidity_2_0(nbuf, 106, 1)
self._HumidityOutdoorMinMax._Min._IsError = (self._HumidityOutdoorMinMax._Min._Value == CWeatherTraits.HumidityNP())
self._HumidityOutdoorMinMax._Min._IsOverflow = (self._HumidityOutdoorMinMax._Min._Value == CWeatherTraits.HumidityOFL())
self._HumidityOutdoorMinMax._Max._IsError = (self._HumidityOutdoorMinMax._Max._Value == CWeatherTraits.HumidityNP())
self._HumidityOutdoorMinMax._Max._IsOverflow = (self._HumidityOutdoorMinMax._Max._Value == CWeatherTraits.HumidityOFL())
self._HumidityOutdoorMinMax._Max._Time = None if self._HumidityOutdoorMinMax._Max._IsError or self._HumidityOutdoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 94, 1, 'HumidityOutdoorMax')
self._HumidityOutdoorMinMax._Min._Time = None if self._HumidityOutdoorMinMax._Min._IsError or self._HumidityOutdoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 99, 1, 'HumidityOutdoorMin')
self._RainLastMonthMax._Max._Time = USBHardware.toDateTime(nbuf, 107, 1, 'RainLastMonthMax')
self._RainLastMonthMax._Max._Value = USBHardware.toRain_6_2(nbuf, 112, 1)
self._RainLastMonth = USBHardware.toRain_6_2(nbuf, 115, 1)
self._RainLastWeekMax._Max._Time = USBHardware.toDateTime(nbuf, 118, 1, 'RainLastWeekMax')
self._RainLastWeekMax._Max._Value = USBHardware.toRain_6_2(nbuf, 123, 1)
self._RainLastWeek = USBHardware.toRain_6_2(nbuf, 126, 1)
self._Rain24HMax._Max._Time = USBHardware.toDateTime(nbuf, 129, 1, 'Rain24HMax')
self._Rain24HMax._Max._Value = USBHardware.toRain_6_2(nbuf, 134, 1)
self._Rain24H = USBHardware.toRain_6_2(nbuf, 137, 1)
self._Rain1HMax._Max._Time = USBHardware.toDateTime(nbuf, 140, 1, 'Rain1HMax')
self._Rain1HMax._Max._Value = USBHardware.toRain_6_2(nbuf, 145, 1)
self._Rain1H = USBHardware.toRain_6_2(nbuf, 148, 1)
self._LastRainReset = USBHardware.toDateTime(nbuf, 151, 0, 'LastRainReset')
self._RainTotal = USBHardware.toRain_7_3(nbuf, 156, 0)
(w ,w1) = USBHardware.readWindDirectionShared(nbuf, 162)
(w2,w3) = USBHardware.readWindDirectionShared(nbuf, 161)
(w4,w5) = USBHardware.readWindDirectionShared(nbuf, 160)
self._WindDirection = w
self._WindDirection1 = w1
self._WindDirection2 = w2
self._WindDirection3 = w3
self._WindDirection4 = w4
self._WindDirection5 = w5
if DEBUG_WEATHER_DATA > 2:
unknownbuf = [0]*9
for i in xrange(0,9):
unknownbuf[i] = nbuf[163+i]
strbuf = ""
for i in unknownbuf:
strbuf += str("%.2x " % i)
logdbg('Bytes with unknown meaning at 157-165: %s' % strbuf)
self._WindSpeed = USBHardware.toWindspeed_6_2(nbuf, 172)
# FIXME: read the WindErrFlags
(g ,g1) = USBHardware.readWindDirectionShared(nbuf, 177)
(g2,g3) = USBHardware.readWindDirectionShared(nbuf, 176)
(g4,g5) = USBHardware.readWindDirectionShared(nbuf, 175)
self._GustDirection = g
self._GustDirection1 = g1
self._GustDirection2 = g2
self._GustDirection3 = g3
self._GustDirection4 = g4
self._GustDirection5 = g5
self._GustMax._Max._Value = USBHardware.toWindspeed_6_2(nbuf, 184)
self._GustMax._Max._IsError = (self._GustMax._Max._Value == CWeatherTraits.WindNP())
self._GustMax._Max._IsOverflow = (self._GustMax._Max._Value == CWeatherTraits.WindOFL())
self._GustMax._Max._Time = None if self._GustMax._Max._IsError or self._GustMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 179, 1, 'GustMax')
self._Gust = USBHardware.toWindspeed_6_2(nbuf, 187)
# Apparently the station returns only ONE date time for both hPa/inHg
# Min Time Reset and Max Time Reset
self._PressureRelative_hPaMinMax._Max._Time = USBHardware.toDateTime(nbuf, 190, 1, 'PressureRelative_hPaMax')
self._PressureRelative_inHgMinMax._Max._Time = self._PressureRelative_hPaMinMax._Max._Time
self._PressureRelative_hPaMinMax._Min._Time = self._PressureRelative_hPaMinMax._Max._Time # firmware bug, should be: USBHardware.toDateTime(nbuf, 195, 1)
self._PressureRelative_inHgMinMax._Min._Time = self._PressureRelative_hPaMinMax._Min._Time
(self._PresRel_hPa_Max, self._PresRel_inHg_Max) = USBHardware.readPressureShared(nbuf, 195, 1) # firmware bug, should be: self._PressureRelative_hPaMinMax._Min._Time
(self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Value) = USBHardware.readPressureShared(nbuf, 200, 1)
(self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Value) = USBHardware.readPressureShared(nbuf, 205, 1)
(self._PressureRelative_hPa, self._PressureRelative_inHg) = USBHardware.readPressureShared(nbuf, 210, 1)
def toLog(self):
logdbg("_WeatherState=%s _WeatherTendency=%s _AlarmRingingFlags %04x" % (CWeatherTraits.forecastMap[self._WeatherState], CWeatherTraits.trendMap[self._WeatherTendency], self._AlarmRingingFlags))
logdbg("_TempIndoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._TempIndoor, self._TempIndoorMinMax._Min._Value, self._TempIndoorMinMax._Min._Time, self._TempIndoorMinMax._Max._Value, self._TempIndoorMinMax._Max._Time))
logdbg("_HumidityIndoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._HumidityIndoor, self._HumidityIndoorMinMax._Min._Value, self._HumidityIndoorMinMax._Min._Time, self._HumidityIndoorMinMax._Max._Value, self._HumidityIndoorMinMax._Max._Time))
logdbg("_TempOutdoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._TempOutdoor, self._TempOutdoorMinMax._Min._Value, self._TempOutdoorMinMax._Min._Time, self._TempOutdoorMinMax._Max._Value, self._TempOutdoorMinMax._Max._Time))
logdbg("_HumidityOutdoor=%8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._HumidityOutdoor, self._HumidityOutdoorMinMax._Min._Value, self._HumidityOutdoorMinMax._Min._Time, self._HumidityOutdoorMinMax._Max._Value, self._HumidityOutdoorMinMax._Max._Time))
logdbg("_Windchill= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._Windchill, self._WindchillMinMax._Min._Value, self._WindchillMinMax._Min._Time, self._WindchillMinMax._Max._Value, self._WindchillMinMax._Max._Time))
logdbg("_Dewpoint= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._Dewpoint, self._DewpointMinMax._Min._Value, self._DewpointMinMax._Min._Time, self._DewpointMinMax._Max._Value, self._DewpointMinMax._Max._Time))
logdbg("_WindSpeed= %8.3f" % self._WindSpeed)
logdbg("_Gust= %8.3f _Max=%8.3f (%s)" % (self._Gust, self._GustMax._Max._Value, self._GustMax._Max._Time))
logdbg('_WindDirection= %3s _GustDirection= %3s' % (CWeatherTraits.windDirMap[self._WindDirection], CWeatherTraits.windDirMap[self._GustDirection]))
logdbg('_WindDirection1= %3s _GustDirection1= %3s' % (CWeatherTraits.windDirMap[self._WindDirection1], CWeatherTraits.windDirMap[self._GustDirection1]))
logdbg('_WindDirection2= %3s _GustDirection2= %3s' % (CWeatherTraits.windDirMap[self._WindDirection2], CWeatherTraits.windDirMap[self._GustDirection2]))
logdbg('_WindDirection3= %3s _GustDirection3= %3s' % (CWeatherTraits.windDirMap[self._WindDirection3], CWeatherTraits.windDirMap[self._GustDirection3]))
logdbg('_WindDirection4= %3s _GustDirection4= %3s' % (CWeatherTraits.windDirMap[self._WindDirection4], CWeatherTraits.windDirMap[self._GustDirection4]))
logdbg('_WindDirection5= %3s _GustDirection5= %3s' % (CWeatherTraits.windDirMap[self._WindDirection5], CWeatherTraits.windDirMap[self._GustDirection5]))
if (self._RainLastMonth > 0) or (self._RainLastWeek > 0):
logdbg("_RainLastMonth= %8.3f _Max=%8.3f (%s)" % (self._RainLastMonth, self._RainLastMonthMax._Max._Value, self._RainLastMonthMax._Max._Time))
logdbg("_RainLastWeek= %8.3f _Max=%8.3f (%s)" % (self._RainLastWeek, self._RainLastWeekMax._Max._Value, self._RainLastWeekMax._Max._Time))
logdbg("_Rain24H= %8.3f _Max=%8.3f (%s)" % (self._Rain24H, self._Rain24HMax._Max._Value, self._Rain24HMax._Max._Time))
logdbg("_Rain1H= %8.3f _Max=%8.3f (%s)" % (self._Rain1H, self._Rain1HMax._Max._Value, self._Rain1HMax._Max._Time))
logdbg("_RainTotal= %8.3f _LastRainReset= (%s)" % (self._RainTotal, self._LastRainReset))
logdbg("PressureRel_hPa= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s) " % (self._PressureRelative_hPa, self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_hPaMinMax._Min._Time, self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_hPaMinMax._Max._Time))
logdbg("PressureRel_inHg=%8.3f _Min=%8.3f (%s) _Max=%8.3f (%s) " % (self._PressureRelative_inHg, self._PressureRelative_inHgMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Time, self._PressureRelative_inHgMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Time))
###logdbg('(* Bug in Weather Station: PressureRelative._Min._Time is written to location of _PressureRelative._Max._Time')
###logdbg('Instead of PressureRelative._Min._Time we get: _PresRel_hPa_Max= %8.3f, _PresRel_inHg_max =%8.3f;' % (self._PresRel_hPa_Max, self._PresRel_inHg_Max))
class CWeatherStationConfig(object):
def __init__(self):
self._InBufCS = 0 # checksum of received config
self._OutBufCS = 0 # calculated config checksum from outbuf config
self._ClockMode = 0
self._TemperatureFormat = 0
self._PressureFormat = 0
self._RainFormat = 0
self._WindspeedFormat = 0
self._WeatherThreshold = 0
self._StormThreshold = 0
self._LCDContrast = 0
self._LowBatFlags = 0
self._WindDirAlarmFlags = 0
self._OtherAlarmFlags = 0
self._ResetMinMaxFlags = 0 # output only
self._HistoryInterval = 0
self._TempIndoorMinMax = CMinMaxMeasurement()
self._TempOutdoorMinMax = CMinMaxMeasurement()
self._HumidityIndoorMinMax = CMinMaxMeasurement()
self._HumidityOutdoorMinMax = CMinMaxMeasurement()
self._Rain24HMax = CMinMaxMeasurement()
self._GustMax = CMinMaxMeasurement()
self._PressureRelative_hPaMinMax = CMinMaxMeasurement()
self._PressureRelative_inHgMinMax = CMinMaxMeasurement()
def setTemps(self,TempFormat,InTempLo,InTempHi,OutTempLo,OutTempHi):
f1 = TempFormat
t1 = InTempLo
t2 = InTempHi
t3 = OutTempLo
t4 = OutTempHi
if f1 not in [ETemperatureFormat.tfFahrenheit,
ETemperatureFormat.tfCelsius]:
logerr('setTemps: unknown temperature format %s' % TempFormat)
return 0
if t1 < -40.0 or t1 > 59.9 or t2 < -40.0 or t2 > 59.9 or \
t3 < -40.0 or t3 > 59.9 or t4 < -40.0 or t4 > 59.9:
logerr('setTemps: one or more values out of range')
return 0
self._TemperatureFormat = f1
self._TempIndoorMinMax._Min._Value = t1
self._TempIndoorMinMax._Max._Value = t2
self._TempOutdoorMinMax._Min._Value = t3
self._TempOutdoorMinMax._Max._Value = t4
return 1
def setHums(self,InHumLo,InHumHi,OutHumLo,OutHumHi):
h1 = InHumLo
h2 = InHumHi
h3 = OutHumLo
h4 = OutHumHi
if h1 < 1 or h1 > 99 or h2 < 1 or h2 > 99 or \
h3 < 1 or h3 > 99 or h4 < 1 or h4 > 99:
logerr('setHums: one or more values out of range')
return 0
self._HumidityIndoorMinMax._Min._Value = h1
self._HumidityIndoorMinMax._Max._Value = h2
self._HumidityOutdoorMinMax._Min._Value = h3
self._HumidityOutdoorMinMax._Max._Value = h4
return 1
def setRain24H(self,RainFormat,Rain24hHi):
f1 = RainFormat
r1 = Rain24hHi
if f1 not in [ERainFormat.rfMm, ERainFormat.rfInch]:
logerr('setRain24: unknown format %s' % RainFormat)
return 0
if r1 < 0.0 or r1 > 9999.9:
logerr('setRain24: value outside range')
return 0
self._RainFormat = f1
self._Rain24HMax._Max._Value = r1
return 1
def setGust(self,WindSpeedFormat,GustHi):
# When the units of a max gust alarm are changed in the weather
# station itself, automatically the value is converted to the new
# unit and rounded to a whole number. Weewx receives a value
# converted to km/h.
#
# It is too much trouble to sort out what exactly the internal
# conversion algoritms are for the other wind units.
#
# Setting a value in km/h units is tested and works, so this will
# be the only option available.
f1 = WindSpeedFormat
g1 = GustHi
if f1 < EWindspeedFormat.wfMs or f1 > EWindspeedFormat.wfMph:
logerr('setGust: unknown format %s' % WindSpeedFormat)
return 0
if f1 != EWindspeedFormat.wfKmh:
logerr('setGust: only units of km/h are supported')
return 0
if g1 < 0.0 or g1 > 180.0:
logerr('setGust: value outside range')
return 0
self._WindSpeedFormat = f1
self._GustMax._Max._Value = int(g1) # apparently gust value is always an integer
return 1
def setPresRels(self,PressureFormat,PresRelhPaLo,PresRelhPaHi,PresRelinHgLo,PresRelinHgHi):
f1 = PressureFormat
p1 = PresRelhPaLo
p2 = PresRelhPaHi
p3 = PresRelinHgLo
p4 = PresRelinHgHi
if f1 not in [EPressureFormat.pfinHg, EPressureFormat.pfHPa]:
logerr('setPresRel: unknown format %s' % PressureFormat)
return 0
if p1 < 920.0 or p1 > 1080.0 or p2 < 920.0 or p2 > 1080.0 or \
p3 < 27.10 or p3 > 31.90 or p4 < 27.10 or p4 > 31.90:
logerr('setPresRel: value outside range')
return 0
self._RainFormat = f1
self._PressureRelative_hPaMinMax._Min._Value = p1
self._PressureRelative_hPaMinMax._Max._Value = p2
self._PressureRelative_inHgMinMax._Min._Value = p3
self._PressureRelative_inHgMinMax._Max._Value = p4
return 1
def getOutBufCS(self):
return self._OutBufCS
def getInBufCS(self):
return self._InBufCS
def setResetMinMaxFlags(self, resetMinMaxFlags):
logdbg('setResetMinMaxFlags: %s' % resetMinMaxFlags)
self._ResetMinMaxFlags = resetMinMaxFlags
def parseRain_3(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 7-digit number with 3 decimals'''
num = int(number*1000)
parsebuf=[0]*7
for i in xrange(7-numbytes,7):
parsebuf[i] = num%10
num = num//10
if StartOnHiNibble:
buf[0][0+start] = parsebuf[6]*16 + parsebuf[5]
buf[0][1+start] = parsebuf[4]*16 + parsebuf[3]
buf[0][2+start] = parsebuf[2]*16 + parsebuf[1]
buf[0][3+start] = parsebuf[0]*16 + (buf[0][3+start] & 0xF)
else:
buf[0][0+start] = (buf[0][0+start] & 0xF0) + parsebuf[6]
buf[0][1+start] = parsebuf[5]*16 + parsebuf[4]
buf[0][2+start] = parsebuf[3]*16 + parsebuf[2]
buf[0][3+start] = parsebuf[1]*16 + parsebuf[0]
def parseWind_6(self, number, buf, start):
'''Parse float number to 6 bytes'''
num = int(number*100*256)
parsebuf=[0]*6
for i in xrange(0,6):
parsebuf[i] = num%16
num = num//16
buf[0][0+start] = parsebuf[5]*16 + parsebuf[4]
buf[0][1+start] = parsebuf[3]*16 + parsebuf[2]
buf[0][2+start] = parsebuf[1]*16 + parsebuf[0]
def parse_0(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 5-digit number with 0 decimals'''
num = int(number)
nbuf=[0]*5
for i in xrange(5-numbytes,5):
nbuf[i] = num%10
num = num//10
if StartOnHiNibble:
buf[0][0+start] = nbuf[4]*16 + nbuf[3]
buf[0][1+start] = nbuf[2]*16 + nbuf[1]
buf[0][2+start] = nbuf[0]*16 + (buf[0][2+start] & 0x0F)
else:
buf[0][0+start] = (buf[0][0+start] & 0xF0) + nbuf[4]
buf[0][1+start] = nbuf[3]*16 + nbuf[2]
buf[0][2+start] = nbuf[1]*16 + nbuf[0]
def parse_1(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 5 digit number with 1 decimal'''
self.parse_0(number*10.0, buf, start, StartOnHiNibble, numbytes)
def parse_2(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 5 digit number with 2 decimals'''
self.parse_0(number*100.0, buf, start, StartOnHiNibble, numbytes)
def parse_3(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 5 digit number with 3 decimals'''
self.parse_0(number*1000.0, buf, start, StartOnHiNibble, numbytes)
def read(self,buf):
nbuf=[0]
nbuf[0]=buf[0]
self._WindspeedFormat = (nbuf[0][4] >> 4) & 0xF
self._RainFormat = (nbuf[0][4] >> 3) & 1
self._PressureFormat = (nbuf[0][4] >> 2) & 1
self._TemperatureFormat = (nbuf[0][4] >> 1) & 1
self._ClockMode = nbuf[0][4] & 1
self._StormThreshold = (nbuf[0][5] >> 4) & 0xF
self._WeatherThreshold = nbuf[0][5] & 0xF
self._LowBatFlags = (nbuf[0][6] >> 4) & 0xF
self._LCDContrast = nbuf[0][6] & 0xF
self._WindDirAlarmFlags = (nbuf[0][7] << 8) | nbuf[0][8]
self._OtherAlarmFlags = (nbuf[0][9] << 8) | nbuf[0][10]
self._TempIndoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 11, 1)
self._TempIndoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 13, 0)
self._TempOutdoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 16, 1)
self._TempOutdoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 18, 0)
self._HumidityIndoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 21, 1)
self._HumidityIndoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 22, 1)
self._HumidityOutdoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 23, 1)
self._HumidityOutdoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 24, 1)
self._Rain24HMax._Max._Value = USBHardware.toRain_7_3(nbuf, 25, 0)
self._HistoryInterval = nbuf[0][29]
self._GustMax._Max._Value = USBHardware.toWindspeed_6_2(nbuf, 30)
(self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Value) = USBHardware.readPressureShared(nbuf, 33, 1)
(self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Value) = USBHardware.readPressureShared(nbuf, 38, 1)
self._ResetMinMaxFlags = (nbuf[0][43]) <<16 | (nbuf[0][44] << 8) | (nbuf[0][45])
self._InBufCS = (nbuf[0][46] << 8) | nbuf[0][47]
self._OutBufCS = calc_checksum(buf, 4, end=39) + 7
"""
Reset DewpointMax 80 00 00
Reset DewpointMin 40 00 00
not used 20 00 00
Reset WindchillMin* 10 00 00 *dateTime only; Min._Value is preserved
Reset TempOutMax 08 00 00
Reset TempOutMin 04 00 00
Reset TempInMax 02 00 00
Reset TempInMin 01 00 00
Reset Gust 00 80 00
not used 00 40 00
not used 00 20 00
not used 00 10 00
Reset HumOutMax 00 08 00
Reset HumOutMin 00 04 00
Reset HumInMax 00 02 00
Reset HumInMin 00 01 00
not used 00 00 80
Reset Rain Total 00 00 40
Reset last month? 00 00 20
Reset last week? 00 00 10
Reset Rain24H 00 00 08
Reset Rain1H 00 00 04
Reset PresRelMax 00 00 02
Reset PresRelMin 00 00 01
"""
#self._ResetMinMaxFlags = 0x000000
#logdbg('set _ResetMinMaxFlags to %06x' % self._ResetMinMaxFlags)
"""
setTemps(self,TempFormat,InTempLo,InTempHi,OutTempLo,OutTempHi)
setHums(self,InHumLo,InHumHi,OutHumLo,OutHumHi)
setPresRels(self,PressureFormat,PresRelhPaLo,PresRelhPaHi,PresRelinHgLo,PresRelinHgHi)
setGust(self,WindSpeedFormat,GustHi)
setRain24H(self,RainFormat,Rain24hHi)
"""
# Examples:
#self.setTemps(ETemperatureFormat.tfCelsius,1.0,41.0,2.0,42.0)
#self.setHums(41,71,42,72)
#self.setPresRels(EPressureFormat.pfHPa,960.1,1040.1,28.36,30.72)
#self.setGust(EWindspeedFormat.wfKmh,040.0)
#self.setRain24H(ERainFormat.rfMm,50.0)
# Set historyInterval to 5 minutes (default: 2 hours)
self._HistoryInterval = EHistoryInterval.hi05Min
# Clear all alarm flags, otherwise the datastream from the weather
# station will pause during an alarm and connection will be lost.
self._WindDirAlarmFlags = 0x0000
self._OtherAlarmFlags = 0x0000
def testConfigChanged(self,buf):
nbuf = [0]
nbuf[0] = buf[0]
nbuf[0][0] = 16*(self._WindspeedFormat & 0xF) + 8*(self._RainFormat & 1) + 4*(self._PressureFormat & 1) + 2*(self._TemperatureFormat & 1) + (self._ClockMode & 1)
nbuf[0][1] = self._WeatherThreshold & 0xF | 16 * self._StormThreshold & 0xF0
nbuf[0][2] = self._LCDContrast & 0xF | 16 * self._LowBatFlags & 0xF0
nbuf[0][3] = (self._OtherAlarmFlags >> 0) & 0xFF
nbuf[0][4] = (self._OtherAlarmFlags >> 8) & 0xFF
nbuf[0][5] = (self._WindDirAlarmFlags >> 0) & 0xFF
nbuf[0][6] = (self._WindDirAlarmFlags >> 8) & 0xFF
# reverse buf from here
self.parse_2(self._PressureRelative_inHgMinMax._Max._Value, nbuf, 7, 1, 5)
self.parse_1(self._PressureRelative_hPaMinMax._Max._Value, nbuf, 9, 0, 5)
self.parse_2(self._PressureRelative_inHgMinMax._Min._Value, nbuf, 12, 1, 5)
self.parse_1(self._PressureRelative_hPaMinMax._Min._Value, nbuf, 14, 0, 5)
self.parseWind_6(self._GustMax._Max._Value, nbuf, 17)
nbuf[0][20] = self._HistoryInterval & 0xF
self.parseRain_3(self._Rain24HMax._Max._Value, nbuf, 21, 0, 7)
self.parse_0(self._HumidityOutdoorMinMax._Max._Value, nbuf, 25, 1, 2)
self.parse_0(self._HumidityOutdoorMinMax._Min._Value, nbuf, 26, 1, 2)
self.parse_0(self._HumidityIndoorMinMax._Max._Value, nbuf, 27, 1, 2)
self.parse_0(self._HumidityIndoorMinMax._Min._Value, nbuf, 28, 1, 2)
self.parse_3(self._TempOutdoorMinMax._Max._Value + CWeatherTraits.TemperatureOffset(), nbuf, 29, 1, 5)
self.parse_3(self._TempOutdoorMinMax._Min._Value + CWeatherTraits.TemperatureOffset(), nbuf, 31, 0, 5)
self.parse_3(self._TempIndoorMinMax._Max._Value + CWeatherTraits.TemperatureOffset(), nbuf, 34, 1, 5)
self.parse_3(self._TempIndoorMinMax._Min._Value + CWeatherTraits.TemperatureOffset(), nbuf, 36, 0, 5)
# reverse buf to here
USBHardware.reverseByteOrder(nbuf, 7, 32)
# do not include the ResetMinMaxFlags bytes when calculating checksum
nbuf[0][39] = (self._ResetMinMaxFlags >> 16) & 0xFF
nbuf[0][40] = (self._ResetMinMaxFlags >> 8) & 0xFF
nbuf[0][41] = (self._ResetMinMaxFlags >> 0) & 0xFF
self._OutBufCS = calc_checksum(nbuf, 0, end=39) + 7
nbuf[0][42] = (self._OutBufCS >> 8) & 0xFF
nbuf[0][43] = (self._OutBufCS >> 0) & 0xFF
buf[0] = nbuf[0]
if self._OutBufCS == self._InBufCS and self._ResetMinMaxFlags == 0:
if DEBUG_CONFIG_DATA > 2:
logdbg('testConfigChanged: checksum not changed: OutBufCS=%04x' % self._OutBufCS)
changed = 0
else:
if DEBUG_CONFIG_DATA > 0:
logdbg('testConfigChanged: checksum or resetMinMaxFlags changed: OutBufCS=%04x InBufCS=%04x _ResetMinMaxFlags=%06x' % (self._OutBufCS, self._InBufCS, self._ResetMinMaxFlags))
if DEBUG_CONFIG_DATA > 1:
self.toLog()
changed = 1
return changed
def toLog(self):
logdbg('OutBufCS= %04x' % self._OutBufCS)
logdbg('InBufCS= %04x' % self._InBufCS)
logdbg('ClockMode= %s' % self._ClockMode)
logdbg('TemperatureFormat= %s' % self._TemperatureFormat)
logdbg('PressureFormat= %s' % self._PressureFormat)
logdbg('RainFormat= %s' % self._RainFormat)
logdbg('WindspeedFormat= %s' % self._WindspeedFormat)
logdbg('WeatherThreshold= %s' % self._WeatherThreshold)
logdbg('StormThreshold= %s' % self._StormThreshold)
logdbg('LCDContrast= %s' % self._LCDContrast)
logdbg('LowBatFlags= %01x' % self._LowBatFlags)
logdbg('WindDirAlarmFlags= %04x' % self._WindDirAlarmFlags)
logdbg('OtherAlarmFlags= %04x' % self._OtherAlarmFlags)
logdbg('HistoryInterval= %s' % self._HistoryInterval)
logdbg('TempIndoor_Min= %s' % self._TempIndoorMinMax._Min._Value)
logdbg('TempIndoor_Max= %s' % self._TempIndoorMinMax._Max._Value)
logdbg('TempOutdoor_Min= %s' % self._TempOutdoorMinMax._Min._Value)
logdbg('TempOutdoor_Max= %s' % self._TempOutdoorMinMax._Max._Value)
logdbg('HumidityIndoor_Min= %s' % self._HumidityIndoorMinMax._Min._Value)
logdbg('HumidityIndoor_Max= %s' % self._HumidityIndoorMinMax._Max._Value)
logdbg('HumidityOutdoor_Min= %s' % self._HumidityOutdoorMinMax._Min._Value)
logdbg('HumidityOutdoor_Max= %s' % self._HumidityOutdoorMinMax._Max._Value)
logdbg('Rain24HMax= %s' % self._Rain24HMax._Max._Value)
logdbg('GustMax= %s' % self._GustMax._Max._Value)
logdbg('PressureRel_hPa_Min= %s' % self._PressureRelative_hPaMinMax._Min._Value)
logdbg('PressureRel_inHg_Min= %s' % self._PressureRelative_inHgMinMax._Min._Value)
logdbg('PressureRel_hPa_Max= %s' % self._PressureRelative_hPaMinMax._Max._Value)
logdbg('PressureRel_inHg_Max= %s' % self._PressureRelative_inHgMinMax._Max._Value)
logdbg('ResetMinMaxFlags= %06x (Output only)' % self._ResetMinMaxFlags)
def asDict(self):
return {
'checksum_in': self._InBufCS,
'checksum_out': self._OutBufCS,
'format_clock': self._ClockMode,
'format_temperature': self._TemperatureFormat,
'format_pressure': self._PressureFormat,
'format_rain': self._RainFormat,
'format_windspeed': self._WindspeedFormat,
'threshold_weather': self._WeatherThreshold,
'threshold_storm': self._StormThreshold,
'lcd_contrast': self._LCDContrast,
'low_battery_flags': self._LowBatFlags,
'alarm_flags_wind_dir': self._WindDirAlarmFlags,
'alarm_flags_other': self._OtherAlarmFlags,
# 'reset_minmax_flags': self._ResetMinMaxFlags,
'history_interval': self._HistoryInterval,
'indoor_temp_min': self._TempIndoorMinMax._Min._Value,
'indoor_temp_min_time': self._TempIndoorMinMax._Min._Time,
'indoor_temp_max': self._TempIndoorMinMax._Max._Value,
'indoor_temp_max_time': self._TempIndoorMinMax._Max._Time,
'indoor_humidity_min': self._HumidityIndoorMinMax._Min._Value,
'indoor_humidity_min_time': self._HumidityIndoorMinMax._Min._Time,
'indoor_humidity_max': self._HumidityIndoorMinMax._Max._Value,
'indoor_humidity_max_time': self._HumidityIndoorMinMax._Max._Time,
'outdoor_temp_min': self._TempOutdoorMinMax._Min._Value,
'outdoor_temp_min_time': self._TempOutdoorMinMax._Min._Time,
'outdoor_temp_max': self._TempOutdoorMinMax._Max._Value,
'outdoor_temp_max_time': self._TempOutdoorMinMax._Max._Time,
'outdoor_humidity_min': self._HumidityOutdoorMinMax._Min._Value,
'outdoor_humidity_min_time':self._HumidityOutdoorMinMax._Min._Time,
'outdoor_humidity_max': self._HumidityOutdoorMinMax._Max._Value,
'outdoor_humidity_max_time':self._HumidityOutdoorMinMax._Max._Time,
'rain_24h_max': self._Rain24HMax._Max._Value,
'rain_24h_max_time': self._Rain24HMax._Max._Time,
'wind_gust_max': self._GustMax._Max._Value,
'wind_gust_max_time': self._GustMax._Max._Time,
'pressure_min': self._PressureRelative_hPaMinMax._Min._Value,
'pressure_min_time': self._PressureRelative_hPaMinMax._Min._Time,
'pressure_max': self._PressureRelative_hPaMinMax._Max._Value,
'pressure_max_time': self._PressureRelative_hPaMinMax._Max._Time
# do not bother with pressure inHg
}
class CHistoryData(object):
def __init__(self):
self.Time = None
self.TempIndoor = CWeatherTraits.TemperatureNP()
self.HumidityIndoor = CWeatherTraits.HumidityNP()
self.TempOutdoor = CWeatherTraits.TemperatureNP()
self.HumidityOutdoor = CWeatherTraits.HumidityNP()
self.PressureRelative = None
self.RainCounterRaw = 0
self.WindSpeed = CWeatherTraits.WindNP()
self.WindDirection = EWindDirection.wdNone
self.Gust = CWeatherTraits.WindNP()
self.GustDirection = EWindDirection.wdNone
def read(self, buf):
nbuf = [0]
nbuf[0] = buf[0]
self.Gust = USBHardware.toWindspeed_3_1(nbuf, 12, 0)
self.GustDirection = (nbuf[0][14] >> 4) & 0xF
self.WindSpeed = USBHardware.toWindspeed_3_1(nbuf, 14, 0)
self.WindDirection = (nbuf[0][14] >> 4) & 0xF
self.RainCounterRaw = USBHardware.toRain_3_1(nbuf, 16, 1)
self.HumidityOutdoor = USBHardware.toHumidity_2_0(nbuf, 17, 0)
self.HumidityIndoor = USBHardware.toHumidity_2_0(nbuf, 18, 0)
self.PressureRelative = USBHardware.toPressure_hPa_5_1(nbuf, 19, 0)
self.TempIndoor = USBHardware.toTemperature_3_1(nbuf, 23, 0)
self.TempOutdoor = USBHardware.toTemperature_3_1(nbuf, 22, 1)
self.Time = USBHardware.toDateTime(nbuf, 25, 1, 'HistoryData')
def toLog(self):
"""emit raw historical data"""
logdbg("Time %s" % self.Time)
logdbg("TempIndoor= %7.1f" % self.TempIndoor)
logdbg("HumidityIndoor= %7.0f" % self.HumidityIndoor)
logdbg("TempOutdoor= %7.1f" % self.TempOutdoor)
logdbg("HumidityOutdoor= %7.0f" % self.HumidityOutdoor)
logdbg("PressureRelative= %7.1f" % self.PressureRelative)
logdbg("RainCounterRaw= %7.3f" % self.RainCounterRaw)
logdbg("WindSpeed= %7.3f" % self.WindSpeed)
logdbg("WindDirection= % 3s" % CWeatherTraits.windDirMap[self.WindDirection])
logdbg("Gust= %7.3f" % self.Gust)
logdbg("GustDirection= % 3s" % CWeatherTraits.windDirMap[self.GustDirection])
def asDict(self):
"""emit historical data as a dict with weewx conventions"""
return {
'dateTime': tstr_to_ts(str(self.Time)),
'inTemp': self.TempIndoor,
'inHumidity': self.HumidityIndoor,
'outTemp': self.TempOutdoor,
'outHumidity': self.HumidityOutdoor,
'pressure': self.PressureRelative,
'rain': self.RainCounterRaw / 10, # weewx wants cm
'windSpeed': self.WindSpeed,
'windDir': getWindDir(self.WindDirection, self.WindSpeed),
'windGust': self.Gust,
'windGustDir': getWindDir(self.GustDirection, self.Gust),
}
class HistoryCache:
def __init__(self):
self.clear_records()
def clear_records(self):
self.since_ts = 0
self.num_rec = 0
self.start_index = None
self.next_index = None
self.records = []
self.num_outstanding_records = None
self.num_scanned = 0
self.last_ts = 0
class CDataStore(object):
class TTransceiverSettings(object):
def __init__(self):
self.VendorId = 0x6666
self.ProductId = 0x5555
self.VersionNo = 1
self.manufacturer = "LA CROSSE TECHNOLOGY"
self.product = "Weather Direct Light Wireless Device"
self.FrequencyStandard = EFrequency.fsUS
self.Frequency = getFrequency(self.FrequencyStandard)
self.SerialNumber = None
self.DeviceID = None
class TLastStat(object):
def __init__(self):
self.LastBatteryStatus = None
self.LastLinkQuality = None
self.LastHistoryIndex = None
self.LatestHistoryIndex = None
self.last_seen_ts = None
self.last_weather_ts = 0
self.last_history_ts = 0
self.last_config_ts = 0
def __init__(self):
self.transceiverPresent = False
self.commModeInterval = 3
self.registeredDeviceID = None
self.LastStat = CDataStore.TLastStat()
self.TransceiverSettings = CDataStore.TTransceiverSettings()
self.StationConfig = CWeatherStationConfig()
self.CurrentWeather = CCurrentWeatherData()
def getFrequencyStandard(self):
return self.TransceiverSettings.FrequencyStandard
def setFrequencyStandard(self, val):
logdbg('setFrequency: %s' % val)
self.TransceiverSettings.FrequencyStandard = val
self.TransceiverSettings.Frequency = getFrequency(val)
def getDeviceID(self):
return self.TransceiverSettings.DeviceID
def setDeviceID(self,val):
logdbg("setDeviceID: %04x" % val)
self.TransceiverSettings.DeviceID = val
def getRegisteredDeviceID(self):
return self.registeredDeviceID
def setRegisteredDeviceID(self, val):
if val != self.registeredDeviceID:
loginf("console is paired to device with ID %04x" % val)
self.registeredDeviceID = val
def getTransceiverPresent(self):
return self.transceiverPresent
def setTransceiverPresent(self, val):
self.transceiverPresent = val
def setLastStatCache(self, seen_ts=None,
quality=None, battery=None,
weather_ts=None,
history_ts=None,
config_ts=None):
if DEBUG_COMM > 1:
logdbg('setLastStatCache: seen=%s quality=%s battery=%s weather=%s history=%s config=%s' %
(seen_ts, quality, battery, weather_ts, history_ts, config_ts))
if seen_ts is not None:
self.LastStat.last_seen_ts = seen_ts
if quality is not None:
self.LastStat.LastLinkQuality = quality
if battery is not None:
self.LastStat.LastBatteryStatus = battery
if weather_ts is not None:
self.LastStat.last_weather_ts = weather_ts
if history_ts is not None:
self.LastStat.last_history_ts = history_ts
if config_ts is not None:
self.LastStat.last_config_ts = config_ts
def setLastHistoryIndex(self,val):
self.LastStat.LastHistoryIndex = val
def getLastHistoryIndex(self):
return self.LastStat.LastHistoryIndex
def setLatestHistoryIndex(self,val):
self.LastStat.LatestHistoryIndex = val
def getLatestHistoryIndex(self):
return self.LastStat.LatestHistoryIndex
def setCurrentWeather(self, data):
self.CurrentWeather = data
def getDeviceRegistered(self):
if ( self.registeredDeviceID is None
or self.TransceiverSettings.DeviceID is None
or self.registeredDeviceID != self.TransceiverSettings.DeviceID ):
return False
return True
def getCommModeInterval(self):
return self.commModeInterval
def setCommModeInterval(self,val):
logdbg("setCommModeInterval to %x" % val)
self.commModeInterval = val
def setTransceiverSerNo(self,val):
logdbg("setTransceiverSerialNumber to %s" % val)
self.TransceiverSettings.SerialNumber = val
def getTransceiverSerNo(self):
return self.TransceiverSettings.SerialNumber
class sHID(object):
"""USB driver abstraction"""
def __init__(self):
self.devh = None
self.timeout = 1000
self.last_dump = None
def open(self, vid, pid, did, serial):
device = self._find_device(vid, pid, did, serial)
if device is None:
logcrt('Cannot find USB device with Vendor=0x%04x ProdID=0x%04x Device=%s Serial=%s' % (vid, pid, did, serial))
raise weewx.WeeWxIOError('Unable to find transceiver on USB')
self._open_device(device)
def close(self):
self._close_device()
def _find_device(self, vid, pid, did, serial):
for bus in usb.busses():
for dev in bus.devices:
if dev.idVendor == vid and dev.idProduct == pid:
if did is None or dev.filename == did:
if serial is None:
loginf('found transceiver at bus=%s device=%s' %
(bus.dirname, dev.filename))
return dev
else:
handle = dev.open()
try:
buf = self.readCfg(handle, 0x1F9, 7)
sn = str("%02d" % (buf[0]))
sn += str("%02d" % (buf[1]))
sn += str("%02d" % (buf[2]))
sn += str("%02d" % (buf[3]))
sn += str("%02d" % (buf[4]))
sn += str("%02d" % (buf[5]))
sn += str("%02d" % (buf[6]))
if str(serial) == sn:
loginf('found transceiver at bus=%s device=%s serial=%s' % (bus.dirname, dev.filename, sn))
return dev
else:
loginf('skipping transceiver with serial %s (looking for %s)' % (sn, serial))
finally:
del handle
return None
def _open_device(self, dev, interface=0):
self.devh = dev.open()
if not self.devh:
raise weewx.WeeWxIOError('Open USB device failed')
loginf('manufacturer: %s' % self.devh.getString(dev.iManufacturer,30))
loginf('product: %s' % self.devh.getString(dev.iProduct,30))
loginf('interface: %d' % interface)
# be sure kernel does not claim the interface
try:
self.devh.detachKernelDriver(interface)
except Exception:
pass
# attempt to claim the interface
try:
logdbg('claiming USB interface %d' % interface)
self.devh.claimInterface(interface)
self.devh.setAltInterface(interface)
except usb.USBError, e:
self._close_device()
logcrt('Unable to claim USB interface %s: %s' % (interface, e))
raise weewx.WeeWxIOError(e)
# FIXME: this seems to be specific to ws28xx?
# FIXME: check return values
usbWait = 0.05
self.devh.getDescriptor(0x1, 0, 0x12)
time.sleep(usbWait)
self.devh.getDescriptor(0x2, 0, 0x9)
time.sleep(usbWait)
self.devh.getDescriptor(0x2, 0, 0x22)
time.sleep(usbWait)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
0xa, [], 0x0, 0x0, 1000)
time.sleep(usbWait)
self.devh.getDescriptor(0x22, 0, 0x2a9)
time.sleep(usbWait)
def _close_device(self):
try:
logdbg('releasing USB interface')
self.devh.releaseInterface()
except Exception:
pass
self.devh = None
def setTX(self):
buf = [0]*0x15
buf[0] = 0xD1
if DEBUG_COMM > 1:
self.dump('setTX', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d1,
index=0x0000000,
timeout=self.timeout)
def setRX(self):
buf = [0]*0x15
buf[0] = 0xD0
if DEBUG_COMM > 1:
self.dump('setRX', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d0,
index=0x0000000,
timeout=self.timeout)
def getState(self,StateBuffer):
buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS |
usb.RECIP_INTERFACE | usb.ENDPOINT_IN,
request=usb.REQ_CLEAR_FEATURE,
buffer=0x0a,
value=0x00003de,
index=0x0000000,
timeout=self.timeout)
if DEBUG_COMM > 1:
self.dump('getState', buf, fmt=DEBUG_DUMP_FORMAT)
StateBuffer[0]=[0]*0x2
StateBuffer[0][0]=buf[1]
StateBuffer[0][1]=buf[2]
def readConfigFlash(self, addr, numBytes, data):
if numBytes > 512:
raise Exception('bad number of bytes')
while numBytes:
buf=[0xcc]*0x0f #0x15
buf[0] = 0xdd
buf[1] = 0x0a
buf[2] = (addr >>8) & 0xFF
buf[3] = (addr >>0) & 0xFF
if DEBUG_COMM > 1:
self.dump('readCfgFlash>', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003dd,
index=0x0000000,
timeout=self.timeout)
buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS |
usb.RECIP_INTERFACE |
usb.ENDPOINT_IN,
request=usb.REQ_CLEAR_FEATURE,
buffer=0x15,
value=0x00003dc,
index=0x0000000,
timeout=self.timeout)
new_data=[0]*0x15
if numBytes < 16:
for i in xrange(0, numBytes):
new_data[i] = buf[i+4]
numBytes = 0
else:
for i in xrange(0, 16):
new_data[i] = buf[i+4]
numBytes -= 16
addr += 16
if DEBUG_COMM > 1:
self.dump('readCfgFlash<', buf, fmt=DEBUG_DUMP_FORMAT)
data[0] = new_data # FIXME: new_data might be unset
def setState(self,state):
buf = [0]*0x15
buf[0] = 0xd7
buf[1] = state
if DEBUG_COMM > 1:
self.dump('setState', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d7,
index=0x0000000,
timeout=self.timeout)
def setFrame(self,data,numBytes):
buf = [0]*0x111
buf[0] = 0xd5
buf[1] = numBytes >> 8
buf[2] = numBytes
for i in xrange(0, numBytes):
buf[i+3] = data[i]
if DEBUG_COMM == 1:
self.dump('setFrame', buf, 'short')
elif DEBUG_COMM > 1:
self.dump('setFrame', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d5,
index=0x0000000,
timeout=self.timeout)
def getFrame(self,data,numBytes):
buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS |
usb.RECIP_INTERFACE |
usb.ENDPOINT_IN,
request=usb.REQ_CLEAR_FEATURE,
buffer=0x111,
value=0x00003d6,
index=0x0000000,
timeout=self.timeout)
new_data=[0]*0x131
new_numBytes=(buf[1] << 8 | buf[2])& 0x1ff
for i in xrange(0, new_numBytes):
new_data[i] = buf[i+3]
if DEBUG_COMM == 1:
self.dump('getFrame', buf, 'short')
elif DEBUG_COMM > 1:
self.dump('getFrame', buf, fmt=DEBUG_DUMP_FORMAT)
data[0] = new_data
numBytes[0] = new_numBytes
def writeReg(self,regAddr,data):
buf = [0]*0x05
buf[0] = 0xf0
buf[1] = regAddr & 0x7F
buf[2] = 0x01
buf[3] = data
buf[4] = 0x00
if DEBUG_COMM > 1:
self.dump('writeReg', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003f0,
index=0x0000000,
timeout=self.timeout)
def execute(self, command):
buf = [0]*0x0f #*0x15
buf[0] = 0xd9
buf[1] = command
if DEBUG_COMM > 1:
self.dump('execute', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d9,
index=0x0000000,
timeout=self.timeout)
def setPreamblePattern(self,pattern):
buf = [0]*0x15
buf[0] = 0xd8
buf[1] = pattern
if DEBUG_COMM > 1:
self.dump('setPreamble', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d8,
index=0x0000000,
timeout=self.timeout)
# three formats, long, short, auto. short shows only the first 16 bytes.
# long shows the full length of the buffer. auto shows the message length
# as indicated by the length in the message itself for setFrame and
# getFrame, or the first 16 bytes for any other message.
def dump(self, cmd, buf, fmt='auto'):
strbuf = ''
msglen = None
if fmt == 'auto':
if buf[0] in [0xd5, 0x00]:
msglen = buf[2] + 3 # use msg length for set/get frame
else:
msglen = 16 # otherwise do same as short format
elif fmt == 'short':
msglen = 16
for i,x in enumerate(buf):
strbuf += str('%02x ' % x)
if (i+1) % 16 == 0:
self.dumpstr(cmd, strbuf)
strbuf = ''
if msglen is not None and i+1 >= msglen:
break
if strbuf:
self.dumpstr(cmd, strbuf)
# filter output that we do not care about, pad the command string.
def dumpstr(self, cmd, strbuf):
pad = ' ' * (15-len(cmd))
# de15 is idle, de14 is intermediate
if strbuf in ['de 15 00 00 00 00 ','de 14 00 00 00 00 ']:
if strbuf != self.last_dump or DEBUG_COMM > 2:
logdbg('%s: %s%s' % (cmd, pad, strbuf))
self.last_dump = strbuf
else:
logdbg('%s: %s%s' % (cmd, pad, strbuf))
self.last_dump = None
def readCfg(self, handle, addr, numBytes):
while numBytes:
buf=[0xcc]*0x0f #0x15
buf[0] = 0xdd
buf[1] = 0x0a
buf[2] = (addr >>8) & 0xFF
buf[3] = (addr >>0) & 0xFF
handle.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003dd,
index=0x0000000,
timeout=1000)
buf = handle.controlMsg(requestType=usb.TYPE_CLASS |
usb.RECIP_INTERFACE | usb.ENDPOINT_IN,
request=usb.REQ_CLEAR_FEATURE,
buffer=0x15,
value=0x00003dc,
index=0x0000000,
timeout=1000)
new_data=[0]*0x15
if numBytes < 16:
for i in xrange(0, numBytes):
new_data[i] = buf[i+4]
numBytes = 0
else:
for i in xrange(0, 16):
new_data[i] = buf[i+4]
numBytes -= 16
addr += 16
return new_data
class CCommunicationService(object):
reg_names = dict()
class AX5051RegisterNames:
REVISION = 0x0
SCRATCH = 0x1
POWERMODE = 0x2
XTALOSC = 0x3
FIFOCTRL = 0x4
FIFODATA = 0x5
IRQMASK = 0x6
IFMODE = 0x8
PINCFG1 = 0x0C
PINCFG2 = 0x0D
MODULATION = 0x10
ENCODING = 0x11
FRAMING = 0x12
CRCINIT3 = 0x14
CRCINIT2 = 0x15
CRCINIT1 = 0x16
CRCINIT0 = 0x17
FREQ3 = 0x20
FREQ2 = 0x21
FREQ1 = 0x22
FREQ0 = 0x23
FSKDEV2 = 0x25
FSKDEV1 = 0x26
FSKDEV0 = 0x27
IFFREQHI = 0x28
IFFREQLO = 0x29
PLLLOOP = 0x2C
PLLRANGING = 0x2D
PLLRNGCLK = 0x2E
TXPWR = 0x30
TXRATEHI = 0x31
TXRATEMID = 0x32
TXRATELO = 0x33
MODMISC = 0x34
FIFOCONTROL2 = 0x37
ADCMISC = 0x38
AGCTARGET = 0x39
AGCATTACK = 0x3A
AGCDECAY = 0x3B
AGCCOUNTER = 0x3C
CICDEC = 0x3F
DATARATEHI = 0x40
DATARATELO = 0x41
TMGGAINHI = 0x42
TMGGAINLO = 0x43
PHASEGAIN = 0x44
FREQGAIN = 0x45
FREQGAIN2 = 0x46
AMPLGAIN = 0x47
TRKFREQHI = 0x4C
TRKFREQLO = 0x4D
XTALCAP = 0x4F
SPAREOUT = 0x60
TESTOBS = 0x68
APEOVER = 0x70
TMMUX = 0x71
PLLVCOI = 0x72
PLLCPEN = 0x73
PLLRNGMISC = 0x74
AGCMANUAL = 0x78
ADCDCLEVEL = 0x79
RFMISC = 0x7A
TXDRIVER = 0x7B
REF = 0x7C
RXMISC = 0x7D
def __init__(self):
logdbg('CCommunicationService.init')
self.shid = sHID()
self.DataStore = CDataStore()
self.firstSleep = 1
self.nextSleep = 1
self.pollCount = 0
self.running = False
self.child = None
self.thread_wait = 60.0 # seconds
self.command = None
self.history_cache = HistoryCache()
# do not set time when offset to whole hour is <= _a3_offset
self._a3_offset = 3
def buildFirstConfigFrame(self, Buffer, cs):
logdbg('buildFirstConfigFrame: cs=%04x' % cs)
newBuffer = [0]
newBuffer[0] = [0]*9
comInt = self.DataStore.getCommModeInterval()
historyAddress = 0xFFFFFF
newBuffer[0][0] = 0xf0
newBuffer[0][1] = 0xf0
newBuffer[0][2] = EAction.aGetConfig
newBuffer[0][3] = (cs >> 8) & 0xff
newBuffer[0][4] = (cs >> 0) & 0xff
newBuffer[0][5] = (comInt >> 4) & 0xff
newBuffer[0][6] = (historyAddress >> 16) & 0x0f | 16 * (comInt & 0xf)
newBuffer[0][7] = (historyAddress >> 8 ) & 0xff
newBuffer[0][8] = (historyAddress >> 0 ) & 0xff
Buffer[0] = newBuffer[0]
Length = 0x09
return Length
def buildConfigFrame(self, Buffer):
logdbg("buildConfigFrame")
newBuffer = [0]
newBuffer[0] = [0]*48
cfgBuffer = [0]
cfgBuffer[0] = [0]*44
changed = self.DataStore.StationConfig.testConfigChanged(cfgBuffer)
if changed:
self.shid.dump('OutBuf', cfgBuffer[0], fmt='long')
newBuffer[0][0] = Buffer[0][0]
newBuffer[0][1] = Buffer[0][1]
newBuffer[0][2] = EAction.aSendConfig # 0x40 # change this value if we won't store config
newBuffer[0][3] = Buffer[0][3]
for i in xrange(0,44):
newBuffer[0][i+4] = cfgBuffer[0][i]
Buffer[0] = newBuffer[0]
Length = 48 # 0x30
else: # current config not up to date; do not write yet
Length = 0
return Length
def buildTimeFrame(self, Buffer, cs):
logdbg("buildTimeFrame: cs=%04x" % cs)
now = time.time()
tm = time.localtime(now)
newBuffer=[0]
newBuffer[0]=Buffer[0]
#00000000: d5 00 0c 00 32 c0 00 8f 45 25 15 91 31 20 01 00
#00000000: d5 00 0c 00 32 c0 06 c1 47 25 15 91 31 20 01 00
# 3 4 5 6 7 8 9 10 11
newBuffer[0][2] = EAction.aSendTime # 0xc0
newBuffer[0][3] = (cs >> 8) & 0xFF
newBuffer[0][4] = (cs >> 0) & 0xFF
newBuffer[0][5] = (tm[5] % 10) + 0x10 * (tm[5] // 10) #sec
newBuffer[0][6] = (tm[4] % 10) + 0x10 * (tm[4] // 10) #min
newBuffer[0][7] = (tm[3] % 10) + 0x10 * (tm[3] // 10) #hour
#DayOfWeek = tm[6] - 1; #ole from 1 - 7 - 1=Sun... 0-6 0=Sun
DayOfWeek = tm[6] #py from 0 - 6 - 0=Mon
newBuffer[0][8] = DayOfWeek % 10 + 0x10 * (tm[2] % 10) #DoW + Day
newBuffer[0][9] = (tm[2] // 10) + 0x10 * (tm[1] % 10) #day + month
newBuffer[0][10] = (tm[1] // 10) + 0x10 * ((tm[0] - 2000) % 10) #month + year
newBuffer[0][11] = (tm[0] - 2000) // 10 #year
Buffer[0]=newBuffer[0]
Length = 0x0c
return Length
def buildACKFrame(self, Buffer, action, cs, hidx=None):
if DEBUG_COMM > 1:
logdbg("buildACKFrame: action=%x cs=%04x historyIndex=%s" %
(action, cs, hidx))
newBuffer = [0]
newBuffer[0] = [0]*9
for i in xrange(0,2):
newBuffer[0][i] = Buffer[0][i]
comInt = self.DataStore.getCommModeInterval()
# When last weather is stale, change action to get current weather
# This is only needed during long periods of history data catchup
if self.command == EAction.aGetHistory:
now = int(time.time())
age = now - self.DataStore.LastStat.last_weather_ts
# Morphing action only with GetHistory requests,
# and stale data after a period of twice the CommModeInterval,
# but not with init GetHistory requests (0xF0)
if action == EAction.aGetHistory and age >= (comInt +1) * 2 and newBuffer[0][1] != 0xF0:
if DEBUG_COMM > 0:
logdbg('buildACKFrame: morphing action from %d to 5 (age=%s)' % (action, age))
action = EAction.aGetCurrent
if hidx is None:
if self.command == EAction.aGetHistory:
hidx = self.history_cache.next_index
elif self.DataStore.getLastHistoryIndex() is not None:
hidx = self.DataStore.getLastHistoryIndex()
if hidx is None or hidx < 0 or hidx >= WS28xxDriver.max_records:
haddr = 0xffffff
else:
haddr = index_to_addr(hidx)
if DEBUG_COMM > 1:
logdbg('buildACKFrame: idx: %s addr: 0x%04x' % (hidx, haddr))
newBuffer[0][2] = action & 0xF
newBuffer[0][3] = (cs >> 8) & 0xFF
newBuffer[0][4] = (cs >> 0) & 0xFF
newBuffer[0][5] = (comInt >> 4) & 0xFF
newBuffer[0][6] = (haddr >> 16) & 0x0F | 16 * (comInt & 0xF)
newBuffer[0][7] = (haddr >> 8 ) & 0xFF
newBuffer[0][8] = (haddr >> 0 ) & 0xFF
#d5 00 09 f0 f0 03 00 32 00 3f ff ff
Buffer[0]=newBuffer[0]
return 9
def handleWsAck(self,Buffer,Length):
logdbg('handleWsAck')
self.DataStore.setLastStatCache(seen_ts=int(time.time()),
quality=(Buffer[0][3] & 0x7f),
battery=(Buffer[0][2] & 0xf))
def handleConfig(self,Buffer,Length):
logdbg('handleConfig: %s' % self.timing())
if DEBUG_CONFIG_DATA > 2:
self.shid.dump('InBuf', Buffer[0], fmt='long')
newBuffer=[0]
newBuffer[0] = Buffer[0]
newLength = [0]
now = int(time.time())
self.DataStore.StationConfig.read(newBuffer)
if DEBUG_CONFIG_DATA > 1:
self.DataStore.StationConfig.toLog()
self.DataStore.setLastStatCache(seen_ts=now,
quality=(Buffer[0][3] & 0x7f),
battery=(Buffer[0][2] & 0xf),
config_ts=now)
cs = newBuffer[0][47] | (newBuffer[0][46] << 8)
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs)
Buffer[0] = newBuffer[0]
Length[0] = newLength[0]
def handleCurrentData(self,Buffer,Length):
if DEBUG_WEATHER_DATA > 0:
logdbg('handleCurrentData: %s' % self.timing())
now = int(time.time())
# update the weather data cache if changed or stale
chksum = CCurrentWeatherData.calcChecksum(Buffer)
age = now - self.DataStore.LastStat.last_weather_ts
if age >= 10 or chksum != self.DataStore.CurrentWeather.checksum():
if DEBUG_WEATHER_DATA > 2:
self.shid.dump('CurWea', Buffer[0], fmt='long')
data = CCurrentWeatherData()
data.read(Buffer)
self.DataStore.setCurrentWeather(data)
if DEBUG_WEATHER_DATA > 1:
data.toLog()
# update the connection cache
self.DataStore.setLastStatCache(seen_ts=now,
quality=(Buffer[0][3] & 0x7f),
battery=(Buffer[0][2] & 0xf),
weather_ts=now)
newBuffer = [0]
newBuffer[0] = Buffer[0]
newLength = [0]
cs = newBuffer[0][5] | (newBuffer[0][4] << 8)
cfgBuffer = [0]
cfgBuffer[0] = [0]*44
changed = self.DataStore.StationConfig.testConfigChanged(cfgBuffer)
inBufCS = self.DataStore.StationConfig.getInBufCS()
if inBufCS == 0 or inBufCS != cs:
# request for a get config
logdbg('handleCurrentData: inBufCS of station does not match')
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetConfig, cs)
elif changed:
# Request for a set config
logdbg('handleCurrentData: outBufCS of station changed')
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aReqSetConfig, cs)
else:
# Request for either a history message or a current weather message
# In general we don't use EAction.aGetCurrent to ask for a current
# weather message; they also come when requested for
# EAction.aGetHistory. This we learned from the Heavy Weather Pro
# messages (via USB sniffer).
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs)
Length[0] = newLength[0]
Buffer[0] = newBuffer[0]
def handleHistoryData(self, buf, buflen):
if DEBUG_HISTORY_DATA > 0:
logdbg('handleHistoryData: %s' % self.timing())
now = int(time.time())
self.DataStore.setLastStatCache(seen_ts=now,
quality=(buf[0][3] & 0x7f),
battery=(buf[0][2] & 0xf),
history_ts=now)
newbuf = [0]
newbuf[0] = buf[0]
newlen = [0]
data = CHistoryData()
data.read(newbuf)
if DEBUG_HISTORY_DATA > 1:
data.toLog()
cs = newbuf[0][5] | (newbuf[0][4] << 8)
latestAddr = bytes_to_addr(buf[0][6], buf[0][7], buf[0][8])
thisAddr = bytes_to_addr(buf[0][9], buf[0][10], buf[0][11])
latestIndex = addr_to_index(latestAddr)
thisIndex = addr_to_index(thisAddr)
ts = tstr_to_ts(str(data.Time))
nrec = get_index(latestIndex - thisIndex)
logdbg('handleHistoryData: time=%s'
' this=%d (0x%04x) latest=%d (0x%04x) nrec=%d' %
(data.Time, thisIndex, thisAddr, latestIndex, latestAddr, nrec))
# track the latest history index
self.DataStore.setLastHistoryIndex(thisIndex)
self.DataStore.setLatestHistoryIndex(latestIndex)
nextIndex = None
if self.command == EAction.aGetHistory:
if self.history_cache.start_index is None:
nreq = 0
if self.history_cache.num_rec > 0:
loginf('handleHistoryData: request for %s records' %
self.history_cache.num_rec)
nreq = self.history_cache.num_rec
else:
loginf('handleHistoryData: request records since %s' %
weeutil.weeutil.timestamp_to_string(self.history_cache.since_ts))
span = int(time.time()) - self.history_cache.since_ts
# FIXME: what if we do not have config data yet?
cfg = self.getConfigData().asDict()
arcint = 60 * getHistoryInterval(cfg['history_interval'])
# FIXME: this assumes a constant archive interval for all
# records in the station history
nreq = int(span / arcint) + 5 # FIXME: punt 5
if nreq > nrec:
loginf('handleHistoryData: too many records requested (%d)'
', clipping to number stored (%d)' % (nreq, nrec))
nreq = nrec
idx = get_index(latestIndex - nreq)
self.history_cache.start_index = idx
self.history_cache.next_index = idx
self.DataStore.setLastHistoryIndex(idx)
self.history_cache.num_outstanding_records = nreq
logdbg('handleHistoryData: start_index=%s'
' num_outstanding_records=%s' % (idx, nreq))
nextIndex = idx
elif self.history_cache.next_index is not None:
# thisIndex should be the next record after next_index
thisIndexTst = get_next_index(self.history_cache.next_index)
if thisIndexTst == thisIndex:
self.history_cache.num_scanned += 1
# get the next history record
if ts is not None and self.history_cache.since_ts <= ts:
# Check if two records in a row with the same ts
if self.history_cache.last_ts == ts:
logdbg('handleHistoryData: remove previous record'
' with duplicate timestamp: %s' %
weeutil.weeutil.timestamp_to_string(ts))
self.history_cache.records.pop()
self.history_cache.last_ts = ts
# append to the history
logdbg('handleHistoryData: appending history record'
' %s: %s' % (thisIndex, data.asDict()))
self.history_cache.records.append(data.asDict())
self.history_cache.num_outstanding_records = nrec
elif ts is None:
logerr('handleHistoryData: skip record: this_ts=None')
else:
logdbg('handleHistoryData: skip record: since_ts=%s this_ts=%s' % (weeutil.weeutil.timestamp_to_string(self.history_cache.since_ts), weeutil.weeutil.timestamp_to_string(ts)))
self.history_cache.next_index = thisIndex
else:
loginf('handleHistoryData: index mismatch: %s != %s' %
(thisIndexTst, thisIndex))
nextIndex = self.history_cache.next_index
logdbg('handleHistoryData: next=%s' % nextIndex)
self.setSleep(0.300,0.010)
newlen[0] = self.buildACKFrame(newbuf, EAction.aGetHistory, cs, nextIndex)
buflen[0] = newlen[0]
buf[0] = newbuf[0]
def handleNextAction(self,Buffer,Length):
newBuffer = [0]
newBuffer[0] = Buffer[0]
newLength = [0]
newLength[0] = Length[0]
self.DataStore.setLastStatCache(seen_ts=int(time.time()),
quality=(Buffer[0][3] & 0x7f))
cs = newBuffer[0][5] | (newBuffer[0][4] << 8)
if (Buffer[0][2] & 0xEF) == EResponseType.rtReqFirstConfig:
logdbg('handleNextAction: a1 (first-time config)')
self.setSleep(0.085,0.005)
newLength[0] = self.buildFirstConfigFrame(newBuffer, cs)
elif (Buffer[0][2] & 0xEF) == EResponseType.rtReqSetConfig:
logdbg('handleNextAction: a2 (set config data)')
self.setSleep(0.085,0.005)
newLength[0] = self.buildConfigFrame(newBuffer)
elif (Buffer[0][2] & 0xEF) == EResponseType.rtReqSetTime:
logdbg('handleNextAction: a3 (set time data)')
now = int(time.time())
age = now - self.DataStore.LastStat.last_weather_ts
if age >= (self.DataStore.getCommModeInterval() +1) * 2:
# always set time if init or stale communication
self.setSleep(0.085,0.005)
newLength[0] = self.buildTimeFrame(newBuffer, cs)
else:
# When time is set at the whole hour we may get an extra
# historical record with time stamp a history period ahead
# We will skip settime if offset to whole hour is too small
# (time difference between WS and server < self._a3_offset)
m, s = divmod(now, 60)
h, m = divmod(m, 60)
logdbg('Time: hh:%02d:%02d' % (m,s))
if (m == 59 and s >= (60 - self._a3_offset)) or (m == 0 and s <= self._a3_offset):
logdbg('Skip settime; time difference <= %s s' % int(self._a3_offset))
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs)
else:
# set time
self.setSleep(0.085,0.005)
newLength[0] = self.buildTimeFrame(newBuffer, cs)
else:
logdbg('handleNextAction: %02x' % (Buffer[0][2] & 0xEF))
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs)
Length[0] = newLength[0]
Buffer[0] = newBuffer[0]
def generateResponse(self, Buffer, Length):
if DEBUG_COMM > 1:
logdbg('generateResponse: %s' % self.timing())
newBuffer = [0]
newBuffer[0] = Buffer[0]
newLength = [0]
newLength[0] = Length[0]
if Length[0] == 0:
raise BadResponse('zero length buffer')
bufferID = (Buffer[0][0] <<8) | Buffer[0][1]
respType = (Buffer[0][2] & 0xE0)
if DEBUG_COMM > 1:
logdbg("generateResponse: id=%04x resp=%x length=%x" %
(bufferID, respType, Length[0]))
deviceID = self.DataStore.getDeviceID()
if bufferID != 0xF0F0:
self.DataStore.setRegisteredDeviceID(bufferID)
if bufferID == 0xF0F0:
loginf('generateResponse: console not paired, attempting to pair to 0x%04x' % deviceID)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetConfig, deviceID, 0xFFFF)
elif bufferID == deviceID:
if respType == EResponseType.rtDataWritten:
# 00000000: 00 00 06 00 32 20
if Length[0] == 0x06:
self.DataStore.StationConfig.setResetMinMaxFlags(0)
self.shid.setRX()
raise DataWritten()
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
elif respType == EResponseType.rtGetConfig:
# 00000000: 00 00 30 00 32 40
if Length[0] == 0x30:
self.handleConfig(newBuffer, newLength)
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
elif respType == EResponseType.rtGetCurrentWeather:
# 00000000: 00 00 d7 00 32 60
if Length[0] == 0xd7: #215
self.handleCurrentData(newBuffer, newLength)
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
elif respType == EResponseType.rtGetHistory:
# 00000000: 00 00 1e 00 32 80
if Length[0] == 0x1e:
self.handleHistoryData(newBuffer, newLength)
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
elif respType == EResponseType.rtRequest:
# 00000000: 00 00 06 f0 f0 a1
# 00000000: 00 00 06 00 32 a3
# 00000000: 00 00 06 00 32 a2
if Length[0] == 0x06:
self.handleNextAction(newBuffer, newLength)
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
else:
raise BadResponse('unexpected response type %x' % respType)
elif respType not in [0x20,0x40,0x60,0x80,0xa1,0xa2,0xa3]:
# message is probably corrupt
raise BadResponse('unknown response type %x' % respType)
else:
msg = 'message from console contains unknown device ID (id=%04x resp=%x)' % (bufferID, respType)
logdbg(msg)
log_frame(Length[0],Buffer[0])
raise BadResponse(msg)
Buffer[0] = newBuffer[0]
Length[0] = newLength[0]
def configureRegisterNames(self):
self.reg_names[self.AX5051RegisterNames.IFMODE] =0x00
self.reg_names[self.AX5051RegisterNames.MODULATION]=0x41 #fsk
self.reg_names[self.AX5051RegisterNames.ENCODING] =0x07
self.reg_names[self.AX5051RegisterNames.FRAMING] =0x84 #1000:0100 ##?hdlc? |1000 010 0
self.reg_names[self.AX5051RegisterNames.CRCINIT3] =0xff
self.reg_names[self.AX5051RegisterNames.CRCINIT2] =0xff
self.reg_names[self.AX5051RegisterNames.CRCINIT1] =0xff
self.reg_names[self.AX5051RegisterNames.CRCINIT0] =0xff
self.reg_names[self.AX5051RegisterNames.FREQ3] =0x38
self.reg_names[self.AX5051RegisterNames.FREQ2] =0x90
self.reg_names[self.AX5051RegisterNames.FREQ1] =0x00
self.reg_names[self.AX5051RegisterNames.FREQ0] =0x01
self.reg_names[self.AX5051RegisterNames.PLLLOOP] =0x1d
self.reg_names[self.AX5051RegisterNames.PLLRANGING]=0x08
self.reg_names[self.AX5051RegisterNames.PLLRNGCLK] =0x03
self.reg_names[self.AX5051RegisterNames.MODMISC] =0x03
self.reg_names[self.AX5051RegisterNames.SPAREOUT] =0x00
self.reg_names[self.AX5051RegisterNames.TESTOBS] =0x00
self.reg_names[self.AX5051RegisterNames.APEOVER] =0x00
self.reg_names[self.AX5051RegisterNames.TMMUX] =0x00
self.reg_names[self.AX5051RegisterNames.PLLVCOI] =0x01
self.reg_names[self.AX5051RegisterNames.PLLCPEN] =0x01
self.reg_names[self.AX5051RegisterNames.RFMISC] =0xb0
self.reg_names[self.AX5051RegisterNames.REF] =0x23
self.reg_names[self.AX5051RegisterNames.IFFREQHI] =0x20
self.reg_names[self.AX5051RegisterNames.IFFREQLO] =0x00
self.reg_names[self.AX5051RegisterNames.ADCMISC] =0x01
self.reg_names[self.AX5051RegisterNames.AGCTARGET] =0x0e
self.reg_names[self.AX5051RegisterNames.AGCATTACK] =0x11
self.reg_names[self.AX5051RegisterNames.AGCDECAY] =0x0e
self.reg_names[self.AX5051RegisterNames.CICDEC] =0x3f
self.reg_names[self.AX5051RegisterNames.DATARATEHI]=0x19
self.reg_names[self.AX5051RegisterNames.DATARATELO]=0x66
self.reg_names[self.AX5051RegisterNames.TMGGAINHI] =0x01
self.reg_names[self.AX5051RegisterNames.TMGGAINLO] =0x96
self.reg_names[self.AX5051RegisterNames.PHASEGAIN] =0x03
self.reg_names[self.AX5051RegisterNames.FREQGAIN] =0x04
self.reg_names[self.AX5051RegisterNames.FREQGAIN2] =0x0a
self.reg_names[self.AX5051RegisterNames.AMPLGAIN] =0x06
self.reg_names[self.AX5051RegisterNames.AGCMANUAL] =0x00
self.reg_names[self.AX5051RegisterNames.ADCDCLEVEL]=0x10
self.reg_names[self.AX5051RegisterNames.RXMISC] =0x35
self.reg_names[self.AX5051RegisterNames.FSKDEV2] =0x00
self.reg_names[self.AX5051RegisterNames.FSKDEV1] =0x31
self.reg_names[self.AX5051RegisterNames.FSKDEV0] =0x27
self.reg_names[self.AX5051RegisterNames.TXPWR] =0x03
self.reg_names[self.AX5051RegisterNames.TXRATEHI] =0x00
self.reg_names[self.AX5051RegisterNames.TXRATEMID] =0x51
self.reg_names[self.AX5051RegisterNames.TXRATELO] =0xec
self.reg_names[self.AX5051RegisterNames.TXDRIVER] =0x88
def initTransceiver(self, frequency_standard):
logdbg('initTransceiver: frequency_standard=%s' % frequency_standard)
self.DataStore.setFrequencyStandard(frequency_standard)
self.configureRegisterNames()
# calculate the frequency then set frequency registers
freq = self.DataStore.TransceiverSettings.Frequency
loginf('base frequency: %d' % freq)
freqVal = long(freq / 16000000.0 * 16777216.0)
corVec = [None]
self.shid.readConfigFlash(0x1F5, 4, corVec)
corVal = corVec[0][0] << 8
corVal |= corVec[0][1]
corVal <<= 8
corVal |= corVec[0][2]
corVal <<= 8
corVal |= corVec[0][3]
loginf('frequency correction: %d (0x%x)' % (corVal,corVal))
freqVal += corVal
if not (freqVal % 2):
freqVal += 1
loginf('adjusted frequency: %d (0x%x)' % (freqVal,freqVal))
self.reg_names[self.AX5051RegisterNames.FREQ3] = (freqVal >>24) & 0xFF
self.reg_names[self.AX5051RegisterNames.FREQ2] = (freqVal >>16) & 0xFF
self.reg_names[self.AX5051RegisterNames.FREQ1] = (freqVal >>8) & 0xFF
self.reg_names[self.AX5051RegisterNames.FREQ0] = (freqVal >>0) & 0xFF
logdbg('frequency registers: %x %x %x %x' % (
self.reg_names[self.AX5051RegisterNames.FREQ3],
self.reg_names[self.AX5051RegisterNames.FREQ2],
self.reg_names[self.AX5051RegisterNames.FREQ1],
self.reg_names[self.AX5051RegisterNames.FREQ0]))
# figure out the transceiver id
buf = [None]
self.shid.readConfigFlash(0x1F9, 7, buf)
tid = buf[0][5] << 8
tid += buf[0][6]
loginf('transceiver identifier: %d (0x%04x)' % (tid,tid))
self.DataStore.setDeviceID(tid)
# figure out the transceiver serial number
sn = str("%02d"%(buf[0][0]))
sn += str("%02d"%(buf[0][1]))
sn += str("%02d"%(buf[0][2]))
sn += str("%02d"%(buf[0][3]))
sn += str("%02d"%(buf[0][4]))
sn += str("%02d"%(buf[0][5]))
sn += str("%02d"%(buf[0][6]))
loginf('transceiver serial: %s' % sn)
self.DataStore.setTransceiverSerNo(sn)
for r in self.reg_names:
self.shid.writeReg(r, self.reg_names[r])
def setup(self, frequency_standard,
vendor_id, product_id, device_id, serial,
comm_interval=3):
self.DataStore.setCommModeInterval(comm_interval)
self.shid.open(vendor_id, product_id, device_id, serial)
self.initTransceiver(frequency_standard)
self.DataStore.setTransceiverPresent(True)
def teardown(self):
self.shid.close()
# FIXME: make this thread-safe
def getWeatherData(self):
return self.DataStore.CurrentWeather
# FIXME: make this thread-safe
def getLastStat(self):
return self.DataStore.LastStat
# FIXME: make this thread-safe
def getConfigData(self):
return self.DataStore.StationConfig
def startCachingHistory(self, since_ts=0, num_rec=0):
self.history_cache.clear_records()
if since_ts is None:
since_ts = 0
self.history_cache.since_ts = since_ts
if num_rec > WS28xxDriver.max_records - 2:
num_rec = WS28xxDriver.max_records - 2
self.history_cache.num_rec = num_rec
self.command = EAction.aGetHistory
def stopCachingHistory(self):
self.command = None
def getUncachedHistoryCount(self):
return self.history_cache.num_outstanding_records
def getNextHistoryIndex(self):
return self.history_cache.next_index
def getNumHistoryScanned(self):
return self.history_cache.num_scanned
def getLatestHistoryIndex(self):
return self.DataStore.LastStat.LatestHistoryIndex
def getHistoryCacheRecords(self):
return self.history_cache.records
def clearHistoryCache(self):
self.history_cache.clear_records()
def startRFThread(self):
if self.child is not None:
return
logdbg('startRFThread: spawning RF thread')
self.running = True
self.child = threading.Thread(target=self.doRF)
self.child.setName('RFComm')
self.child.setDaemon(True)
self.child.start()
def stopRFThread(self):
self.running = False
logdbg('stopRFThread: waiting for RF thread to terminate')
self.child.join(self.thread_wait)
if self.child.isAlive():
logerr('unable to terminate RF thread after %d seconds' %
self.thread_wait)
else:
self.child = None
def isRunning(self):
return self.running
def doRF(self):
try:
logdbg('setting up rf communication')
self.doRFSetup()
logdbg('starting rf communication')
while self.running:
self.doRFCommunication()
except Exception, e:
logerr('exception in doRF: %s' % e)
if weewx.debug:
log_traceback(dst=syslog.LOG_DEBUG)
self.running = False
raise
finally:
logdbg('stopping rf communication')
# it is probably not necessary to have two setPreamblePattern invocations.
# however, HeavyWeatherPro seems to do it this way on a first time config.
# doing it this way makes configuration easier during a factory reset and
# when re-establishing communication with the station sensors.
def doRFSetup(self):
self.shid.execute(5)
self.shid.setPreamblePattern(0xaa)
self.shid.setState(0)
time.sleep(1)
self.shid.setRX()
self.shid.setPreamblePattern(0xaa)
self.shid.setState(0x1e)
time.sleep(1)
self.shid.setRX()
self.setSleep(0.085,0.005)
def doRFCommunication(self):
time.sleep(self.firstSleep)
self.pollCount = 0
while self.running:
StateBuffer = [None]
self.shid.getState(StateBuffer)
self.pollCount += 1
if StateBuffer[0][0] == 0x16:
break
time.sleep(self.nextSleep)
else:
return
DataLength = [0]
DataLength[0] = 0
FrameBuffer=[0]
FrameBuffer[0]=[0]*0x03
self.shid.getFrame(FrameBuffer, DataLength)
try:
self.generateResponse(FrameBuffer, DataLength)
self.shid.setFrame(FrameBuffer[0], DataLength[0])
except BadResponse, e:
logerr('generateResponse failed: %s' % e)
except DataWritten, e:
logdbg('SetTime/SetConfig data written')
self.shid.setTX()
# these are for diagnostics and debugging
def setSleep(self, firstsleep, nextsleep):
self.firstSleep = firstsleep
self.nextSleep = nextsleep
def timing(self):
s = self.firstSleep + self.nextSleep * (self.pollCount - 1)
return 'sleep=%s first=%s next=%s count=%s' % (
s, self.firstSleep, self.nextSleep, self.pollCount)
| sai9/weewx-gitsvn | bin/weewx/drivers/ws28xx.py | Python | gpl-3.0 | 174,398 | 0.006061 |
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2007 Async Open Source <http://www.async.com.br>
## 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., or visit: http://www.gnu.org/.
##
## Author(s): Stoq Team <stoq-devel@async.com.br>
##
""" Implementation of classes related to till operations. """
import datetime
import gtk
from kiwi.currency import currency
from kiwi.ui.objectlist import Column, ColoredColumn
from stoqlib.api import api
from stoqlib.domain.till import TillEntry
from stoqlib.gui.search.searchdialog import SearchDialog
from stoqlib.gui.base.dialogs import run_dialog
from stoqlib.gui.editors.tilleditor import (CashAdvanceEditor, CashInEditor,
CashOutEditor)
from stoqlib.gui.stockicons import (STOQ_MONEY, STOQ_MONEY_ADD,
STOQ_MONEY_REMOVE)
from stoqlib.gui.search.searchcolumns import IdentifierColumn
from stoqlib.gui.search.searchfilters import DateSearchFilter
from stoqlib.gui.search.searchoptions import Today
from stoqlib.gui.utils.printing import print_report
from stoqlib.lib.translation import stoqlib_gettext
from stoqlib.lib.defaults import payment_value_colorize
from stoqlib.reporting.till import TillHistoryReport
_ = stoqlib_gettext
class TillHistoryDialog(SearchDialog):
size = (780, -1)
search_spec = TillEntry
selection_mode = gtk.SELECTION_MULTIPLE
searchbar_labels = _('Till Entries matching:')
title = _('Till history')
#
# SearchDialog
#
def get_columns(self, *args):
return [IdentifierColumn('identifier', title=_('Entry #'), sorted=True),
Column('date', _('Date'), data_type=datetime.date),
Column('time', _('Time'), data_type=datetime.time),
Column('description', _('Description'), data_type=str,
expand=True),
ColoredColumn('value', _('Value'), data_type=currency,
color='red', data_func=payment_value_colorize,
width=140)]
def create_filters(self):
self.set_text_field_columns(['description'])
self.date_filter = DateSearchFilter(_('Date:'))
self.date_filter.select(Today)
self.add_filter(self.date_filter, columns=['date'])
# add summary label
value_format = '<b>%s</b>'
total_label = '<b>%s</b>' % api.escape(_(u'Total:'))
self.search.set_summary_label('value', total_label, value_format)
def setup_widgets(self):
self.results.set_visible_rows(10)
self.results.connect('has-rows', self._has_rows)
self._add_editor_button(_('Cash _Add...'), CashAdvanceEditor,
STOQ_MONEY)
self._add_editor_button(_('Cash _In...'), CashInEditor,
STOQ_MONEY_ADD)
self._add_editor_button(_('Cash _Out...'), CashOutEditor,
STOQ_MONEY_REMOVE)
self.print_button = gtk.Button(None, gtk.STOCK_PRINT, True)
self.print_button.set_property("use-stock", True)
self.print_button.connect('clicked', self._print_button_clicked)
self.action_area.set_layout(gtk.BUTTONBOX_START)
self.action_area.pack_end(self.print_button, False, False, 6)
self.print_button.show()
self.print_button.set_sensitive(False)
#
# Private API
#
def _add_editor_button(self, name, editor_class, stock):
button = self.add_button(name, stock=stock)
button.connect('clicked', self._run_editor, editor_class)
button.show()
def _print_button_clicked(self, button):
print_report(TillHistoryReport, self.results, list(self.results),
filters=self.search.get_search_filters())
def _run_editor(self, button, editor_class):
with api.new_store() as store:
run_dialog(editor_class, self, store)
if store.committed:
self.search.refresh()
self.results.unselect_all()
if len(self.results):
self.results.select(self.results[-1])
def _has_rows(self, results, obj):
self.print_button.set_sensitive(obj)
| andrebellafronte/stoq | stoqlib/gui/dialogs/tillhistory.py | Python | gpl-2.0 | 4,857 | 0.003088 |
# -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from shoop.admin.form_part import FormPart, TemplatedFormDef
from shoop.core.models import Shop
from shoop.discount_pricing.models import DiscountedProductPrice
class DiscountPricingForm(forms.Form):
def __init__(self, **kwargs):
self.product = kwargs.pop("product")
super(DiscountPricingForm, self).__init__(**kwargs)
self.shops = []
if self.product:
self._build_fields()
def _build_fields(self):
self.shops = list(Shop.objects.all())
prices_by_shop_and_group = dict(
(shop_id, price)
for (shop_id, price)
in DiscountedProductPrice.objects.filter(product=self.product)
.values_list("shop_id", "price_value")
)
for shop in self.shops:
name = self._get_field_name(shop)
price = prices_by_shop_and_group.get(shop.id)
price_field = forms.DecimalField(
min_value=0, initial=price,
label=_("Price (%s)") % shop, required=False
)
self.fields[name] = price_field
def _get_field_name(self, shop):
return "s_%d" % shop.id
def _process_single_save(self, shop):
name = self._get_field_name(shop)
value = self.cleaned_data.get(name)
clear = (value is None or value < 0)
if clear:
DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete()
else:
(spp, created) = DiscountedProductPrice.objects.get_or_create(
product=self.product, shop=shop,
defaults={'price_value': value})
if not created:
spp.price_value = value
spp.save()
def save(self):
if not self.has_changed(): # No changes, so no need to do anything.
return
for shop in self.shops:
self._process_single_save(shop)
def get_shop_field(self, shop):
name = self._get_field_name(shop)
return self[name]
class DiscountPricingFormPart(FormPart):
priority = 10
def get_form_defs(self):
yield TemplatedFormDef(
name="discount_pricing",
form_class=DiscountPricingForm,
template_name="shoop/admin/discount_pricing/form_part.jinja",
required=False,
kwargs={"product": self.object}
)
def form_valid(self, form):
form["discount_pricing"].save()
| jorge-marques/shoop | shoop/discount_pricing/admin_form_part.py | Python | agpl-3.0 | 2,820 | 0.000355 |
# -*- coding:utf-8 -*-
from .inception import InceptionDao
from .models import DataMaskingRules, DataMaskingColumns
from simplejson import JSONDecodeError
import simplejson as json
import re
inceptionDao = InceptionDao()
class Masking(object):
# 脱敏数据
def data_masking(self, cluster_name, db_name, sql, sql_result):
result = {'status': 0, 'msg': 'ok', 'data': []}
# 通过inception获取语法树,并进行解析
try:
print_info = self.query_tree(sql, cluster_name, db_name)
except Exception as msg:
result['status'] = 1
result['msg'] = str(msg)
return result
if print_info is None:
result['status'] = 1
result['msg'] = 'inception返回的结果集为空!可能是SQL语句有语法错误,无法完成脱敏校验,如果需要继续查询请关闭校验'
elif print_info['errlevel'] != 0:
result['status'] = 2
result['msg'] = 'inception返回异常,无法完成脱敏校验,如果需要继续查询请关闭校验:\n' + print_info['errmsg']
else:
query_tree = print_info['query_tree']
# 获取命中脱敏规则的列数据
try:
table_hit_columns, hit_columns = self.analy_query_tree(query_tree, cluster_name)
except Exception as msg:
result['status'] = 2
result['msg'] = '解析inception语法树获取表信息出错,无法完成脱敏校验,如果需要继续查询请关闭校验:{}\nquery_tree:{}'.format(str(msg),
print_info)
return result
# 存在select * 的查询,遍历column_list,获取命中列的index,添加到hit_columns
if table_hit_columns and sql_result.get('rows'):
column_list = sql_result['column_list']
table_hit_column = {}
for column_info in table_hit_columns:
table_hit_column_info = {}
rule_type = column_info['rule_type']
table_hit_column_info[column_info['column_name']] = rule_type
table_hit_column.update(table_hit_column_info)
for index, item in enumerate(column_list):
if item in table_hit_column.keys():
column = {}
column['column_name'] = item
column['index'] = index
column['rule_type'] = table_hit_column.get(item)
hit_columns.append(column)
# 对命中规则列hit_columns的数据进行脱敏
# 获取全部脱敏规则信息,减少循环查询,提升效率
DataMaskingRulesOb = DataMaskingRules.objects.all()
if hit_columns and sql_result.get('rows'):
rows = list(sql_result['rows'])
for column in hit_columns:
index = column['index']
for idx, item in enumerate(rows):
rows[idx] = list(item)
rows[idx][index] = self.regex(DataMaskingRulesOb, column['rule_type'], rows[idx][index])
sql_result['rows'] = rows
return result
# 通过inception获取语法树
def query_tree(self, sqlContent, cluster_name, dbName):
try:
print_info = inceptionDao.query_print(sqlContent, cluster_name, dbName)
except Exception as e:
raise Exception('通过inception获取语法树异常,请检查inception配置,并确保inception可以访问实例:' + str(e))
if print_info:
id = print_info[0][0]
statement = print_info[0][1]
# 返回值为非0的情况下,说明是有错的,1表示警告,不影响执行,2表示严重错误,必须修改
errlevel = print_info[0][2]
query_tree = print_info[0][3]
errmsg = print_info[0][4]
# 提交给inception语法错误的情况
if errmsg == 'Global environment':
errlevel = 2
errmsg = 'Global environment: ' + query_tree
if errlevel == 0:
pass
# print(json.dumps(json.loads(query_tree), indent=4, sort_keys=False, ensure_ascii=False))
return {'id': id, 'statement': statement, 'errlevel': errlevel, 'query_tree': query_tree,
'errmsg': errmsg}
else:
return None
# 解析语法树,获取语句涉及的表,用于查询权限限制
def query_table_ref(self, sqlContent, cluster_name, dbName):
result = {'status': 0, 'msg': 'ok', 'data': []}
try:
print_info = self.query_tree(sqlContent, cluster_name, dbName)
except Exception as msg:
result['status'] = 1
result['msg'] = str(msg)
return result
if print_info is None:
result['status'] = 1
result['msg'] = 'inception返回的结果集为空!可能是SQL语句有语法错误,无法校验表权限,如果需要继续查询请关闭校验'
elif print_info['errlevel'] != 0:
result['status'] = 2
result['msg'] = 'inception返回异常,无法校验表权限,如果需要继续查询请关闭校验:\n' + print_info['errmsg']
else:
try:
table_ref = json.loads(print_info['query_tree'])['table_ref']
except Exception:
try:
table_ref = json.loads(print_info['query_tree'])['table_ref']
except JSONDecodeError:
try:
table_ref = json.loads(repair_json_str(print_info['query_tree']))['table_ref']
except JSONDecodeError as msg:
result['status'] = 2
result['msg'] = '通过inception语法树解析表信息出错,无法校验表权限,如果需要继续查询请关闭校验:{}\nquery_tree:{}'.format(str(msg),
print_info)
table_ref = ''
result['data'] = table_ref
return result
# 解析query_tree,获取语句信息,并返回命中脱敏规则的列信息
def analy_query_tree(self, query_tree, cluster_name):
try:
query_tree_dict = json.loads(query_tree)
except JSONDecodeError:
query_tree_dict = json.loads(repair_json_str(query_tree))
select_list = query_tree_dict.get('select_list')
table_ref = query_tree_dict.get('table_ref')
# 获取全部脱敏字段信息,减少循环查询,提升效率
DataMaskingColumnsOb = DataMaskingColumns.objects.all()
# 判断语句涉及的表是否存在脱敏字段配置
is_exist = False
for table in table_ref:
if DataMaskingColumnsOb.filter(cluster_name=cluster_name,
table_schema=table['db'],
table_name=table['table'],
active=1).exists():
is_exist = True
# 不存在脱敏字段则直接跳过规则解析
if is_exist:
# 遍历select_list
columns = []
hit_columns = [] # 命中列
table_hit_columns = [] # 涉及表命中的列,仅select *需要
# 判断是否存在不支持脱敏的语法
for select_item in select_list:
if select_item['type'] not in ('FIELD_ITEM', 'aggregate'):
raise Exception('不支持该查询语句脱敏!')
if select_item['type'] == 'aggregate':
if select_item['aggregate'].get('type') not in ('FIELD_ITEM', 'INT_ITEM'):
raise Exception('不支持该查询语句脱敏!')
# 获取select信息的规则,仅处理type为FIELD_ITEM和aggregate类型的select信息,如[*],[*,column_a],[column_a,*],[column_a,a.*,column_b],[a.*,column_a,b.*],
select_index = [
select_item['field'] if select_item['type'] == 'FIELD_ITEM' else select_item['aggregate'].get('field')
for
select_item in select_list if select_item['type'] in ('FIELD_ITEM', 'aggregate')]
# 处理select_list,为统一的{'type': 'FIELD_ITEM', 'db': 'archer_master', 'table': 'sql_users', 'field': 'email'}格式
select_list = [select_item if select_item['type'] == 'FIELD_ITEM' else select_item['aggregate'] for
select_item in select_list if select_item['type'] in ('FIELD_ITEM', 'aggregate')]
if select_index:
# 如果发现存在field='*',则遍历所有表,找出所有的命中字段
if '*' in select_index:
# 涉及表命中的列
for table in table_ref:
hit_columns_info = self.hit_table(DataMaskingColumnsOb, cluster_name, table['db'],
table['table'])
table_hit_columns.extend(hit_columns_info)
# 几种不同查询格式
# [*]
if re.match(r"^(\*,?)+$", ','.join(select_index)):
hit_columns = []
# [*,column_a]
elif re.match(r"^(\*,)+(\w,?)+$", ','.join(select_index)):
# 找出field不为* 的列信息, 循环判断列是否命中脱敏规则,并增加规则类型和index,index采取后切片
for index, item in enumerate(select_list):
item['index'] = index - len(select_list)
if item.get('field') != '*':
columns.append(item)
# [column_a, *]
elif re.match(r"^(\w,?)+(\*,?)+$", ','.join(select_index)):
# 找出field不为* 的列信息, 循环判断列是否命中脱敏规则,并增加规则类型和index,index采取前切片
for index, item in enumerate(select_list):
item['index'] = index
if item.get('field') != '*':
columns.append(item)
# [column_a,a.*,column_b]
elif re.match(r"^(\w,?)+(\*,?)+(\w,?)+$", ','.join(select_index)):
# 找出field不为* 的列信息, 循环判断列是否命中脱敏规则,并增加规则类型和index,*前面的字段index采取前切片,*后面的字段采取后切片
for index, item in enumerate(select_list):
item['index'] = index
if item.get('field') == '*':
first_idx = index
break
select_list.reverse()
for index, item in enumerate(select_list):
item['index'] = index
if item.get('field') == '*':
last_idx = len(select_list) - index - 1
break
select_list.reverse()
for index, item in enumerate(select_list):
if item.get('field') != '*' and index < first_idx:
item['index'] = index
if item.get('field') != '*' and index > last_idx:
item['index'] = index - len(select_list)
columns.append(item)
# [a.*, column_a, b.*]
else:
raise Exception('不支持select信息为[a.*, column_a, b.*]格式的查询脱敏!')
# 没有*的查询,直接遍历查询命中字段,query_tree的列index就是查询语句列的index
else:
for index, item in enumerate(select_list):
item['index'] = index
if item.get('field') != '*':
columns.append(item)
# 格式化命中的列信息
for column in columns:
hit_info = self.hit_column(DataMaskingColumnsOb, cluster_name, column.get('db'), column.get('table'),
column.get('field'))
if hit_info['is_hit']:
hit_info['index'] = column['index']
hit_columns.append(hit_info)
else:
table_hit_columns = None
hit_columns = None
return table_hit_columns, hit_columns
# 判断字段是否命中脱敏规则,如果命中则返回脱敏的规则id和规则类型
def hit_column(self, DataMaskingColumnsOb, cluster_name, table_schema, table_name, column_name):
column_info = DataMaskingColumnsOb.filter(cluster_name=cluster_name, table_schema=table_schema,
table_name=table_name, column_name=column_name, active=1)
hit_column_info = {}
hit_column_info['cluster_name'] = cluster_name
hit_column_info['table_schema'] = table_schema
hit_column_info['table_name'] = table_name
hit_column_info['column_name'] = column_name
hit_column_info['rule_type'] = 0
hit_column_info['is_hit'] = False
# 命中规则
if column_info:
hit_column_info['rule_type'] = column_info[0].rule_type
hit_column_info['is_hit'] = True
return hit_column_info
# 获取表中所有命中脱敏规则的字段信息
def hit_table(self, DataMaskingColumnsOb, cluster_name, table_schema, table_name):
columns_info = DataMaskingColumnsOb.filter(cluster_name=cluster_name, table_schema=table_schema,
table_name=table_name, active=1)
# 命中规则
hit_columns_info = []
for column in columns_info:
hit_column_info = {}
hit_column_info['cluster_name'] = cluster_name
hit_column_info['table_schema'] = table_schema
hit_column_info['table_name'] = table_name
hit_column_info['is_hit'] = True
hit_column_info['column_name'] = column.column_name
hit_column_info['rule_type'] = column.rule_type
hit_columns_info.append(hit_column_info)
return hit_columns_info
# 利用正则表达式脱敏数据
def regex(self, DataMaskingRulesOb, rule_type, value):
rules_info = DataMaskingRulesOb.get(rule_type=rule_type)
if rules_info:
rule_regex = rules_info.rule_regex
hide_group = rules_info.hide_group
# 正则匹配必须分组,隐藏的组会使用****代替
try:
p = re.compile(rule_regex)
m = p.search(str(value))
masking_str = ''
for i in range(m.lastindex):
if i == hide_group - 1:
group = '****'
else:
group = m.group(i + 1)
masking_str = masking_str + group
return masking_str
except Exception:
return value
else:
return value
def repair_json_str(json_str):
# 处理JSONDecodeError: Expecting property name enclosed in double quotes
# inception语法树出现{"a":1,}、["a":1,]、{'a':1}、[, { }]
json_str = re.sub(r"{\s*'(.+)':", r'{"\1":', json_str)
json_str = re.sub(r",\s*?]", "]", json_str)
json_str = re.sub(r",\s*?}", "}", json_str)
json_str = re.sub(r"\[,\s*?{", "[{", json_str)
json_str = json_str.replace("'", "\"")
return json_str
| jly8866/archer | sql/data_masking.py | Python | apache-2.0 | 16,236 | 0.002478 |
#!/usr/bin/python
# coding=utf-8
################################################################################
import os
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from test import run_only
from mock import Mock
from mock import patch
from mock import mock_open
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
from docker import Client
except ImportError:
Client = None
from diamond.collector import Collector
from docker_collector import DockerCollector
dirname = os.path.dirname(__file__)
fixtures_path = os.path.join(dirname, 'fixtures/')
fixtures = []
for root, dirnames, filenames in os.walk(fixtures_path):
fixtures.append([root, dirnames, filenames])
docker_fixture = [
{u'Id': u'c3341726a9b4235a35b390c5f6f28e5a6869879a48da1d609db8f6bf4275bdc5',
u'Names': [u'/testcontainer']},
{u'Id': u'0aec7f643ca1cb45f54d41dcabd8fcbcfcbc57170c3e6dd439af1a52761c2bed',
u'Names': [u'/testcontainer3']},
{u'Id': u'9c151939e20682b924d7299875e94a4aabbe946b30b407f89e276507432c625b',
u'Names': None}]
def run_only_if_docker_client_is_available(func):
try:
from docker import Client
except ImportError:
Client = None
pred = lambda: Client is not None
return run_only(func, pred)
class TestDockerCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('DockerCollector', {
'interval': 10,
'byte_unit': 'megabyte',
'memory_path': fixtures_path,
})
self.collector = DockerCollector(config, None)
def test_import(self):
self.assertTrue(DockerCollector)
def test_finds_linux_v2_memory_stat_path(self):
tid = 'c3341726a9b4235a35b390c5f6f28e5a6869879a48da1d609db8f6bf4275bdc5'
path = self.collector._memory_stat_path(tid)
self.assertTrue(path is not None)
self.assertTrue(os.path.exists(path))
def test_finds_linux_v3_memory_stat_path(self):
tid = '0aec7f643ca1cb45f54d41dcabd8fcbcfcbc57170c3e6dd439af1a52761c2bed'
path = self.collector._memory_stat_path(tid)
self.assertTrue(path is not None)
self.assertTrue(os.path.exists(path))
def test_doesnt_find_bogus_memory_stat_path(self):
tid = 'testcontainer'
path = self.collector._memory_stat_path(tid)
self.assertTrue(path is None)
@patch('os.path.exists', Mock(return_value=True))
def test_default_memory_path(self):
read_data = "\n".join([
'none /selinux selinuxfs rw,relatime 0 0',
'cgroup /goofy/memory cgroup'
' rw,nosuid,nodev,noexec,relatime,devices 0 0',
'cgroup /mickeymouse/memory cgroup'
' rw,nosuid,nodev,noexec,relatime,memory 0 0',
'tmpfs /dev/shm tmpfs rw,seclabel,nosuid,nodev 0 0',
'',
])
m = mock_open(read_data=read_data)
with patch('__builtin__.open', m, create=True):
self.assertEqual(self.collector._default_memory_path(),
'/mickeymouse/memory')
m.assert_called_once_with('/proc/mounts')
# @run_only_if_docker_client_is_available
# @patch.object(Collector, 'publish')
# @patch.object(Client, 'containers', Mock(return_value=[]))
# @patch.object(Client, 'images', Mock(return_value=[]))
# def test_collect_sunny_day(self, publish_mock):
# self.assertTrue(self.collector.collect())
# self.assertPublishedMany(publish_mock, {
# 'containers_running_count': 100,
# 'containers_stopped_count': 100,
# 'images_count': 100,
# 'images_dangling_count': 100,
# })
# @run_only_if_docker_client_is_available
# @patch('__builtin__.open')
# @patch.object(Client, 'containers', Mock(return_value=[]))
# @patch.object(Collector, 'publish')
# def test_should_open_memory_stat(self, publish_mock, open_mock):
# # open_mock.side_effect = lambda x: StringIO('')
# self.collector.collect()
# print open_mock.mock_calls
# open_mock.assert_any_call(fixtures_path +
# 'docker/c3341726a9b4235a35b'
# '390c5f6f28e5a6869879a48da1d609db8f6bf4275bdc5/memory.stat')
# # open_mock.assert_any_call(fixtures_path +
# 'lxc/testcontainer/memory.stat')
# # open_mock.assert_any_call(fixtures_path + 'lxc/memory.stat')
# # open_mock.assert_any_call(fixtures_path + 'memory.stat')
# @run_only_if_docker_client_is_available
# @patch('__builtin__.open')
# @patch.object(Client, 'containers')
# @patch.object(Collector, 'publish')
# def test_should_get_containers(self, publish_mock, containers_mock,
# open_mock):
# containers_mock.return_value = []
# open_mock.side_effect = lambda x: StringIO('')
# self.collector.collect()
# containers_mock.assert_any_call(all=True)
# @run_only_if_docker_client_is_available
# @patch.object(Collector, 'publish')
# @patch.object(Client, 'containers',
# Mock(return_value=docker_fixture))
# def test_should_work_with_real_data(self, publish_mock):
# self.collector.collect()
# self.assertPublishedMany(publish_mock, {
# 'lxc.testcontainer.cache': 1,
# 'lxc.testcontainer.rss': 1,
# 'lxc.testcontainer.swap': 1,
# 'lxc.cache': 1,
# 'lxc.rss': 1,
# 'lxc.swap': 1,
# 'system.cache': 1,
# 'system.rss': 1,
# 'system.swap': 1,
# 'docker.testcontainer.cache': 1,
# 'docker.testcontainer.rss': 1,
# 'docker.testcontainer.swap': 1,
# 'docker.cache': 1,
# 'docker.rss': 1,
# 'docker.swap': 1,
# })
if __name__ == "__main__":
unittest.main()
| TAKEALOT/Diamond | src/collectors/docker_collector/test/testdocker_collector.py | Python | mit | 5,993 | 0.001335 |
from datetime import datetime
def prettyDateNow():
"""
Returns a good looking string for the local time.
"""
return datetime.now().ctime()
def prettyDateNowUTC():
"""
Returns a good looking string for utc time.
"""
return datetime.utcnow().ctime()
def timestampNowLongUTC():
"""
Returns a timestamp in the format of %Y-%m-%d %H:%M:%S in Universal Time
Coordinates.
"""
return datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
| 0xPoly/ooni-probe | ooni/otime.py | Python | bsd-2-clause | 479 | 0.006263 |
#!/usr/bin/python3
#
# Polychromatic is licensed under the GPLv3.
# Copyright (C) 2020-2021 Luke Horwell <code@horwell.me>
#
"""
This module controls the 'Preferences' window of the Controller GUI.
"""
from .. import common
from .. import effects
from .. import locales
from .. import middleman
from .. import procpid
from .. import preferences as pref
from . import shared
import os
#import configparser # Imported on demand, OpenRazer only
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWidgets import QWidget, QPushButton, QTreeWidget, QLabel, \
QComboBox, QCheckBox, QDialog, QSpinBox, \
QDoubleSpinBox, QDialogButtonBox, QTabWidget, \
QMessageBox, QAction, QToolButton
class PreferencesWindow(shared.TabData):
"""
A window for adjusting the options of the application, viewing background
processes and getting more information about backends in use.
"""
def __init__(self, appdata):
super().__init__(appdata)
self.openrazer = OpenRazerPreferences(appdata)
self.dialog = None
self.pref_data = None
self.prompt_restart = False
self.restart_applet = False
self.options = [
# [group, item, <Qt object>, Qt object name, Inverted?]
# -- General
["controller", "system_qt_theme", QCheckBox, "UseSystemQtTheme", False],
["controller", "show_menu_bar", QCheckBox, "AlwaysHideMenuBar", True],
["controller", "landing_tab", QComboBox, "LandingTabCombo", False],
["controller", "window_behaviour", QComboBox, "WindowBehaviourCombo", False],
["controller", "toolbar_style", QComboBox, "ToolbarStyle", False],
# -- Tray
["tray", "autostart", QCheckBox, "TrayAutoStart", False],
["tray", "mode", QComboBox, "TrayModeCombo", False],
["tray", "autostart_delay", QSpinBox, "TrayDelaySpinner", 0],
# -- Customise
["custom", "use_dpi_stages", QCheckBox, "DPIStagesAuto", True],
["custom", "dpi_stage_1", QSpinBox, "DPIStage1", 0],
["custom", "dpi_stage_2", QSpinBox, "DPIStage2", 0],
["custom", "dpi_stage_3", QSpinBox, "DPIStage3", 0],
["custom", "dpi_stage_4", QSpinBox, "DPIStage4", 0],
["custom", "dpi_stage_5", QSpinBox, "DPIStage5", 0],
# -- Editor
["editor", "live_preview", QCheckBox, "LivePreview", False],
["editor", "hide_key_labels", QCheckBox, "HideKeyLabels", False],
["editor", "system_cursors", QCheckBox, "UseSystemCursors", False],
["editor", "suppress_confirm_dialog", QCheckBox, "SuppressConfirmDialog", False],
["editor", "show_saved_colour_shades", QCheckBox, "ShowSavedColourShades", False],
]
def open_window(self, open_tab=None):
"""
Opens the Preferences window to change Polychromatic's options.
Parameters:
open_tab (int) Optionally jump to this specific tab index.
"""
self.pref_data = pref.load_file(self.paths.preferences)
self.prompt_restart = False
self.restart_applet = False
self.dialog = shared.get_ui_widget(self.appdata, "preferences", QDialog)
self.dialog.findChild(QDialogButtonBox, "DialogButtons").accepted.connect(self._save_changes)
# Set icons for tabs
tabs = self.dialog.findChild(QTabWidget, "PreferencesTabs")
tabs.setTabIcon(0, self.widgets.get_icon_qt("general", "controller"))
tabs.setTabIcon(1, self.widgets.get_icon_qt("general", "tray-applet"))
tabs.setTabIcon(2, self.widgets.get_icon_qt("effects", "paint"))
tabs.setTabIcon(3, self.widgets.get_icon_qt("general", "matrix"))
tabs.setTabIcon(4, self.widgets.get_icon_qt("emblems", "software"))
# Set icons for controls
if not self.appdata.system_qt_theme:
self.dialog.findChild(QPushButton, "SavedColoursButton").setIcon(self.widgets.get_icon_qt("general", "edit"))
self.dialog.findChild(QPushButton, "SavedColoursReset").setIcon(self.widgets.get_icon_qt("general", "reset"))
self.dialog.findChild(QToolButton, "DPIStagesReset").setIcon(self.widgets.get_icon_qt("general", "reset"))
# Options
for option in self.options:
self._load_option(option[0], option[1], option[2], option[3], option[4])
self.dialog.findChild(QPushButton, "SavedColoursButton").clicked.connect(self.modify_colours)
self.dialog.findChild(QPushButton, "SavedColoursReset").clicked.connect(self.reset_colours)
self.dialog.findChild(QToolButton, "DPIStagesReset").clicked.connect(self._reset_dpi_stages_from_hardware)
# Create Icon Picker
def _set_new_tray_icon(new_icon):
self.dbg.stdout("New tray icon saved in memory: " + new_icon, self.dbg.debug, 1)
self.pref_data["tray"]["icon"] = new_icon
self.restart_applet = True
tray_icon_picker = self.widgets.create_icon_picker_control(_set_new_tray_icon, self.pref_data["tray"]["icon"], self._("Choose Tray Applet Icon"), shared.IconPicker.PURPOSE_TRAY_ONLY)
tray_icon_widget = self.dialog.findChild(QLabel, "TrayIconPickerPlaceholder")
tray_icon_widget.parentWidget().layout().replaceWidget(tray_icon_widget, tray_icon_picker)
# Backend Buttons
self.dialog.findChild(QPushButton, "OpenRazerSettings").clicked.connect(self.menubar.openrazer.configure)
self.dialog.findChild(QPushButton, "OpenRazerAbout").clicked.connect(self.menubar.openrazer.about)
self.dialog.findChild(QPushButton, "OpenRazerRestartDaemon").clicked.connect(self.menubar.openrazer.restart_daemon)
self.dialog.findChild(QPushButton, "OpenRazerTroubleshoot").clicked.connect(self.menubar.openrazer.troubleshoot)
# Buttons disguised as labels
view_log = self.dialog.findChild(QLabel, "OpenRazerLog")
def view_log_clicked(QMouseEvent):
if QMouseEvent.button() == Qt.LeftButton:
self.openrazer.open_log()
view_log.mouseReleaseEvent = view_log_clicked
if not self.appdata.system_qt_theme:
self.dialog.findChild(QPushButton, "OpenRazerSettings").setIcon(self.widgets.get_icon_qt("general", "preferences"))
self.dialog.findChild(QPushButton, "OpenRazerAbout").setIcon(self.widgets.get_icon_qt("general", "info"))
self.dialog.findChild(QPushButton, "OpenRazerRestartDaemon").setIcon(self.widgets.get_icon_qt("general", "refresh"))
self.dialog.findChild(QPushButton, "OpenRazerTroubleshoot").setIcon(self.widgets.get_icon_qt("emblems", "utility"))
# Drop custom icons when using native themes
if self.appdata.system_qt_theme:
combo = self.dialog.findChild(QComboBox, "LandingTabCombo")
for i in range(0, combo.count()):
combo.setItemIcon(i, QIcon())
# Prompt for a restart after changing these options
def _cb_set_restart_flag():
self.prompt_restart = True
self.dialog.findChild(QCheckBox, "UseSystemQtTheme").stateChanged.connect(_cb_set_restart_flag)
# Restart the tray applet after changing these options
def _cb_set_applet_flag(i):
self.restart_applet = True
self.dialog.findChild(QComboBox, "TrayModeCombo").currentIndexChanged.connect(_cb_set_applet_flag)
self.dialog.findChild(QCheckBox, "DPIStagesAuto").stateChanged.connect(_cb_set_applet_flag)
self.dialog.findChild(QCheckBox, "DPIStagesAuto").stateChanged.connect(self._refresh_dpi_stages_state)
for i in range(1, 6):
self.dialog.findChild(QSpinBox, "DPIStage" + str(i)).valueChanged.connect(_cb_set_applet_flag)
# FIXME: Hide incomplete features
self.dialog.findChild(QComboBox, "LandingTabCombo").removeItem(3)
self.dialog.findChild(QComboBox, "LandingTabCombo").removeItem(2)
# Disable tray applet tab if not installed
if not procpid.ProcessManager().is_component_installed("tray-applet"):
tabs.setTabEnabled(1, False)
# Show time!
self.dialog.findChild(QTabWidget, "PreferencesTabs").setCurrentIndex(open_tab if open_tab else 0)
self.refresh_backend_status()
self._refresh_dpi_stages_state()
self.dialog.open()
def refresh_backend_status(self):
"""
Refreshes the current status and enables/disables controls accordingly.
"""
if not self.dialog:
return
# See also: polychromatic_controller.Applicationdata.init_bg_thread.BackgroundThread()
openrazer_disabled = True if not "openrazer" in self.appdata.middleman.get_backends() else False
self.dialog.findChild(QPushButton, "OpenRazerSettings").setDisabled(openrazer_disabled)
self.dialog.findChild(QPushButton, "OpenRazerAbout").setDisabled(openrazer_disabled)
self.dialog.findChild(QPushButton, "OpenRazerRestartDaemon").setDisabled(openrazer_disabled)
self.dialog.findChild(QPushButton, "OpenRazerTroubleshoot").setDisabled(openrazer_disabled)
self.dialog.findChild(QLabel, "OpenRazerLog").setDisabled(openrazer_disabled)
# Backend Status
for backend in middleman.BACKEND_ID_NAMES.keys():
label = self._("Unknown")
icon = "serious"
for obj in self.middleman.backends:
if obj.backend_id == backend:
label = self._("Active")
icon = "success"
break
if backend in self.middleman.not_installed:
label = self._("Not Installed")
icon = "warning"
elif backend in self.middleman.import_errors.keys():
label = self._("Error loading the module")
icon = "serious"
backend_label = self.dialog.findChild(QLabel, "Status_" + backend + "_label")
backend_label.setText(label)
backend_status_icon = self.dialog.findChild(QLabel, "Status_" + backend + "_icon")
shared.set_pixmap_for_label(backend_status_icon, common.get_icon("general", icon), 24)
def _load_option(self, group, item, qcontrol, qid, inverted):
"""
Applies the setting in memory with the control.
Params:
group Preference group, e.g. "controller"
item Preference item, e.g. "landing_tab"
qcontrol Qt control object, e.g. QCheckBox
qid Name of Qt control, e.g. "UseSystemQtTheme"
invert (Optional, boolean) UI inverted to stored config
must_restart Changing this option requires application restart.
"""
data = self.pref_data[group][item]
widget = self.dialog.findChild(qcontrol, qid)
if qcontrol == QCheckBox:
widget.setChecked(not data if inverted else data)
elif qcontrol == QComboBox:
widget.setCurrentIndex(data)
elif qcontrol == QSpinBox:
widget.setValue(data)
def _set_option(self, group, item, qcontrol, qid, inverted):
"""
Updates the preferences in memory to reflect the UI control state.
Params:
Same as _get_option().
"""
widget = self.dialog.findChild(qcontrol, qid)
if qcontrol == QCheckBox:
data = widget.isChecked()
if inverted:
data = not data
elif qcontrol == QComboBox:
data = widget.currentIndex()
elif qcontrol == QSpinBox:
data = widget.value()
self.pref_data[group][item] = data
def _save_changes(self):
"""
Writes the preferences to file according to the GUI.
"""
self.dbg.stdout("Saving preferences...", self.dbg.action, 1)
for option in self.options:
self._set_option(option[0], option[1], option[2], option[3], option[4])
result = pref.save_file(self.paths.preferences, self.pref_data)
if result:
self.dbg.stdout("Save complete.", self.dbg.success, 1)
else:
self.dbg.stdout("Save failed! Check permissions?", self.dbg.error)
self.widgets.open_dialog(self.widgets.dialog_error,
self._("Save Error"),
self._("Save failed. Please check the permissions and try again."))
return False
# Update memory for the rest of the application
self.appdata.preferences = self.pref_data
# Instant reload
if self.pref_data["controller"]["show_menu_bar"] == True:
self.menubar.reinstate_menu_bar()
else:
self.menubar.hide_menu_bar()
# Force refresh of current tab
self.appdata.main_window.findChild(QAction, "actionRefreshTab").trigger()
# Some options require a restart
if self.prompt_restart:
self.dbg.stdout("Program settings changed. Prompting to restart application.", self.dbg.action, 1)
procmgr = procpid.ProcessManager()
def _cb_restart_now():
procmgr.restart_self(self.appdata.exec_path, self.appdata.exec_args)
self.widgets.open_dialog(self.widgets.dialog_generic,
self._("Restart Required"),
self._("To apply these changes, the application must be restarted. Any unsaved changes will be lost."),
buttons=[QMessageBox.Ok, QMessageBox.Ignore],
default_button=QMessageBox.Ok,
actions={QMessageBox.Ok: _cb_restart_now})
# Reload tray applet
if self.restart_applet:
self.dbg.stdout("Tray applet settings changed. Will restart component.", self.dbg.success, 1)
process = procpid.ProcessManager("tray-applet")
process.reload()
def _refresh_dpi_stages_state(self):
"""
Modifying DPI stages is only useful if a mouse is present and the user
wishes to use their own values.
"""
label = self.dialog.findChild(QLabel, "DPIStagesLabel")
checkbox = self.dialog.findChild(QCheckBox, "DPIStagesAuto")
spinbox_widget = self.dialog.findChild(QWidget, "DPIStagesWidget")
spinbox_is_zero = self.dialog.findChild(QSpinBox, "DPIStage1").value() == 0
# Is there a mouse? Disable section if none is present.
mice_present = False
if self.appdata.device_list:
mice_present = len(self.appdata.middleman.get_filtered_device_list("mouse")) > 0
for control in [label, checkbox, spinbox_widget]:
control.setDisabled(not mice_present)
if not mice_present:
return
# Disable controls when using default DPI stages
spinbox_widget.setDisabled(checkbox.isChecked())
# Automatically populate default DPI stages if blank
if self.appdata.device_list and checkbox.isChecked() and spinbox_is_zero:
self._reset_dpi_stages_from_hardware()
def _reset_dpi_stages_from_hardware(self):
"""
Reset user defined DPI stages to a DPI-capable mouse.
"""
mice_present = len(self.appdata.middleman.get_filtered_device_list("mouse")) > 0
if not mice_present:
return
mouse_device = None
for device in self.appdata.device_list:
if device["form_factor"]["id"] == "mouse":
device = self.appdata.middleman.get_device(device["backend"], device["uid"])
if device["dpi_stages"]:
mouse_device = device
break
if mouse_device:
self.dbg.stdout("Setting user-defined DPI stages to '{0}'".format(device["name"]), self.dbg.action, 1)
default_dpi_stages = device["dpi_stages"]
try:
for i in range(1, 6):
self.dialog.findChild(QSpinBox, "DPIStage" + str(i)).setValue(default_dpi_stages[i - 1])
except (IndexError, AttributeError):
# 5 stages not guaranteed
pass
def modify_colours(self):
"""
Opens the colour picker for editing saved colours for later use.
"""
def _cb_dummy(a, b):
# List is saved upon closing, nothing to do.
pass
virtual_picker = self.widgets.create_colour_control("#FFFFFF", _cb_dummy, None, self._("Saved Colours"))
virtual_picker.findChild(QPushButton).click()
def reset_colours(self):
"""
Reset colours to the defaults.
"""
def _cb_reset_colours():
os.remove(self.paths.colours)
pref.init(self._)
self.widgets.open_dialog(self.widgets.dialog_generic,
self._("Reset to Default Colours"),
self._("All colours in the list will be reset. Continue?"),
buttons=[QMessageBox.Ok, QMessageBox.Cancel],
default_button=QMessageBox.Ok,
actions={QMessageBox.Ok: _cb_reset_colours})
class OpenRazerPreferences(shared.TabData):
"""
A special window for changing the OpenRazer configuration file when OpenRazer
is in use.
"""
def __init__(self, appdata):
super().__init__(appdata)
# OpenRazer uses configparser. If not available, open text editor instead.
try:
import configparser
self.config_possible = True
except (ImportError, ModuleNotFoundError):
self.config_possible = False
self.conf_path = None
try:
self.conf_path = "{0}/.config/openrazer/razer.conf".format(os.environ["XDG_CONFIG_HOME"])
except KeyError:
pass
if not self.conf_path:
try:
self.conf_path = "/home/{0}/.config/openrazer/razer.conf".format(os.environ["USER"])
except KeyError:
self.conf_path = "/home/$USER/.config/openrazer/razer.conf"
self.keys = [
# "Group", "Item", <data type>
["General", "verbose_logging", bool],
#["Startup", "sync_effects_enabled", bool],
["Startup", "devices_off_on_screensaver", bool],
["Startup", "mouse_battery_notifier", bool],
["Startup", "mouse_battery_notifier_freq", int],
["Startup", "restore_persistence", bool],
]
self.client = [
# "Filename", <data type>
["allow_image_download", int],
["ripple_refresh_rate", float]
]
def open_log(self):
self.menubar.openrazer.open_log()
def restart_daemon(self):
self.menubar.openrazer.restart_daemon()
def open_window(self):
"""
Opens a window for adjusting OpenRazer options.
If configparser is not present for some reason, open the text editor.
"""
if not self.config_possible:
os.system("xdg-open file://{0}".format(self.conf_path))
return
self.dialog = shared.get_ui_widget(self.appdata, "openrazer-config", QDialog)
self.dialog.findChild(QDialogButtonBox, "DialogButtons").accepted.connect(self._save_and_restart)
# razer.conf
for key in self.keys:
group = key[0]
key_name = key[1]
data_type = key[2]
if data_type == bool:
chkbox = self.dialog.findChild(QCheckBox, key_name)
chkbox.setChecked(self._read_config(group, key_name, bool))
elif data_type == int:
spinner = self.dialog.findChild(QSpinBox, key_name)
spinner.setValue(self._read_config(group, key_name, int))
# Client
for meta in self.client:
filename = meta[0]
data_type = meta[1]
path = os.path.join(self.paths.config, "backends", "openrazer", filename)
if not os.path.exists(path):
continue
try:
with open(path, "r") as f:
data = str(f.readline()).strip()
data = data_type(data)
except ValueError:
self.dbg.stdout("Ignoring unexpected data from override file: " + filename, self.dbg.warning, 1)
continue
if data_type == int:
chkbox = self.dialog.findChild(QCheckBox, filename)
chkbox.setChecked(True if data == 1 else False)
elif data_type == float:
spinner = self.dialog.findChild(QDoubleSpinBox, filename)
spinner.setValue(float(data))
# TODO: Not implemented yet
self.dialog.findChild(QLabel, "restore_persistence_note").setHidden(True)
self.dialog.open()
def _save_and_restart(self):
"""
Updates the razer.conf file according to the GUI options.
"""
# razer.conf
for key in self.keys:
group = key[0]
key_name = key[1]
data_type = key[2]
if data_type == bool:
value = self.dialog.findChild(QCheckBox, key_name).isChecked()
elif data_type == int:
value = self.dialog.findChild(QSpinBox, key_name).value()
else:
continue
self._write_config(group, key_name, value)
# Client
for meta in self.client:
filename = meta[0]
data_type = meta[1]
path = os.path.join(self.paths.config, "backends", "openrazer", filename)
if data_type == int:
data = 1 if self.dialog.findChild(QCheckBox, filename).isChecked() else 0
with open(path, "w") as f:
f.write(str(data))
elif data_type == float:
data = self.dialog.findChild(QDoubleSpinBox, filename).value()
with open(path, "w") as f:
f.write(str(data))
# Restart the daemon to apply changes
self.menubar.openrazer.restart_daemon()
def _read_config(self, group, key_name, data_type):
"""
Reads OpenRazer's razer.conf file, similar format to an INI.
If value is not found, the default is False or 0.
"""
import configparser
config = configparser.ConfigParser()
config.read(self.conf_path)
try:
value = config[group][key_name]
if value == "True":
return True
elif value == "False":
return False
else:
return data_type(value)
except KeyError:
# Return default data
if data_type == int:
return 0
elif data_type == bool:
return False
def _write_config(self, group, key_name, value):
"""
Overwrites a new key to OpenRazer's razer.conf file.
"""
import configparser
config = configparser.ConfigParser()
config.read(self.conf_path)
if group not in config:
config[group] = {}
config[group][key_name] = str(value)
if not os.path.exists(os.path.dirname(self.conf_path)):
os.makedirs(os.path.dirname(self.conf_path))
with open(self.conf_path, "w") as f:
config.write(f)
| lah7/polychromatic | pylib/controller/preferences.py | Python | gpl-3.0 | 23,790 | 0.003153 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# {{pkglts pysetup,
from os import walk
from os.path import abspath, normpath
from os.path import join as pj
from setuptools import setup, find_packages
short_descr = "Set of data structures used in openalea such as : graph, grid, topomesh"
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
def parse_requirements(fname):
with open(fname, 'r') as f:
txt = f.read()
reqs = []
for line in txt.splitlines():
line = line.strip()
if len(line) > 0 and not line.startswith("#"):
reqs.append(line)
return reqs
# find version number in /src/$pkg_pth/version.py
version = {}
with open("src/openalea/container/version.py") as fp:
exec(fp.read(), version)
setup(
name='openalea.container',
version=version["__version__"],
description=short_descr,
long_description=readme + '\n\n' + history,
author="revesansparole",
author_email='revesansparole@gmail.com',
url='',
license="mit",
zip_safe=False,
packages=find_packages('src'),
package_dir={'': 'src'},
install_requires=parse_requirements("requirements.txt"),
tests_require=parse_requirements("dvlpt_requirements.txt"),
entry_points={
# 'console_scripts': [
# 'fake_script = openalea.fakepackage.amodule:console_script', ],
# 'gui_scripts': [
# 'fake_gui = openalea.fakepackage.amodule:gui_script',],
# 'wralea': wralea_entry_points
},
keywords='',
classifiers=[
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2 :: Only',
'Programming Language :: Python :: 2.7'
],
test_suite='nose.collector',
)
# }}
| revesansparole/oacontainer | setup.py | Python | mit | 1,872 | 0.001603 |
from __future__ import absolute_import
from pprint import pprint
# pylint: disable=import-error
from twisted.internet import defer, threads, reactor
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
@defer.inlineCallbacks
def create_node(name):
node = yield threads.deferToThread(_thread_create_node,
name=name)
pprint(node)
reactor.stop()
def _thread_create_node(name):
Driver = get_driver(Provider.RACKSPACE)
conn = Driver('username', 'api key')
image = conn.list_images()[0]
size = conn.list_sizes()[0]
node = conn.create_node(name=name, image=image, size=size)
return node
def stop(*args, **kwargs):
reactor.stop()
d = create_node(name='my-lc-node')
d.addCallback(stop) # pylint: disable=no-member
d.addErrback(stop) # pylint: disable=no-member
reactor.run()
| StackPointCloud/libcloud | docs/examples/misc/twisted_create_node.py | Python | apache-2.0 | 898 | 0.001114 |
"""
Tests for locust api module
These tests requires locust installed
"""
#pylint: disable=W0403,C0103,too-many-public-methods
import unittest
from subprocess import call
from netifaces import interfaces
from locust.api import Agent
from time import time, sleep
STATUSES = {'success': 'success',
'error': 'error'}
MESSAGES = {'success': 'Network adapter is enabled',
'error': 'Network adapter is not enabled'}
HOSTNAME = 'google.com'
def is_network_enabled():
"""Ping a host to check if network is enabled """
cmd_ptrn = 'ping -c {packets} {hostname} '
cmd_ptrn = cmd_ptrn.format(packets=1, hostname=HOSTNAME)
result = not bool(call(cmd_ptrn, shell=True))
sleep(1)
return result
def wait_for_network_disabled(seconds=30):
"""Wait until network is disabled"""
then = time() + seconds
while then > time():
if not is_network_enabled():
return True
return False
def wait_for_network_enabled(seconds=30):
"""Wait until network is enabled"""
then = time() + seconds
while then > time():
if is_network_enabled():
return True
return False
def check_network_interface_is_up(interface_name):
"""Check if netiface is up using 'ip' console command"""
cmd_ptrn = "ip a|grep ': {interface}:.*state UP'"
cmd_ptrn = cmd_ptrn.format(interface=interface_name)
response = 0 == call(cmd_ptrn, shell=True)
return response
def get_active_adapter():
""" Returns first active adapter from the list of adapters"""
for adapter in interfaces():
if check_network_interface_is_up(adapter):
return adapter
def enable_network_adapters_if_disabled():
"""Enables all network adapters if disabled"""
if not wait_for_network_enabled():
Agent.enable_network_adapters()
wait_for_network_enabled()
def disable_adapters(adapters=None):
""" Disables specified adapter or list of adapters.
Disables all if no adapters provided.
Returns error message in case of error """
time_to_be_disabled = 0
result = Agent.disable_network_adapters(adapters, time_to_be_disabled)
if 0 == result['list'][0]['status'].find('error'):
return 'Error while disabling adapters. Result: {}'.format(result)
if not wait_for_network_disabled():
return 'Error while disabling adapters. Network is still enabled.' \
' Result: {}'.format(result)
if wait_for_network_enabled():
return 'Error while disabling adapters. Network was enabled. ' \
'But it should stay disabled. Result: {}'.format(result)
class EnableNetworkAdaptersApi(unittest.TestCase):
"""Implements unit tests
for enable_network_adapters method of bagent.api."""
wrong_status = 'Expected status: {expected}. Current status: {actual}'
wrong_message = 'Expected message: {expected}. Current message: {actual}'
def test_enable_one_network_adapter(self):
"""Enables an active adapter, that was disabled previously"""
adapter = get_active_adapter()
disable_adapters_error = disable_adapters(adapter)
self.assertFalse(disable_adapters_error, msg=disable_adapters_error)
self.assertTrue(wait_for_network_disabled(),
'Initially Network is enabled.')
result = Agent.enable_network_adapters(adapter)
self.assertEqual(type(result), dict, 'Returned result should be dict')
status_from_result = result['list'][0]['status']
message_from_result = result['list'][0]['message']
self.assertEqual(status_from_result, STATUSES['success'],
self.wrong_status.format(
expected=STATUSES['success'],
actual=status_from_result))
self.assertEqual(message_from_result, MESSAGES['success'],
self.wrong_message.format(
expected=MESSAGES['success'],
actual=message_from_result))
self.assertTrue(wait_for_network_enabled(),
'Network was not enabled')
def test_enable_all_network_adapters_empty_list(self):
"""Enables all adapters, that was disabled previously
List of adapters is empty """
adapter = None
disable_adapters_error = disable_adapters(adapter)
self.assertFalse(disable_adapters_error, msg=disable_adapters_error)
self.assertTrue(wait_for_network_disabled(),
'Initially Network is enabled.')
result = Agent.enable_network_adapters(adapter)
self.assertEqual(type(result), dict, 'Returned result should be dict')
status_from_result = result['list'][0]['status']
message_from_result = result['list'][0]['message']
self.assertEqual(status_from_result, STATUSES['success'],
self.wrong_status.format(
expected=STATUSES['success'],
actual=status_from_result))
self.assertEqual(message_from_result, MESSAGES['success'],
self.wrong_message.format(
expected=MESSAGES['success'],
actual=message_from_result))
self.assertTrue(wait_for_network_enabled(),
'Network was not enabled')
def test_enable_all_network_adapters(self):
"""Enables all adapters, that was disabled previously"""
adapter = interfaces()
disable_adapters_error = disable_adapters(adapter)
self.assertFalse(disable_adapters_error, msg=disable_adapters_error)
self.assertTrue(wait_for_network_disabled(),
'Initially Network is enabled.')
result = Agent.enable_network_adapters(adapter)
self.assertEqual(type(result), dict, 'Returned result should be dict')
status_from_result = result['list'][0]['status']
message_from_result = result['list'][0]['message']
self.assertEqual(status_from_result, STATUSES['success'],
self.wrong_status.format(
expected=STATUSES['success'],
actual=status_from_result))
self.assertEqual(message_from_result, MESSAGES['success'],
self.wrong_message.format(
expected=MESSAGES['success'],
actual=message_from_result))
self.assertTrue(wait_for_network_enabled(),
'Network was not enabled')
def test_enable_non_existing_network_adapters(self):
""" Trying to use adapter name that does not exist"""
adapter = 'this_adapter_does_not_exist'
disable_adapters_error = disable_adapters()
self.assertFalse(disable_adapters_error, msg=disable_adapters_error)
self.assertTrue(wait_for_network_disabled(),
'Initially Network is enabled.')
result = Agent.enable_network_adapters(adapter)
self.assertEqual(type(result), dict, 'Returned result should be dict')
status_from_result = result['list'][0]['status']
message_from_result = result['list'][0]['message']
self.assertEqual(status_from_result, STATUSES['error'],
self.wrong_status.format(
expected=STATUSES['error'],
actual=status_from_result))
self.assertEqual(message_from_result, MESSAGES['error'],
self.wrong_message.format(
expected=MESSAGES['error'],
actual=message_from_result))
self.assertFalse(wait_for_network_enabled(),
'Network was enabled. But it should stay disabled.')
enable_network_adapters_if_disabled()
def setUp(self):
enable_network_adapters_if_disabled()
@classmethod
def tearDownClass(cls):
enable_network_adapters_if_disabled()
def main():
"""method for invoking unit tests."""
unittest.main(verbosity=3)
if __name__ == '__main__':
main()
| arozumenko/locust | tests/locust/tests_enable_network_adapters.py | Python | apache-2.0 | 8,175 | 0.000367 |
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request, 'home.html')
def contact(request):
return render(request, 'contact.html') | kaiocesar/simplemooc | simplemooc/core/views.py | Python | mit | 192 | 0.026042 |
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Lukáš Lalinský
# Copyright (C) 2014 Shadab Zafar
# Copyright (C) 2015-2021 Laurent Monin
# Copyright (C) 2019 Wieland Hoffmann
# Copyright (C) 2019-2020 Philipp Wolfer
#
# 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.
from functools import partial
import imp
import importlib
import json
import os.path
import shutil
import tempfile
import zipfile
import zipimport
from PyQt5 import QtCore
from picard import log
from picard.const import (
PLUGINS_API,
USER_PLUGIN_DIR,
)
from picard.plugin import (
_PLUGIN_MODULE_PREFIX,
PluginData,
PluginWrapper,
_unregister_module_extensions,
)
import picard.plugins
from picard.version import (
Version,
VersionError,
)
_SUFFIXES = tuple(importlib.machinery.all_suffixes())
_PACKAGE_ENTRIES = ("__init__.py", "__init__.pyc", "__init__.pyo")
_PLUGIN_PACKAGE_SUFFIX = ".picard"
_PLUGIN_PACKAGE_SUFFIX_LEN = len(_PLUGIN_PACKAGE_SUFFIX)
_FILEEXTS = ('.py', '.pyc', '.pyo', '.zip')
_UPDATE_SUFFIX = '.update'
_UPDATE_SUFFIX_LEN = len(_UPDATE_SUFFIX)
_extension_points = []
def is_update(path):
return path.endswith(_UPDATE_SUFFIX)
def strip_update_suffix(path):
if not is_update(path):
return path
return path[:-_UPDATE_SUFFIX_LEN]
def is_zip(path):
return path.endswith('.zip')
def strip_zip_suffix(path):
if not is_zip(path):
return path
return path[:-4]
def is_package(path):
return path.endswith(_PLUGIN_PACKAGE_SUFFIX)
def strip_package_suffix(path):
if not is_package(path):
return path
return path[:-_PLUGIN_PACKAGE_SUFFIX_LEN]
def is_zipped_package(path):
return path.endswith(_PLUGIN_PACKAGE_SUFFIX + '.zip')
def _plugin_name_from_path(path):
path = os.path.normpath(path)
if is_zip(path):
name = os.path.basename(strip_zip_suffix(path))
if is_package(name):
return strip_package_suffix(name)
else:
return name
elif os.path.isdir(path):
for entry in _PACKAGE_ENTRIES:
if os.path.isfile(os.path.join(path, entry)):
return os.path.basename(path)
else:
file = os.path.basename(path)
if file in _PACKAGE_ENTRIES:
return None
name, ext = os.path.splitext(file)
if ext in _SUFFIXES:
return name
return None
def load_manifest(archive_path):
archive = zipfile.ZipFile(archive_path)
manifest_data = None
with archive.open('MANIFEST.json') as f:
manifest_data = json.loads(str(f.read().decode()))
return manifest_data
def zip_import(path):
if (not is_zip(path) or not os.path.isfile(path)):
return (None, None, None)
try:
zip_importer = zipimport.zipimporter(path)
plugin_name = _plugin_name_from_path(path)
manifest_data = None
if is_zipped_package(path):
try:
manifest_data = load_manifest(path)
except Exception as why:
log.warning("Failed to load manifest data from json: %s", why)
return (zip_importer, plugin_name, manifest_data)
except zipimport.ZipImportError as why:
log.error("ZIP import error: %s", why)
return (None, None, None)
def _compatible_api_versions(api_versions):
versions = [Version.from_string(v) for v in list(api_versions)]
return set(versions) & set(picard.api_versions_tuple)
class PluginManager(QtCore.QObject):
plugin_installed = QtCore.pyqtSignal(PluginWrapper, bool)
plugin_updated = QtCore.pyqtSignal(str, bool)
plugin_removed = QtCore.pyqtSignal(str, bool)
plugin_errored = QtCore.pyqtSignal(str, str, bool)
def __init__(self, plugins_directory=None):
super().__init__()
self.plugins = []
self._available_plugins = None # None=never loaded, [] = empty
if plugins_directory is None:
plugins_directory = USER_PLUGIN_DIR
self.plugins_directory = os.path.normpath(plugins_directory)
@property
def available_plugins(self):
return self._available_plugins
def plugin_error(self, name, error, *args, **kwargs):
"""Log a plugin loading error for the plugin `name` and signal the
error via the `plugin_errored` signal.
A string consisting of all `args` interpolated into `error` will be
passed to the function given via the `log_func` keyword argument
(default: log.error) and as the error message to the `plugin_errored`
signal."""
error = error % args
log_func = kwargs.get('log_func', log.error)
log_func(error)
self.plugin_errored.emit(name, error, False)
def _marked_for_update(self):
for file in os.listdir(self.plugins_directory):
if file.endswith(_UPDATE_SUFFIX):
source_path = os.path.join(self.plugins_directory, file)
target_path = strip_update_suffix(source_path)
plugin_name = _plugin_name_from_path(target_path)
if plugin_name:
yield (source_path, target_path, plugin_name)
else:
log.error('Cannot get plugin name from %r', source_path)
def handle_plugin_updates(self):
for source_path, target_path, plugin_name in self._marked_for_update():
self._remove_plugin(plugin_name)
os.rename(source_path, target_path)
log.debug('Updating plugin %r (%r))', plugin_name, target_path)
def load_plugins_from_directory(self, plugindir):
plugindir = os.path.normpath(plugindir)
if not os.path.isdir(plugindir):
log.info("Plugin directory %r doesn't exist", plugindir)
return
if plugindir == self.plugins_directory:
# .update trick is only for plugins installed through the Picard UI
# and only for plugins in plugins_directory (USER_PLUGIN_DIR by default)
self.handle_plugin_updates()
# now load found plugins
names = set()
for path in [os.path.join(plugindir, file) for file in os.listdir(plugindir)]:
name = _plugin_name_from_path(path)
if name:
names.add(name)
log.debug("Looking for plugins in directory %r, %d names found",
plugindir,
len(names))
for name in sorted(names):
try:
self._load_plugin_from_directory(name, plugindir)
except Exception:
self.plugin_error(name, _("Unable to load plugin '%s'"), name, log_func=log.exception)
def _get_plugin_index_by_name(self, name):
for index, plugin in enumerate(self.plugins):
if name == plugin.module_name:
return (plugin, index)
return (None, None)
def _load_plugin_from_directory(self, name, plugindir):
module_file = None
zipfilename = os.path.join(plugindir, name + '.zip')
(zip_importer, module_name, manifest_data) = zip_import(zipfilename)
if zip_importer:
name = module_name
if not zip_importer.find_module(name):
error = _("Failed loading zipped plugin %r from %r")
self.plugin_error(name, error, name, zipfilename)
return None
module_pathname = zip_importer.get_filename(name)
else:
try:
info = imp.find_module(name, [plugindir])
module_file = info[0]
module_pathname = info[1]
except ImportError:
error = _("Failed loading plugin %r in %r")
self.plugin_error(name, error, name, [plugindir])
return None
plugin = None
try:
existing_plugin, existing_plugin_index = self._get_plugin_index_by_name(name)
if existing_plugin:
log.warning("Module %r conflict: unregistering previously"
" loaded %r version %s from %r",
existing_plugin.module_name,
existing_plugin.name,
existing_plugin.version,
existing_plugin.file)
_unregister_module_extensions(name)
full_module_name = _PLUGIN_MODULE_PREFIX + name
if zip_importer:
plugin_module = zip_importer.load_module(full_module_name)
else:
plugin_module = imp.load_module(full_module_name, *info)
plugin = PluginWrapper(plugin_module, plugindir,
file=module_pathname, manifest_data=manifest_data)
compatible_versions = _compatible_api_versions(plugin.api_versions)
if compatible_versions:
log.debug("Loading plugin %r version %s, compatible with API: %s",
plugin.name,
plugin.version,
", ".join([v.to_string(short=True) for v in
sorted(compatible_versions)]))
plugin.compatible = True
setattr(picard.plugins, name, plugin_module)
if existing_plugin:
self.plugins[existing_plugin_index] = plugin
else:
self.plugins.append(plugin)
else:
error = _("Plugin '%s' from '%s' is not compatible with this "
"version of Picard.") % (plugin.name, plugin.file)
self.plugin_error(plugin.name, error, log_func=log.warning)
except VersionError as e:
error = _("Plugin %r has an invalid API version string : %s")
self.plugin_error(name, error, name, e)
except BaseException:
error = _("Plugin %r")
self.plugin_error(name, error, name, log_func=log.exception)
if module_file is not None:
module_file.close()
return plugin
def _get_existing_paths(self, plugin_name, fileexts):
dirpath = os.path.join(self.plugins_directory, plugin_name)
if not os.path.isdir(dirpath):
dirpath = None
filepaths = [os.path.join(self.plugins_directory, f)
for f in os.listdir(self.plugins_directory)
if f in [plugin_name + ext for ext in fileexts]
]
return (dirpath, filepaths)
def _remove_plugin_files(self, plugin_name, with_update=False):
plugin_name = strip_zip_suffix(plugin_name)
log.debug("Remove plugin files and dirs : %r", plugin_name)
dirpath, filepaths = self._get_existing_paths(plugin_name, _FILEEXTS)
if dirpath:
if os.path.islink(dirpath):
log.debug("Removing symlink %r", dirpath)
os.remove(dirpath)
elif os.path.isdir(dirpath):
log.debug("Removing directory %r", dirpath)
shutil.rmtree(dirpath)
if filepaths:
for filepath in filepaths:
log.debug("Removing file %r", filepath)
os.remove(filepath)
if with_update:
update = filepath + _UPDATE_SUFFIX
if os.path.isfile(update):
log.debug("Removing file %r", update)
os.remove(update)
def _remove_plugin(self, plugin_name, with_update=False):
self._remove_plugin_files(plugin_name, with_update)
_unregister_module_extensions(plugin_name)
self.plugins = [p for p in self.plugins if p.module_name != plugin_name]
def remove_plugin(self, plugin_name, with_update=False):
self._remove_plugin(plugin_name, with_update=with_update)
self.plugin_removed.emit(plugin_name, False)
def _install_plugin_zip(self, plugin_name, plugin_data, update=False):
# zipped module from download
zip_plugin = plugin_name + '.zip'
dst = os.path.join(self.plugins_directory, zip_plugin)
if update:
dst += _UPDATE_SUFFIX
if os.path.isfile(dst):
os.remove(dst)
with tempfile.NamedTemporaryFile(dir=self.plugins_directory) as zipfile:
zipfile.write(plugin_data)
zipfile.flush()
os.fsync(zipfile.fileno())
try:
os.link(zipfile.name, dst)
except OSError:
with open(dst, 'wb') as dstfile:
zipfile.seek(0)
shutil.copyfileobj(zipfile, dstfile)
log.debug("Plugin (zipped) saved to %r", dst)
def _install_plugin_file(self, path, update=False):
dst = os.path.join(self.plugins_directory, os.path.basename(path))
if update:
dst += _UPDATE_SUFFIX
if os.path.isfile(dst):
os.remove(dst)
shutil.copy2(path, dst)
log.debug("Plugin (file) saved to %r", dst)
def _install_plugin_dir(self, plugin_name, path, update=False):
dst = os.path.join(self.plugins_directory, plugin_name)
if update:
dst += _UPDATE_SUFFIX
if os.path.isdir(dst):
shutil.rmtree(dst)
shutil.copytree(path, dst)
log.debug("Plugin (directory) saved to %r", dst)
def install_plugin(self, path, update=False, plugin_name=None, plugin_data=None):
"""
path is either:
1) /some/dir/name.py
2) /some/dir/name (directory containing __init__.py)
3) /some/dir/name.zip (containing either 1 or 2)
"""
assert path or plugin_name, "path is required if plugin_name is empty"
if not plugin_name:
plugin_name = _plugin_name_from_path(path)
if plugin_name:
try:
if plugin_data:
self._install_plugin_zip(plugin_name, plugin_data, update=update)
elif os.path.isfile(path):
self._install_plugin_file(path, update=update)
elif os.path.isdir(path):
self._install_plugin_dir(plugin_name, path, update=update)
except OSError as why:
log.error("Unable to copy plugin '%s' to %r: %s" % (plugin_name, self.plugins_directory, why))
return
if not update:
try:
installed_plugin = self._load_plugin_from_directory(plugin_name, self.plugins_directory)
if not installed_plugin:
raise RuntimeError("Failed loading newly installed plugin %s" % plugin_name)
except Exception as e:
log.error("Unable to load plugin '%s': %s", plugin_name, e)
self._remove_plugin(plugin_name)
else:
self.plugin_installed.emit(installed_plugin, False)
else:
self.plugin_updated.emit(plugin_name, False)
def query_available_plugins(self, callback=None):
self.tagger.webservice.get(
PLUGINS_API['host'],
PLUGINS_API['port'],
PLUGINS_API['endpoint']['plugins'],
partial(self._plugins_json_loaded, callback=callback),
priority=True,
important=True
)
def is_available(self, plugin_name):
return any(p.module_name == plugin_name for p in self._available_plugins)
def _plugins_json_loaded(self, response, reply, error, callback=None):
if error:
self.tagger.window.set_statusbar_message(
N_("Error loading plugins list: %(error)s"),
{'error': reply.errorString()},
echo=log.error
)
self._available_plugins = []
else:
try:
self._available_plugins = [PluginData(data, key) for key, data in
response['plugins'].items()
if _compatible_api_versions(data['api_versions'])]
except (AttributeError, KeyError, TypeError):
self._available_plugins = []
if callback:
callback()
# pylint: disable=no-self-use
def enabled(self, name):
return True
| metabrainz/picard | picard/pluginmanager.py | Python | gpl-2.0 | 17,081 | 0.000995 |
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.olsr', 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'])
typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator', u'ns3::AttributeConstructionList::CIterator')
typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator*', u'ns3::AttributeConstructionList::CIterator*')
typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator&', u'ns3::AttributeConstructionList::CIterator&')
## 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')
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor> [struct]
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor'])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker> [struct]
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeChecker'])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue> [struct]
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeValue'])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase> [struct]
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase'])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl> [struct]
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::EventImpl'])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation> [struct]
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation'])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector> [struct]
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::NixVector'])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet> [struct]
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Packet'])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor> [struct]
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor'])
## event-garbage-collector.h (module 'core'): ns3::EventGarbageCollector [class]
module.add_class('EventGarbageCollector', import_from_module='ns.core')
## 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')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
module.add_class('Inet6SocketAddress', import_from_module='ns.network')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
module.add_class('InetSocketAddress', import_from_module='ns.network')
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## int-to-type.h (module 'core'): ns3::IntToType<0> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0'])
## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<1> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1'])
## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<2> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2'])
## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<3> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3'])
## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<4> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4'])
## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<5> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5'])
## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<6> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6'])
## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], 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-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class]
module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration]
module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class]
module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet')
## 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')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Mac48Address )', u'ns3::Mac48Address::TracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Mac48Address )*', u'ns3::Mac48Address::TracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Mac48Address )&', u'ns3::Mac48Address::TracedCallback&')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
## mac8-address.h (module 'network'): ns3::Mac8Address [class]
module.add_class('Mac8Address', import_from_module='ns.network')
## mac8-address.h (module 'network'): ns3::Mac8Address [class]
root_module['ns3::Mac8Address'].implicitly_converts_to(root_module['ns3::Address'])
## node-container.h (module 'network'): ns3::NodeContainer [class]
module.add_class('NodeContainer', import_from_module='ns.network')
typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator', u'ns3::NodeContainer::Iterator')
typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator*', u'ns3::NodeContainer::Iterator*')
typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator&', u'ns3::NodeContainer::Iterator&')
## non-copyable.h (module 'core'): ns3::NonCopyable [class]
module.add_class('NonCopyable', destructor_visibility='protected', import_from_module='ns.core')
## 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')
## olsr-helper.h (module 'olsr'): ns3::OlsrHelper [class]
module.add_class('OlsrHelper', parent=root_module['ns3::Ipv4RoutingHelper'])
## 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::ItemType [enumeration]
module.add_enum('ItemType', ['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'])
## 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')
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class]
module.add_class('SystemWallClockMs', 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')
## nstime.h (module 'core'): ns3::TimeWithUnit [class]
module.add_class('TimeWithUnit', import_from_module='ns.core')
## timer.h (module 'core'): ns3::Timer [class]
module.add_class('Timer', import_from_module='ns.core')
## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration]
module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core')
## timer.h (module 'core'): ns3::Timer::State [enumeration]
module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core')
## timer-impl.h (module 'core'): ns3::TimerImpl [class]
module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core')
## 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::SupportLevel [enumeration]
module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], 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'])
typehandlers.add_type_alias(u'uint32_t', u'ns3::TypeId::hash_t')
typehandlers.add_type_alias(u'uint32_t*', u'ns3::TypeId::hash_t*')
typehandlers.add_type_alias(u'uint32_t&', u'ns3::TypeId::hash_t&')
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-128.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## int64x64-128.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')
## 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'])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class]
module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header'])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration]
module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet')
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration]
module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet')
## 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::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], 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::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], 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::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], 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::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'))
## socket.h (module 'network'): ns3::Socket [class]
module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object'])
## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration]
module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::Socket::SocketType [enumeration]
module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration]
module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration]
module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::SocketIpTosTag [class]
module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpTtlTag [class]
module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class]
module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class]
module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketPriorityTag [class]
module.add_class('SocketPriorityTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class]
module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## 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')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time )', u'ns3::Time::TracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time )*', u'ns3::Time::TracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Time )&', u'ns3::Time::TracedCallback&')
## 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'])
## 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> >'])
## 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'])
## 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'])
## 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::EmptyAttributeAccessor [class]
module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor'])
## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class]
module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', 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'])
## ipv4.h (module 'internet'): ns3::Ipv4 [class]
module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## 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'])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class]
module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >'])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class]
module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >'])
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class]
module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object'])
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Ipv4RoutingProtocol::UnicastForwardCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Ipv4RoutingProtocol::UnicastForwardCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Ipv4RoutingProtocol::UnicastForwardCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Ipv4RoutingProtocol::MulticastForwardCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Ipv4RoutingProtocol::MulticastForwardCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Ipv4RoutingProtocol::MulticastForwardCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Ipv4RoutingProtocol::LocalDeliverCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Ipv4RoutingProtocol::LocalDeliverCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Ipv4RoutingProtocol::LocalDeliverCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Ipv4RoutingProtocol::ErrorCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Ipv4RoutingProtocol::ErrorCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Ipv4RoutingProtocol::ErrorCallback&')
## ipv4-static-routing.h (module 'internet'): ns3::Ipv4StaticRouting [class]
module.add_class('Ipv4StaticRouting', import_from_module='ns.internet', parent=root_module['ns3::Ipv4RoutingProtocol'])
## 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'])
## 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')
typehandlers.add_type_alias(u'void ( * ) ( )', u'ns3::NetDevice::LinkChangeTracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( )*', u'ns3::NetDevice::LinkChangeTracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( )&', u'ns3::NetDevice::LinkChangeTracedCallback&')
typehandlers.add_type_alias(u'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 >', u'ns3::NetDevice::ReceiveCallback')
typehandlers.add_type_alias(u'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 >*', u'ns3::NetDevice::ReceiveCallback*')
typehandlers.add_type_alias(u'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 >&', u'ns3::NetDevice::ReceiveCallback&')
typehandlers.add_type_alias(u'ns3::Callback< bool, 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 >', u'ns3::NetDevice::PromiscReceiveCallback')
typehandlers.add_type_alias(u'ns3::Callback< bool, 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 >*', u'ns3::NetDevice::PromiscReceiveCallback*')
typehandlers.add_type_alias(u'ns3::Callback< bool, 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 >&', u'ns3::NetDevice::PromiscReceiveCallback&')
## 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'])
typehandlers.add_type_alias(u'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 >', u'ns3::Node::ProtocolHandler')
typehandlers.add_type_alias(u'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 >*', u'ns3::Node::ProtocolHandler*')
typehandlers.add_type_alias(u'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 >&', u'ns3::Node::ProtocolHandler&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Node::DeviceAdditionListener')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Node::DeviceAdditionListener*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Node::DeviceAdditionListener&')
## 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'])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class]
module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
## 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> >'])
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > )', u'ns3::Packet::TracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > )*', u'ns3::Packet::TracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > )&', u'ns3::Packet::TracedCallback&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )', u'ns3::Packet::AddressTracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )*', u'ns3::Packet::AddressTracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )&', u'ns3::Packet::AddressTracedCallback&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )', u'ns3::Packet::TwoAddressTracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )*', u'ns3::Packet::TwoAddressTracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )&', u'ns3::Packet::TwoAddressTracedCallback&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )', u'ns3::Packet::Mac48AddressTracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )*', u'ns3::Packet::Mac48AddressTracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )&', u'ns3::Packet::Mac48AddressTracedCallback&')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t )', u'ns3::Packet::SizeTracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t )*', u'ns3::Packet::SizeTracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t )&', u'ns3::Packet::SizeTracedCallback&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, double )', u'ns3::Packet::SinrTracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, double )*', u'ns3::Packet::SinrTracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, double )&', u'ns3::Packet::SinrTracedCallback&')
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class]
module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## 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'])
## 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'])
## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class]
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['bool', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class]
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::olsr::PacketHeader &, const std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class]
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'const ns3::olsr::PacketHeader &', 'const std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> [class]
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'const ns3::Address &', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class]
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class]
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class]
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class]
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
## callback.h (module 'core'): ns3::CallbackImpl<void, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class]
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting [class]
module.add_class('Ipv4ListRouting', import_from_module='ns.internet', parent=root_module['ns3::Ipv4RoutingProtocol'])
module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector')
module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map')
module.add_container('std::vector< unsigned int >', 'unsigned int', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::MessageHeader >', 'ns3::olsr::MessageHeader', container_type=u'vector')
## 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 olsr
nested_module = module.add_cpp_namespace('olsr')
register_types_ns3_olsr(nested_module)
## Register a nested module for the namespace tests
nested_module = module.add_cpp_namespace('tests')
register_types_ns3_tests(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 *, std::size_t const )', u'ns3::Hash::Hash32Function_ptr')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, std::size_t const )*', u'ns3::Hash::Hash32Function_ptr*')
typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, std::size_t const )&', u'ns3::Hash::Hash32Function_ptr&')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, std::size_t const )', u'ns3::Hash::Hash64Function_ptr')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, std::size_t const )*', u'ns3::Hash::Hash64Function_ptr*')
typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, std::size_t const )&', 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 ( * ) ( 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&')
def register_types_ns3_olsr(module):
root_module = module.get_root()
## olsr-repositories.h (module 'olsr'): ns3::olsr::Association [struct]
module.add_class('Association')
## olsr-repositories.h (module 'olsr'): ns3::olsr::AssociationTuple [struct]
module.add_class('AssociationTuple')
## olsr-repositories.h (module 'olsr'): ns3::olsr::DuplicateTuple [struct]
module.add_class('DuplicateTuple')
## olsr-repositories.h (module 'olsr'): ns3::olsr::IfaceAssocTuple [struct]
module.add_class('IfaceAssocTuple')
## olsr-repositories.h (module 'olsr'): ns3::olsr::LinkTuple [struct]
module.add_class('LinkTuple')
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader [class]
module.add_class('MessageHeader', parent=root_module['ns3::Header'])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::MessageType [enumeration]
module.add_enum('MessageType', ['HELLO_MESSAGE', 'TC_MESSAGE', 'MID_MESSAGE', 'HNA_MESSAGE'], outer_class=root_module['ns3::olsr::MessageHeader'])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello [struct]
module.add_class('Hello', outer_class=root_module['ns3::olsr::MessageHeader'])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::LinkMessage [struct]
module.add_class('LinkMessage', outer_class=root_module['ns3::olsr::MessageHeader::Hello'])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna [struct]
module.add_class('Hna', outer_class=root_module['ns3::olsr::MessageHeader'])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna::Association [struct]
module.add_class('Association', outer_class=root_module['ns3::olsr::MessageHeader::Hna'])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Mid [struct]
module.add_class('Mid', outer_class=root_module['ns3::olsr::MessageHeader'])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Tc [struct]
module.add_class('Tc', outer_class=root_module['ns3::olsr::MessageHeader'])
## olsr-repositories.h (module 'olsr'): ns3::olsr::MprSelectorTuple [struct]
module.add_class('MprSelectorTuple')
## olsr-repositories.h (module 'olsr'): ns3::olsr::NeighborTuple [struct]
module.add_class('NeighborTuple')
## olsr-repositories.h (module 'olsr'): ns3::olsr::NeighborTuple::Status [enumeration]
module.add_enum('Status', ['STATUS_NOT_SYM', 'STATUS_SYM'], outer_class=root_module['ns3::olsr::NeighborTuple'])
## olsr-state.h (module 'olsr'): ns3::olsr::OlsrState [class]
module.add_class('OlsrState')
## olsr-header.h (module 'olsr'): ns3::olsr::PacketHeader [class]
module.add_class('PacketHeader', parent=root_module['ns3::Header'])
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingProtocol [class]
module.add_class('RoutingProtocol', parent=root_module['ns3::Ipv4RoutingProtocol'])
typehandlers.add_type_alias(u'void ( * ) ( ns3::olsr::PacketHeader const &, ns3::olsr::MessageList const & )', u'ns3::olsr::RoutingProtocol::PacketTxRxTracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( ns3::olsr::PacketHeader const &, ns3::olsr::MessageList const & )*', u'ns3::olsr::RoutingProtocol::PacketTxRxTracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::olsr::PacketHeader const &, ns3::olsr::MessageList const & )&', u'ns3::olsr::RoutingProtocol::PacketTxRxTracedCallback&')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t )', u'ns3::olsr::RoutingProtocol::TableChangeTracedCallback')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t )*', u'ns3::olsr::RoutingProtocol::TableChangeTracedCallback*')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t )&', u'ns3::olsr::RoutingProtocol::TableChangeTracedCallback&')
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingTableEntry [struct]
module.add_class('RoutingTableEntry')
## olsr-repositories.h (module 'olsr'): ns3::olsr::TopologyTuple [struct]
module.add_class('TopologyTuple')
## olsr-repositories.h (module 'olsr'): ns3::olsr::TwoHopNeighborTuple [struct]
module.add_class('TwoHopNeighborTuple')
module.add_container('std::vector< ns3::Ipv4Address >', 'ns3::Ipv4Address', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::MessageHeader::Hello::LinkMessage >', 'ns3::olsr::MessageHeader::Hello::LinkMessage', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::MessageHeader::Hna::Association >', 'ns3::olsr::MessageHeader::Hna::Association', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::MprSelectorTuple >', 'ns3::olsr::MprSelectorTuple', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::NeighborTuple >', 'ns3::olsr::NeighborTuple', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::TwoHopNeighborTuple >', 'ns3::olsr::TwoHopNeighborTuple', container_type=u'vector')
module.add_container('ns3::olsr::MprSet', 'ns3::Ipv4Address', container_type=u'set')
module.add_container('std::vector< ns3::olsr::LinkTuple >', 'ns3::olsr::LinkTuple', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::TopologyTuple >', 'ns3::olsr::TopologyTuple', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::IfaceAssocTuple >', 'ns3::olsr::IfaceAssocTuple', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::AssociationTuple >', 'ns3::olsr::AssociationTuple', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::Association >', 'ns3::olsr::Association', container_type=u'vector')
module.add_container('std::vector< ns3::olsr::RoutingTableEntry >', 'ns3::olsr::RoutingTableEntry', container_type=u'vector')
module.add_container('std::set< unsigned int >', 'unsigned int', container_type=u'set')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::MessageHeader >', u'ns3::olsr::MessageList')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::MessageHeader >*', u'ns3::olsr::MessageList*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::MessageHeader >&', u'ns3::olsr::MessageList&')
typehandlers.add_type_alias(u'std::set< ns3::Ipv4Address >', u'ns3::olsr::MprSet')
typehandlers.add_type_alias(u'std::set< ns3::Ipv4Address >*', u'ns3::olsr::MprSet*')
typehandlers.add_type_alias(u'std::set< ns3::Ipv4Address >&', u'ns3::olsr::MprSet&')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::MprSelectorTuple >', u'ns3::olsr::MprSelectorSet')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::MprSelectorTuple >*', u'ns3::olsr::MprSelectorSet*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::MprSelectorTuple >&', u'ns3::olsr::MprSelectorSet&')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::LinkTuple >', u'ns3::olsr::LinkSet')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::LinkTuple >*', u'ns3::olsr::LinkSet*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::LinkTuple >&', u'ns3::olsr::LinkSet&')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::NeighborTuple >', u'ns3::olsr::NeighborSet')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::NeighborTuple >*', u'ns3::olsr::NeighborSet*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::NeighborTuple >&', u'ns3::olsr::NeighborSet&')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::TwoHopNeighborTuple >', u'ns3::olsr::TwoHopNeighborSet')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::TwoHopNeighborTuple >*', u'ns3::olsr::TwoHopNeighborSet*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::TwoHopNeighborTuple >&', u'ns3::olsr::TwoHopNeighborSet&')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::TopologyTuple >', u'ns3::olsr::TopologySet')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::TopologyTuple >*', u'ns3::olsr::TopologySet*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::TopologyTuple >&', u'ns3::olsr::TopologySet&')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::DuplicateTuple >', u'ns3::olsr::DuplicateSet')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::DuplicateTuple >*', u'ns3::olsr::DuplicateSet*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::DuplicateTuple >&', u'ns3::olsr::DuplicateSet&')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::IfaceAssocTuple >', u'ns3::olsr::IfaceAssocSet')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::IfaceAssocTuple >*', u'ns3::olsr::IfaceAssocSet*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::IfaceAssocTuple >&', u'ns3::olsr::IfaceAssocSet&')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::AssociationTuple >', u'ns3::olsr::AssociationSet')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::AssociationTuple >*', u'ns3::olsr::AssociationSet*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::AssociationTuple >&', u'ns3::olsr::AssociationSet&')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::Association >', u'ns3::olsr::Associations')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::Association >*', u'ns3::olsr::Associations*')
typehandlers.add_type_alias(u'std::vector< ns3::olsr::Association >&', u'ns3::olsr::Associations&')
def register_types_ns3_tests(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_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeAccessor >'])
register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeChecker >'])
register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeValue >'])
register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, root_module['ns3::DefaultDeleter< ns3::CallbackImplBase >'])
register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, root_module['ns3::DefaultDeleter< ns3::EventImpl >'])
register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Hash::Implementation >'])
register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, root_module['ns3::DefaultDeleter< ns3::NixVector >'])
register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Packet >'])
register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::TraceSourceAccessor >'])
register_Ns3EventGarbageCollector_methods(root_module, root_module['ns3::EventGarbageCollector'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher'])
register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress'])
register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress'])
register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >'])
register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >'])
register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >'])
register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >'])
register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >'])
register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >'])
register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper'])
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_Ns3Mac8Address_methods(root_module, root_module['ns3::Mac8Address'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3NonCopyable_methods(root_module, root_module['ns3::NonCopyable'])
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_Ns3OlsrHelper_methods(root_module, root_module['ns3::OlsrHelper'])
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_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_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit'])
register_Ns3Timer_methods(root_module, root_module['ns3::Timer'])
register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl'])
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_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header'])
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__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >'])
register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >'])
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__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
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__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3Socket_methods(root_module, root_module['ns3::Socket'])
register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag'])
register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag'])
register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag'])
register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag'])
register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag'])
register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag'])
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_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_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_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable'])
register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable'])
register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable'])
register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor'])
register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
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_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4'])
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_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute'])
register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route'])
register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol'])
register_Ns3Ipv4StaticRouting_methods(root_module, root_module['ns3::Ipv4StaticRouting'])
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_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
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_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable'])
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_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Const_ns3OlsrPacketHeader___amp___Const_stdVector__lt__ns3OlsrMessageHeader__stdAllocator__lt__ns3OlsrMessageHeader__gt_____gt_____amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::olsr::PacketHeader &, const std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3Ipv4ListRouting_methods(root_module, root_module['ns3::Ipv4ListRouting'])
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'])
register_Ns3OlsrAssociation_methods(root_module, root_module['ns3::olsr::Association'])
register_Ns3OlsrAssociationTuple_methods(root_module, root_module['ns3::olsr::AssociationTuple'])
register_Ns3OlsrDuplicateTuple_methods(root_module, root_module['ns3::olsr::DuplicateTuple'])
register_Ns3OlsrIfaceAssocTuple_methods(root_module, root_module['ns3::olsr::IfaceAssocTuple'])
register_Ns3OlsrLinkTuple_methods(root_module, root_module['ns3::olsr::LinkTuple'])
register_Ns3OlsrMessageHeader_methods(root_module, root_module['ns3::olsr::MessageHeader'])
register_Ns3OlsrMessageHeaderHello_methods(root_module, root_module['ns3::olsr::MessageHeader::Hello'])
register_Ns3OlsrMessageHeaderHelloLinkMessage_methods(root_module, root_module['ns3::olsr::MessageHeader::Hello::LinkMessage'])
register_Ns3OlsrMessageHeaderHna_methods(root_module, root_module['ns3::olsr::MessageHeader::Hna'])
register_Ns3OlsrMessageHeaderHnaAssociation_methods(root_module, root_module['ns3::olsr::MessageHeader::Hna::Association'])
register_Ns3OlsrMessageHeaderMid_methods(root_module, root_module['ns3::olsr::MessageHeader::Mid'])
register_Ns3OlsrMessageHeaderTc_methods(root_module, root_module['ns3::olsr::MessageHeader::Tc'])
register_Ns3OlsrMprSelectorTuple_methods(root_module, root_module['ns3::olsr::MprSelectorTuple'])
register_Ns3OlsrNeighborTuple_methods(root_module, root_module['ns3::olsr::NeighborTuple'])
register_Ns3OlsrOlsrState_methods(root_module, root_module['ns3::olsr::OlsrState'])
register_Ns3OlsrPacketHeader_methods(root_module, root_module['ns3::olsr::PacketHeader'])
register_Ns3OlsrRoutingProtocol_methods(root_module, root_module['ns3::olsr::RoutingProtocol'])
register_Ns3OlsrRoutingTableEntry_methods(root_module, root_module['ns3::olsr::RoutingTableEntry'])
register_Ns3OlsrTopologyTuple_methods(root_module, root_module['ns3::olsr::TopologyTuple'])
register_Ns3OlsrTwoHopNeighborTuple_methods(root_module, root_module['ns3::olsr::TwoHopNeighborTuple'])
return
def register_Ns3Address_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_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) [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) [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<const ns3::AttributeChecker> 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'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::Begin() const [member function]
cls.add_method('Begin',
'ns3::AttributeConstructionList::CIterator',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::End() const [member function]
cls.add_method('End',
'ns3::AttributeConstructionList::CIterator',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<const ns3::AttributeChecker> 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) [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(ns3::Buffer const & o) [constructor]
cls.add_constructor([param('ns3::Buffer const &', 'o')])
## 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'): 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) [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::GetRemainingSize() const [member function]
cls.add_method('GetRemainingSize',
'uint32_t',
[],
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) [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) [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) [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) [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) [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) [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_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, cls):
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter() [constructor]
cls.add_constructor([])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeAccessor> const & arg0) [constructor]
cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeAccessor > const &', 'arg0')])
## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeAccessor>::Delete(ns3::AttributeAccessor * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::AttributeAccessor *', 'object')],
is_static=True)
return
def register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, cls):
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter() [constructor]
cls.add_constructor([])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeChecker> const & arg0) [constructor]
cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeChecker > const &', 'arg0')])
## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeChecker>::Delete(ns3::AttributeChecker * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::AttributeChecker *', 'object')],
is_static=True)
return
def register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, cls):
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter() [constructor]
cls.add_constructor([])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeValue> const & arg0) [constructor]
cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeValue > const &', 'arg0')])
## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeValue>::Delete(ns3::AttributeValue * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::AttributeValue *', 'object')],
is_static=True)
return
def register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, cls):
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter() [constructor]
cls.add_constructor([])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter(ns3::DefaultDeleter<ns3::CallbackImplBase> const & arg0) [constructor]
cls.add_constructor([param('ns3::DefaultDeleter< ns3::CallbackImplBase > const &', 'arg0')])
## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::CallbackImplBase>::Delete(ns3::CallbackImplBase * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::CallbackImplBase *', 'object')],
is_static=True)
return
def register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, cls):
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter() [constructor]
cls.add_constructor([])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter(ns3::DefaultDeleter<ns3::EventImpl> const & arg0) [constructor]
cls.add_constructor([param('ns3::DefaultDeleter< ns3::EventImpl > const &', 'arg0')])
## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::EventImpl>::Delete(ns3::EventImpl * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::EventImpl *', 'object')],
is_static=True)
return
def register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, cls):
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter() [constructor]
cls.add_constructor([])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter(ns3::DefaultDeleter<ns3::Hash::Implementation> const & arg0) [constructor]
cls.add_constructor([param('ns3::DefaultDeleter< ns3::Hash::Implementation > const &', 'arg0')])
## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Hash::Implementation>::Delete(ns3::Hash::Implementation * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Hash::Implementation *', 'object')],
is_static=True)
return
def register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, cls):
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter() [constructor]
cls.add_constructor([])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter(ns3::DefaultDeleter<ns3::NixVector> const & arg0) [constructor]
cls.add_constructor([param('ns3::DefaultDeleter< ns3::NixVector > const &', 'arg0')])
## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::NixVector>::Delete(ns3::NixVector * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::NixVector *', 'object')],
is_static=True)
return
def register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, cls):
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter() [constructor]
cls.add_constructor([])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter(ns3::DefaultDeleter<ns3::Packet> const & arg0) [constructor]
cls.add_constructor([param('ns3::DefaultDeleter< ns3::Packet > const &', 'arg0')])
## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Packet>::Delete(ns3::Packet * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Packet *', 'object')],
is_static=True)
return
def register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, cls):
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter() [constructor]
cls.add_constructor([])
## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::TraceSourceAccessor> const & arg0) [constructor]
cls.add_constructor([param('ns3::DefaultDeleter< ns3::TraceSourceAccessor > const &', 'arg0')])
## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::TraceSourceAccessor>::Delete(ns3::TraceSourceAccessor * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::TraceSourceAccessor *', 'object')],
is_static=True)
return
def register_Ns3EventGarbageCollector_methods(root_module, cls):
## event-garbage-collector.h (module 'core'): ns3::EventGarbageCollector::EventGarbageCollector() [constructor]
cls.add_constructor([])
## event-garbage-collector.h (module 'core'): void ns3::EventGarbageCollector::Track(ns3::EventId event) [member function]
cls.add_method('Track',
'void',
[param('ns3::EventId', 'event')])
## event-garbage-collector.h (module 'core'): ns3::EventGarbageCollector::EventGarbageCollector(ns3::EventGarbageCollector const & arg0) [constructor]
cls.add_constructor([param('ns3::EventGarbageCollector const &', 'arg0')])
return
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [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) [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, std::size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('std::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, std::size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('std::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_Ns3Inet6SocketAddress_methods(root_module, cls):
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [constructor]
cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor]
cls.add_constructor([param('char const *', 'ipv6')])
## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function]
cls.add_method('ConvertFrom',
'ns3::Inet6SocketAddress',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function]
cls.add_method('GetIpv6',
'ns3::Ipv6Address',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function]
cls.add_method('SetIpv6',
'void',
[param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function]
cls.add_method('SetPort',
'void',
[param('uint16_t', 'port')])
return
def register_Ns3InetSocketAddress_methods(root_module, cls):
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [constructor]
cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor]
cls.add_constructor([param('char const *', 'ipv4')])
## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::InetSocketAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function]
cls.add_method('GetIpv4',
'ns3::Ipv4Address',
[],
is_const=True)
## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet-socket-address.h (module 'network'): uint8_t ns3::InetSocketAddress::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ipv4Address', 'address')])
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function]
cls.add_method('SetPort',
'void',
[param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
return
def register_Ns3IntToType__0_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [constructor]
cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')])
return
def register_Ns3IntToType__1_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [constructor]
cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')])
return
def register_Ns3IntToType__2_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [constructor]
cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')])
return
def register_Ns3IntToType__3_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [constructor]
cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')])
return
def register_Ns3IntToType__4_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [constructor]
cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')])
return
def register_Ns3IntToType__5_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [constructor]
cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')])
return
def register_Ns3IntToType__6_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [constructor]
cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')])
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [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_Ns3Ipv4InterfaceAddress_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor]
cls.add_constructor([])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [constructor]
cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function]
cls.add_method('GetLocal',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function]
cls.add_method('GetMask',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function]
cls.add_method('GetScope',
'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function]
cls.add_method('IsSecondary',
'bool',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function]
cls.add_method('SetBroadcast',
'void',
[param('ns3::Ipv4Address', 'broadcast')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function]
cls.add_method('SetLocal',
'void',
[param('ns3::Ipv4Address', 'local')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function]
cls.add_method('SetMask',
'void',
[param('ns3::Ipv4Mask', 'mask')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function]
cls.add_method('SetPrimary',
'void',
[])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SetScope',
'void',
[param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function]
cls.add_method('SetSecondary',
'void',
[])
return
def register_Ns3Ipv4Mask_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [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_Ns3Ipv4RoutingHelper_methods(root_module, cls):
## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper() [constructor]
cls.add_constructor([])
## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper(ns3::Ipv4RoutingHelper const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4RoutingHelper const &', 'arg0')])
## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper * ns3::Ipv4RoutingHelper::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ipv4RoutingHelper *',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4-routing-helper.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4RoutingHelper::Create(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintNeighborCacheAllAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintNeighborCacheAllEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintNeighborCacheAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('PrintNeighborCacheEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function]
cls.add_method('PrintRoutingTableAllAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function]
cls.add_method('PrintRoutingTableAllEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function]
cls.add_method('PrintRoutingTableAt',
'void',
[param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')],
is_static=True)
## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function]
cls.add_method('PrintRoutingTableEvery',
'void',
[param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')],
is_static=True)
return
def register_Ns3Ipv6Address_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_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) [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::MakeAutoconfiguredAddress(ns3::Mac8Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac8Address', '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::MakeAutoconfiguredLinkLocalAddress(ns3::Mac8Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac8Address', '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_output_stream_operator()
cls.add_binary_comparison_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) [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_binary_comparison_operator('<')
cls.add_output_stream_operator()
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [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_Ns3Mac8Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
## mac8-address.h (module 'network'): ns3::Mac8Address::Mac8Address(ns3::Mac8Address const & arg0) [constructor]
cls.add_constructor([param('ns3::Mac8Address const &', 'arg0')])
## mac8-address.h (module 'network'): ns3::Mac8Address::Mac8Address() [constructor]
cls.add_constructor([])
## mac8-address.h (module 'network'): ns3::Mac8Address::Mac8Address(uint8_t addr) [constructor]
cls.add_constructor([param('uint8_t', 'addr')])
## mac8-address.h (module 'network'): static ns3::Mac8Address ns3::Mac8Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac8Address',
[],
is_static=True)
## mac8-address.h (module 'network'): static ns3::Mac8Address ns3::Mac8Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac8Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac8-address.h (module 'network'): void ns3::Mac8Address::CopyFrom(uint8_t const * pBuffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'pBuffer')])
## mac8-address.h (module 'network'): void ns3::Mac8Address::CopyTo(uint8_t * pBuffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'pBuffer')],
is_const=True)
## mac8-address.h (module 'network'): static ns3::Mac8Address ns3::Mac8Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Mac8Address',
[],
is_static=True)
## mac8-address.h (module 'network'): static bool ns3::Mac8Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3NodeContainer_methods(root_module, cls):
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [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'): ns3::NodeContainer::Iterator ns3::NodeContainer::Begin() const [member function]
cls.add_method('Begin',
'ns3::NodeContainer::Iterator',
[],
is_const=True)
## node-container.h (module 'network'): bool ns3::NodeContainer::Contains(uint32_t id) const [member function]
cls.add_method('Contains',
'bool',
[param('uint32_t', 'id')],
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'): ns3::NodeContainer::Iterator ns3::NodeContainer::End() const [member function]
cls.add_method('End',
'ns3::NodeContainer::Iterator',
[],
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_Ns3NonCopyable_methods(root_module, cls):
## non-copyable.h (module 'core'): ns3::NonCopyable::NonCopyable() [constructor]
cls.add_constructor([],
visibility='protected')
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) [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) [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) [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_Ns3OlsrHelper_methods(root_module, cls):
## olsr-helper.h (module 'olsr'): ns3::OlsrHelper::OlsrHelper() [constructor]
cls.add_constructor([])
## olsr-helper.h (module 'olsr'): ns3::OlsrHelper::OlsrHelper(ns3::OlsrHelper const & arg0) [constructor]
cls.add_constructor([param('ns3::OlsrHelper const &', 'arg0')])
## olsr-helper.h (module 'olsr'): ns3::OlsrHelper * ns3::OlsrHelper::Copy() const [member function]
cls.add_method('Copy',
'ns3::OlsrHelper *',
[],
is_const=True, is_virtual=True)
## olsr-helper.h (module 'olsr'): void ns3::OlsrHelper::ExcludeInterface(ns3::Ptr<ns3::Node> node, uint32_t interface) [member function]
cls.add_method('ExcludeInterface',
'void',
[param('ns3::Ptr< ns3::Node >', 'node'), param('uint32_t', 'interface')])
## olsr-helper.h (module 'olsr'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::OlsrHelper::Create(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True, is_virtual=True)
## olsr-helper.h (module 'olsr'): void ns3::OlsrHelper::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## olsr-helper.h (module 'olsr'): int64_t ns3::OlsrHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')])
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) [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) [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)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::type [variable]
cls.add_instance_attribute('type', 'ns3::PacketMetadata::Item::ItemType', 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) [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) [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) [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) [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) [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 [ 1 ]', 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::size [variable]
cls.add_instance_attribute('size', 'uint32_t', 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_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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [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_Ns3SystemWallClockMs_methods(root_module, cls):
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [constructor]
cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')])
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor]
cls.add_constructor([])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function]
cls.add_method('End',
'int64_t',
[])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function]
cls.add_method('GetElapsedReal',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function]
cls.add_method('GetElapsedSystem',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function]
cls.add_method('GetElapsedUser',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function]
cls.add_method('Start',
'void',
[])
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) [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) [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 v) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t v) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'v')])
## 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_Ns3TimeWithUnit_methods(root_module, cls):
cls.add_output_stream_operator()
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [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_Ns3Timer_methods(root_module, cls):
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [constructor]
cls.add_constructor([param('ns3::Timer const &', 'arg0')])
## timer.h (module 'core'): ns3::Timer::Timer() [constructor]
cls.add_constructor([])
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor]
cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')])
## timer.h (module 'core'): void ns3::Timer::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function]
cls.add_method('GetState',
'ns3::Timer::State',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function]
cls.add_method('IsSuspended',
'bool',
[],
is_const=True)
## timer.h (module 'core'): void ns3::Timer::Remove() [member function]
cls.add_method('Remove',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Resume() [member function]
cls.add_method('Resume',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule() [member function]
cls.add_method('Schedule',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function]
cls.add_method('Schedule',
'void',
[param('ns3::Time', 'delay')])
## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function]
cls.add_method('SetDelay',
'void',
[param('ns3::Time const &', 'delay')])
## timer.h (module 'core'): void ns3::Timer::Suspend() [member function]
cls.add_method('Suspend',
'void',
[])
return
def register_Ns3TimerImpl_methods(root_module, cls):
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor]
cls.add_constructor([])
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [constructor]
cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')])
## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function]
cls.add_method('Schedule',
'ns3::EventId',
[param('ns3::Time const &', 'delay')],
is_pure_virtual=True, is_virtual=True)
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) [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<const ns3::AttributeAccessor> accessor, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::SUPPORTED, std::string const & supportMsg="") [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'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SupportLevel::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')])
## 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<const ns3::AttributeAccessor> accessor, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::SUPPORTED, std::string const & supportMsg="") [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'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SupportLevel::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<const ns3::TraceSourceAccessor> 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<const ns3::TraceSourceAccessor> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::SUPPORTED, std::string const & supportMsg="") [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'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SupportLevel::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(std::size_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('std::size_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(std::size_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('std::size_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::size_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'std::size_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'): ns3::TypeId::hash_t ns3::TypeId::GetHash() const [member function]
cls.add_method('GetHash',
'ns3::TypeId::hash_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(uint16_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint16_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint16_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint16_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(std::size_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('std::size_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::size_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'std::size_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(ns3::TypeId::hash_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(ns3::TypeId::hash_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<const ns3::TraceSourceAccessor> 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'): ns3::Ptr<const ns3::TraceSourceAccessor> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')],
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(std::size_t i, ns3::Ptr<const ns3::AttributeValue> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('std::size_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 uid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'uid')])
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) [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)
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)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable]
cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable]
cls.add_instance_attribute('supportMsg', 'std::string', 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) [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)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable]
cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable]
cls.add_instance_attribute('supportMsg', 'std::string', 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) [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_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_output_stream_operator()
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_unary_numeric_operator('-')
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(double const value) [constructor]
cls.add_constructor([param('double const', 'value')])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long double const value) [constructor]
cls.add_constructor([param('long double const', 'value')])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(int const v) [constructor]
cls.add_constructor([param('int const', 'v')])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long int const v) [constructor]
cls.add_constructor([param('long int const', 'v')])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int const v) [constructor]
cls.add_constructor([param('long long int const', 'v')])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int const v) [constructor]
cls.add_constructor([param('unsigned int const', 'v')])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int const v) [constructor]
cls.add_constructor([param('long unsigned int const', 'v')])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int const v) [constructor]
cls.add_constructor([param('long long unsigned int const', 'v')])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t const hi, uint64_t const lo) [constructor]
cls.add_constructor([param('int64_t const', 'hi'), param('uint64_t const', 'lo')])
## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-128.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-128.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-128.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-128.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t const v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t const', 'v')],
is_static=True)
## int64x64-128.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-128.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_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) [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'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')],
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) [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_Ns3Ipv4Header_methods(root_module, cls):
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor]
cls.add_constructor([])
## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function]
cls.add_method('DscpTypeToString',
'std::string',
[param('ns3::Ipv4Header::DscpType', 'dscp')],
is_const=True)
## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function]
cls.add_method('EcnTypeToString',
'std::string',
[param('ns3::Ipv4Header::EcnType', 'ecn')],
is_const=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function]
cls.add_method('EnableChecksum',
'void',
[])
## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function]
cls.add_method('GetDscp',
'ns3::Ipv4Header::DscpType',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function]
cls.add_method('GetEcn',
'ns3::Ipv4Header::EcnType',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function]
cls.add_method('GetFragmentOffset',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function]
cls.add_method('GetIdentification',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function]
cls.add_method('GetPayloadSize',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function]
cls.add_method('GetTtl',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function]
cls.add_method('IsChecksumOk',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function]
cls.add_method('IsDontFragment',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function]
cls.add_method('IsLastFragment',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'destination')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function]
cls.add_method('SetDontFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function]
cls.add_method('SetDscp',
'void',
[param('ns3::Ipv4Header::DscpType', 'dscp')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function]
cls.add_method('SetEcn',
'void',
[param('ns3::Ipv4Header::EcnType', 'ecn')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function]
cls.add_method('SetFragmentOffset',
'void',
[param('uint16_t', 'offsetBytes')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function]
cls.add_method('SetIdentification',
'void',
[param('uint16_t', 'identification')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function]
cls.add_method('SetLastFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function]
cls.add_method('SetMayFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function]
cls.add_method('SetMoreFragments',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function]
cls.add_method('SetPayloadSize',
'void',
[param('uint16_t', 'size')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function]
cls.add_method('SetProtocol',
'void',
[param('uint8_t', 'num')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 'source')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function]
cls.add_method('SetTtl',
'void',
[param('uint8_t', 'ttl')])
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'): bool ns3::Object::IsInitialized() const [member function]
cls.add_method('IsInitialized',
'bool',
[],
is_const=True)
## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [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) [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<const ns3::Object> 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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')])
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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')])
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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')])
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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')])
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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')])
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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')])
return
def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')])
return
def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')])
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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')])
return
def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')])
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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')])
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) [constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')])
return
def register_Ns3Socket_methods(root_module, cls):
## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [constructor]
cls.add_constructor([param('ns3::Socket const &', 'arg0')])
## socket.h (module 'network'): ns3::Socket::Socket() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function]
cls.add_method('Bind',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind() [member function]
cls.add_method('Bind',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind6() [member function]
cls.add_method('Bind6',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function]
cls.add_method('BindToNetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'netdevice')],
is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Close() [member function]
cls.add_method('Close',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function]
cls.add_method('Connect',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')],
is_static=True)
## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function]
cls.add_method('GetAllowBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function]
cls.add_method('GetBoundNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[])
## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function]
cls.add_method('GetErrno',
'ns3::Socket::SocketErrno',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function]
cls.add_method('GetIpTos',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function]
cls.add_method('GetIpTtl',
'uint8_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function]
cls.add_method('GetIpv6HopLimit',
'uint8_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function]
cls.add_method('GetIpv6Tclass',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function]
cls.add_method('GetPeerName',
'int',
[param('ns3::Address &', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function]
cls.add_method('GetPriority',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function]
cls.add_method('GetRxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function]
cls.add_method('GetSockName',
'int',
[param('ns3::Address &', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function]
cls.add_method('GetSocketType',
'ns3::Socket::SocketType',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function]
cls.add_method('GetTxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function]
cls.add_method('IpTos2Priority',
'uint8_t',
[param('uint8_t', 'ipTos')],
is_static=True)
## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address, std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function]
cls.add_method('Ipv6JoinGroup',
'void',
[param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function]
cls.add_method('Ipv6JoinGroup',
'void',
[param('ns3::Ipv6Address', 'address')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function]
cls.add_method('Ipv6LeaveGroup',
'void',
[],
is_virtual=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function]
cls.add_method('IsIpRecvTos',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function]
cls.add_method('IsIpRecvTtl',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function]
cls.add_method('IsIpv6RecvHopLimit',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function]
cls.add_method('IsIpv6RecvTclass',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function]
cls.add_method('IsRecvPktInfo',
'bool',
[],
is_const=True)
## socket.h (module 'network'): int ns3::Socket::Listen() [member function]
cls.add_method('Listen',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[])
## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Recv',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function]
cls.add_method('SendTo',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function]
cls.add_method('SendTo',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')])
## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function]
cls.add_method('SetAcceptCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')])
## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function]
cls.add_method('SetAllowBroadcast',
'bool',
[param('bool', 'allowBroadcast')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function]
cls.add_method('SetCloseCallbacks',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')])
## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function]
cls.add_method('SetConnectCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')])
## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function]
cls.add_method('SetDataSentCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')])
## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function]
cls.add_method('SetIpRecvTos',
'void',
[param('bool', 'ipv4RecvTos')])
## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function]
cls.add_method('SetIpRecvTtl',
'void',
[param('bool', 'ipv4RecvTtl')])
## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function]
cls.add_method('SetIpTos',
'void',
[param('uint8_t', 'ipTos')])
## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function]
cls.add_method('SetIpTtl',
'void',
[param('uint8_t', 'ipTtl')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function]
cls.add_method('SetIpv6HopLimit',
'void',
[param('uint8_t', 'ipHopLimit')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function]
cls.add_method('SetIpv6RecvHopLimit',
'void',
[param('bool', 'ipv6RecvHopLimit')])
## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function]
cls.add_method('SetIpv6RecvTclass',
'void',
[param('bool', 'ipv6RecvTclass')])
## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function]
cls.add_method('SetIpv6Tclass',
'void',
[param('int', 'ipTclass')])
## socket.h (module 'network'): void ns3::Socket::SetPriority(uint8_t priority) [member function]
cls.add_method('SetPriority',
'void',
[param('uint8_t', 'priority')])
## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function]
cls.add_method('SetRecvCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')])
## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function]
cls.add_method('SetRecvPktInfo',
'void',
[param('bool', 'flag')])
## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function]
cls.add_method('SetSendCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')])
## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function]
cls.add_method('ShutdownRecv',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function]
cls.add_method('ShutdownSend',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function]
cls.add_method('IsManualIpTtl',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function]
cls.add_method('IsManualIpv6HopLimit',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function]
cls.add_method('IsManualIpv6Tclass',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function]
cls.add_method('NotifyConnectionFailed',
'void',
[],
visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function]
cls.add_method('NotifyConnectionRequest',
'bool',
[param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function]
cls.add_method('NotifyConnectionSucceeded',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function]
cls.add_method('NotifyDataRecv',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function]
cls.add_method('NotifyDataSent',
'void',
[param('uint32_t', 'size')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function]
cls.add_method('NotifyErrorClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function]
cls.add_method('NotifyNewConnectionCreated',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function]
cls.add_method('NotifyNormalClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function]
cls.add_method('NotifySend',
'void',
[param('uint32_t', 'spaceAvailable')],
visibility='protected')
return
def register_Ns3SocketIpTosTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [constructor]
cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
return
def register_Ns3SocketIpTtlTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [constructor]
cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function]
cls.add_method('GetTtl',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function]
cls.add_method('SetTtl',
'void',
[param('uint8_t', 'ttl')])
return
def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [constructor]
cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function]
cls.add_method('GetHopLimit',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function]
cls.add_method('SetHopLimit',
'void',
[param('uint8_t', 'hopLimit')])
return
def register_Ns3SocketIpv6TclassTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [constructor]
cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function]
cls.add_method('GetTclass',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function]
cls.add_method('SetTclass',
'void',
[param('uint8_t', 'tclass')])
return
def register_Ns3SocketPriorityTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [constructor]
cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketPriorityTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketPriorityTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function]
cls.add_method('GetPriority',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketPriorityTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketPriorityTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketPriorityTag::SetPriority(uint8_t priority) [member function]
cls.add_method('SetPriority',
'void',
[param('uint8_t', 'priority')])
return
def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [constructor]
cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
return
def register_Ns3Time_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('>=')
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
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_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right'))
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()
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [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) [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) [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::Deserialize(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')],
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_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) [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) [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) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_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) [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) [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<const ns3::CallbackImplBase> 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')
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'ns3::ObjectBase*'])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'void'])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::NetDevice> '])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Packet const> '])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'unsigned short'])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'ns3::Address const&'])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'ns3::NetDevice::PacketType'])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Socket> '])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'bool'])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'unsigned int'])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'ns3::olsr::PacketHeader const&'])
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function]
cls.add_method('GetCppTypeid',
'std::string',
[],
is_static=True, visibility='protected', template_parameters=[u'std::vector<ns3::olsr::MessageHeader', u' std::allocator<ns3::olsr::MessageHeader> > const&'])
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_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, std::size_t length) [member function]
cls.add_method('SetValueArray',
'void',
[param('double *', 'values'), param('std::size_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_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_Ns3EmptyAttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [constructor]
cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::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_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
return
def register_Ns3EmptyAttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [constructor]
cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::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_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_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) [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_Ns3Ipv4_methods(root_module, cls):
## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')])
## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor]
cls.add_constructor([])
## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('AddAddress',
'bool',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddInterface',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function]
cls.add_method('CreateRawSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function]
cls.add_method('DeleteRawSocket',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv4InterfaceAddress',
[param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function]
cls.add_method('GetInterfaceForAddress',
'int32_t',
[param('ns3::Ipv4Address', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function]
cls.add_method('GetInterfaceForDevice',
'int32_t',
[param('ns3::Ptr< ns3::NetDevice const >', 'device')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function]
cls.add_method('GetInterfaceForPrefix',
'int32_t',
[param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function]
cls.add_method('GetMetric',
'uint16_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function]
cls.add_method('GetMtu',
'uint16_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function]
cls.add_method('GetNInterfaces',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function]
cls.add_method('GetNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function]
cls.add_method('GetProtocol',
'ns3::Ptr< ns3::IpL4Protocol >',
[param('int', 'protocolNumber')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function]
cls.add_method('GetProtocol',
'ns3::Ptr< ns3::IpL4Protocol >',
[param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function]
cls.add_method('GetRoutingProtocol',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function]
cls.add_method('IsDestinationAddress',
'bool',
[param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function]
cls.add_method('IsForwarding',
'bool',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function]
cls.add_method('IsUp',
'bool',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function]
cls.add_method('Remove',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function]
cls.add_method('Remove',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function]
cls.add_method('RemoveAddress',
'bool',
[param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function]
cls.add_method('RemoveAddress',
'bool',
[param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SelectSourceAddress',
'ns3::Ipv4Address',
[param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('SendWithHeader',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function]
cls.add_method('SetDown',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function]
cls.add_method('SetForwarding',
'void',
[param('uint32_t', 'interface'), param('bool', 'val')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint32_t', 'interface'), param('uint16_t', 'metric')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function]
cls.add_method('SetRoutingProtocol',
'void',
[param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function]
cls.add_method('SetUp',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function]
cls.add_method('SourceAddressSelection',
'ns3::Ipv4Address',
[param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable]
cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function]
cls.add_method('GetIpForward',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function]
cls.add_method('GetWeakEsModel',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function]
cls.add_method('SetIpForward',
'void',
[param('bool', 'forward')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function]
cls.add_method('SetWeakEsModel',
'void',
[param('bool', 'model')],
is_pure_virtual=True, visibility='private', is_virtual=True)
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) [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::Ipv4Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')])
## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Ipv4Mask const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')])
## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3Ipv4MulticastRoute_methods(root_module, cls):
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function]
cls.add_method('GetGroup',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function]
cls.add_method('GetOrigin',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<const unsigned int, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function]
cls.add_method('GetOutputTtlMap',
'std::map< unsigned int, unsigned int >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function]
cls.add_method('GetParent',
'uint32_t',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function]
cls.add_method('SetGroup',
'void',
[param('ns3::Ipv4Address const', 'group')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function]
cls.add_method('SetOrigin',
'void',
[param('ns3::Ipv4Address const', 'origin')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function]
cls.add_method('SetOutputTtl',
'void',
[param('uint32_t', 'oif'), param('uint32_t', 'ttl')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function]
cls.add_method('SetParent',
'void',
[param('uint32_t', 'iif')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable]
cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable]
cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True)
return
def register_Ns3Ipv4Route_methods(root_module, cls):
cls.add_output_stream_operator()
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function]
cls.add_method('GetGateway',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function]
cls.add_method('GetOutputDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'dest')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function]
cls.add_method('SetGateway',
'void',
[param('ns3::Ipv4Address', 'gw')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function]
cls.add_method('SetOutputDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 'src')])
return
def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls):
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor]
cls.add_constructor([])
## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')])
## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function]
cls.add_method('RouteInput',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
is_pure_virtual=True, is_virtual=True)
## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3Ipv4StaticRouting_methods(root_module, cls):
## ipv4-static-routing.h (module 'internet'): ns3::Ipv4StaticRouting::Ipv4StaticRouting(ns3::Ipv4StaticRouting const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4StaticRouting const &', 'arg0')])
## ipv4-static-routing.h (module 'internet'): ns3::Ipv4StaticRouting::Ipv4StaticRouting() [constructor]
cls.add_constructor([])
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::AddHostRouteTo(ns3::Ipv4Address dest, ns3::Ipv4Address nextHop, uint32_t interface, uint32_t metric=0) [member function]
cls.add_method('AddHostRouteTo',
'void',
[param('ns3::Ipv4Address', 'dest'), param('ns3::Ipv4Address', 'nextHop'), param('uint32_t', 'interface'), param('uint32_t', 'metric', default_value='0')])
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::AddHostRouteTo(ns3::Ipv4Address dest, uint32_t interface, uint32_t metric=0) [member function]
cls.add_method('AddHostRouteTo',
'void',
[param('ns3::Ipv4Address', 'dest'), param('uint32_t', 'interface'), param('uint32_t', 'metric', default_value='0')])
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::AddMulticastRoute(ns3::Ipv4Address origin, ns3::Ipv4Address group, uint32_t inputInterface, std::vector<unsigned int, std::allocator<unsigned int> > outputInterfaces) [member function]
cls.add_method('AddMulticastRoute',
'void',
[param('ns3::Ipv4Address', 'origin'), param('ns3::Ipv4Address', 'group'), param('uint32_t', 'inputInterface'), param('std::vector< unsigned int >', 'outputInterfaces')])
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::AddNetworkRouteTo(ns3::Ipv4Address network, ns3::Ipv4Mask networkMask, ns3::Ipv4Address nextHop, uint32_t interface, uint32_t metric=0) [member function]
cls.add_method('AddNetworkRouteTo',
'void',
[param('ns3::Ipv4Address', 'network'), param('ns3::Ipv4Mask', 'networkMask'), param('ns3::Ipv4Address', 'nextHop'), param('uint32_t', 'interface'), param('uint32_t', 'metric', default_value='0')])
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::AddNetworkRouteTo(ns3::Ipv4Address network, ns3::Ipv4Mask networkMask, uint32_t interface, uint32_t metric=0) [member function]
cls.add_method('AddNetworkRouteTo',
'void',
[param('ns3::Ipv4Address', 'network'), param('ns3::Ipv4Mask', 'networkMask'), param('uint32_t', 'interface'), param('uint32_t', 'metric', default_value='0')])
## ipv4-static-routing.h (module 'internet'): ns3::Ipv4RoutingTableEntry ns3::Ipv4StaticRouting::GetDefaultRoute() [member function]
cls.add_method('GetDefaultRoute',
'ns3::Ipv4RoutingTableEntry',
[])
## ipv4-static-routing.h (module 'internet'): uint32_t ns3::Ipv4StaticRouting::GetMetric(uint32_t index) const [member function]
cls.add_method('GetMetric',
'uint32_t',
[param('uint32_t', 'index')],
is_const=True)
## ipv4-static-routing.h (module 'internet'): ns3::Ipv4MulticastRoutingTableEntry ns3::Ipv4StaticRouting::GetMulticastRoute(uint32_t i) const [member function]
cls.add_method('GetMulticastRoute',
'ns3::Ipv4MulticastRoutingTableEntry',
[param('uint32_t', 'i')],
is_const=True)
## ipv4-static-routing.h (module 'internet'): uint32_t ns3::Ipv4StaticRouting::GetNMulticastRoutes() const [member function]
cls.add_method('GetNMulticastRoutes',
'uint32_t',
[],
is_const=True)
## ipv4-static-routing.h (module 'internet'): uint32_t ns3::Ipv4StaticRouting::GetNRoutes() const [member function]
cls.add_method('GetNRoutes',
'uint32_t',
[],
is_const=True)
## ipv4-static-routing.h (module 'internet'): ns3::Ipv4RoutingTableEntry ns3::Ipv4StaticRouting::GetRoute(uint32_t i) const [member function]
cls.add_method('GetRoute',
'ns3::Ipv4RoutingTableEntry',
[param('uint32_t', 'i')],
is_const=True)
## ipv4-static-routing.h (module 'internet'): static ns3::TypeId ns3::Ipv4StaticRouting::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')],
is_const=True, is_virtual=True)
## ipv4-static-routing.h (module 'internet'): bool ns3::Ipv4StaticRouting::RemoveMulticastRoute(ns3::Ipv4Address origin, ns3::Ipv4Address group, uint32_t inputInterface) [member function]
cls.add_method('RemoveMulticastRoute',
'bool',
[param('ns3::Ipv4Address', 'origin'), param('ns3::Ipv4Address', 'group'), param('uint32_t', 'inputInterface')])
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::RemoveMulticastRoute(uint32_t index) [member function]
cls.add_method('RemoveMulticastRoute',
'void',
[param('uint32_t', 'index')])
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::RemoveRoute(uint32_t i) [member function]
cls.add_method('RemoveRoute',
'void',
[param('uint32_t', 'i')])
## ipv4-static-routing.h (module 'internet'): bool ns3::Ipv4StaticRouting::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function]
cls.add_method('RouteInput',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')],
is_virtual=True)
## ipv4-static-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4StaticRouting::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
is_virtual=True)
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::SetDefaultMulticastRoute(uint32_t outputInterface) [member function]
cls.add_method('SetDefaultMulticastRoute',
'void',
[param('uint32_t', 'outputInterface')])
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::SetDefaultRoute(ns3::Ipv4Address nextHop, uint32_t interface, uint32_t metric=0) [member function]
cls.add_method('SetDefaultRoute',
'void',
[param('ns3::Ipv4Address', 'nextHop'), param('uint32_t', 'interface'), param('uint32_t', 'metric', default_value='0')])
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
is_virtual=True)
## ipv4-static-routing.h (module 'internet'): void ns3::Ipv4StaticRouting::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
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) [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::Ipv6Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')])
## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Ipv6Prefix const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')])
## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Mac48Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'value')])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [constructor]
cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')])
## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_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) [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::NetDevice::PromiscReceiveCallback cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, 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 >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::NetDevice::ReceiveCallback 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_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) [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) [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::Node::DeviceAdditionListener 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::Node::ProtocolHandler 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::Node::DeviceAdditionListener 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::Node::ProtocolHandler 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) [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::ObjectFactory const & value) [constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'value')])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [constructor]
cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')])
## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3OutputStreamWrapper_methods(root_module, cls):
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [constructor]
cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::ios_base::openmode filemode) [constructor]
cls.add_constructor([param('std::string', 'filename'), param('std::ios_base::openmode', 'filemode')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor]
cls.add_constructor([param('std::ostream *', 'os')])
## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function]
cls.add_method('GetStream',
'std::ostream *',
[])
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) [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'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header, uint32_t size) const [member function]
cls.add_method('PeekHeader',
'uint32_t',
[param('ns3::Header &', 'header'), param('uint32_t', 'size')],
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'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'uint32_t',
[param('ns3::Header &', 'header'), param('uint32_t', 'size')])
## 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',
[],
deprecated=True, is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetScale() const [member function]
cls.add_method('GetScale',
'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 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::ParetoRandomVariable::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::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_Ns3TimeValue_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor]
cls.add_constructor([])
## 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::TimeValue::TimeValue(ns3::TimeValue const & arg0) [constructor]
cls.add_constructor([param('ns3::TimeValue const &', 'arg0')])
## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::TypeId const & value) [constructor]
cls.add_constructor([param('ns3::TypeId const &', 'value')])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [constructor]
cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')])
## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_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) [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::Address const & value) [constructor]
cls.add_constructor([param('ns3::Address const &', 'value')])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [constructor]
cls.add_constructor([param('ns3::AddressValue const &', 'arg0')])
## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor]
cls.add_constructor([param('ns3::CallbackImpl< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')])
## callback.h (module 'core'): static std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function]
cls.add_method('DoGetTypeid',
'std::string',
[],
is_static=True)
## callback.h (module 'core'): std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, ns3::Address const & arg1) [member operator]
cls.add_method('operator()',
'bool',
[param('ns3::Ptr< ns3::Socket >', 'arg0'), param('ns3::Address const &', 'arg1')],
is_pure_virtual=True, is_virtual=True, custom_name=u'__call__')
return
def register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor]
cls.add_constructor([param('ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')])
## callback.h (module 'core'): static std::string ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function]
cls.add_method('DoGetTypeid',
'std::string',
[],
is_static=True)
## callback.h (module 'core'): std::string ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): ns3::ObjectBase * ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()() [member operator]
cls.add_method('operator()',
'ns3::ObjectBase *',
[],
is_pure_virtual=True, is_virtual=True, custom_name=u'__call__')
return
def register_Ns3CallbackImpl__Void_Const_ns3OlsrPacketHeader___amp___Const_stdVector__lt__ns3OlsrMessageHeader__stdAllocator__lt__ns3OlsrMessageHeader__gt_____gt_____amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::olsr::PacketHeader &, const std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::olsr::PacketHeader &, const std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, const ns3::olsr::PacketHeader &, const std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor]
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::olsr::PacketHeader const &, std::vector< ns3::olsr::MessageHeader, std::allocator< ns3::olsr::MessageHeader > > const, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')])
## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, const ns3::olsr::PacketHeader &, const std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function]
cls.add_method('DoGetTypeid',
'std::string',
[],
is_static=True)
## callback.h (module 'core'): std::string ns3::CallbackImpl<void, const ns3::olsr::PacketHeader &, const std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackImpl<void, const ns3::olsr::PacketHeader &, const std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::olsr::PacketHeader const & arg0, std::vector<ns3::olsr::MessageHeader, std::allocator<ns3::olsr::MessageHeader> > const & arg1) [member operator]
cls.add_method('operator()',
'void',
[param('ns3::olsr::PacketHeader const &', 'arg0'), param('std::vector< ns3::olsr::MessageHeader > const &', 'arg1')],
is_pure_virtual=True, is_virtual=True, custom_name=u'__call__')
cls.add_copy_constructor()
return
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor]
cls.add_constructor([param('ns3::CallbackImpl< 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 > const &', 'arg0')])
## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function]
cls.add_method('DoGetTypeid',
'std::string',
[],
is_static=True)
## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0, ns3::Ptr<const ns3::Packet> arg1, short unsigned int arg2, ns3::Address const & arg3, ns3::Address const & arg4, ns3::NetDevice::PacketType arg5) [member operator]
cls.add_method('operator()',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('short unsigned int', 'arg2'), param('ns3::Address const &', 'arg3'), param('ns3::Address const &', 'arg4'), param('ns3::NetDevice::PacketType', 'arg5')],
is_pure_virtual=True, is_virtual=True, custom_name=u'__call__')
return
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor]
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')])
## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function]
cls.add_method('DoGetTypeid',
'std::string',
[],
is_static=True)
## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0) [member operator]
cls.add_method('operator()',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'arg0')],
is_pure_virtual=True, is_virtual=True, custom_name=u'__call__')
return
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor]
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')])
## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function]
cls.add_method('DoGetTypeid',
'std::string',
[],
is_static=True)
## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, ns3::Address const & arg1) [member operator]
cls.add_method('operator()',
'void',
[param('ns3::Ptr< ns3::Socket >', 'arg0'), param('ns3::Address const &', 'arg1')],
is_pure_virtual=True, is_virtual=True, custom_name=u'__call__')
return
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor]
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')])
## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function]
cls.add_method('DoGetTypeid',
'std::string',
[],
is_static=True)
## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0) [member operator]
cls.add_method('operator()',
'void',
[param('ns3::Ptr< ns3::Socket >', 'arg0')],
is_pure_virtual=True, is_virtual=True, custom_name=u'__call__')
return
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor]
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')])
## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function]
cls.add_method('DoGetTypeid',
'std::string',
[],
is_static=True)
## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, unsigned int arg1) [member operator]
cls.add_method('operator()',
'void',
[param('ns3::Ptr< ns3::Socket >', 'arg0'), param('unsigned int', 'arg1')],
is_pure_virtual=True, is_virtual=True, custom_name=u'__call__')
return
def register_Ns3CallbackImpl__Void_Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImpl<void, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImpl<void, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor]
cls.add_constructor([param('ns3::CallbackImpl< void, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')])
## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function]
cls.add_method('DoGetTypeid',
'std::string',
[],
is_static=True)
## callback.h (module 'core'): std::string ns3::CallbackImpl<void, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackImpl<void, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(unsigned int arg0) [member operator]
cls.add_method('operator()',
'void',
[param('unsigned int', 'arg0')],
is_pure_virtual=True, is_virtual=True, custom_name=u'__call__')
return
def register_Ns3Ipv4ListRouting_methods(root_module, cls):
## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting(ns3::Ipv4ListRouting const & arg0) [constructor]
cls.add_constructor([param('ns3::Ipv4ListRouting const &', 'arg0')])
## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting() [constructor]
cls.add_constructor([])
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::AddRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol, int16_t priority) [member function]
cls.add_method('AddRoutingProtocol',
'void',
[param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol'), param('int16_t', 'priority')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): uint32_t ns3::Ipv4ListRouting::GetNRoutingProtocols() const [member function]
cls.add_method('GetNRoutingProtocols',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4ListRouting::GetRoutingProtocol(uint32_t index, int16_t & priority) const [member function]
cls.add_method('GetRoutingProtocol',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[param('uint32_t', 'index'), param('int16_t &', 'priority', direction=2)],
is_const=True, is_virtual=True)
## ipv4-list-routing.h (module 'internet'): static ns3::TypeId ns3::Ipv4ListRouting::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')],
is_const=True, is_virtual=True)
## ipv4-list-routing.h (module 'internet'): bool ns3::Ipv4ListRouting::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function]
cls.add_method('RouteInput',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4ListRouting::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3HashImplementation_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [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, std::size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('std::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, std::size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('std::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) [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) [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, std::size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('std::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) [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, std::size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('std::size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, std::size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('std::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) [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, std::size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('std::size_t const', 'size')],
is_virtual=True)
## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, std::size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('std::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_Ns3OlsrAssociation_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_output_stream_operator()
## olsr-repositories.h (module 'olsr'): ns3::olsr::Association::Association() [constructor]
cls.add_constructor([])
## olsr-repositories.h (module 'olsr'): ns3::olsr::Association::Association(ns3::olsr::Association const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::Association const &', 'arg0')])
## olsr-repositories.h (module 'olsr'): ns3::olsr::Association::netmask [variable]
cls.add_instance_attribute('netmask', 'ns3::Ipv4Mask', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::Association::networkAddr [variable]
cls.add_instance_attribute('networkAddr', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3OlsrAssociationTuple_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_output_stream_operator()
## olsr-repositories.h (module 'olsr'): ns3::olsr::AssociationTuple::AssociationTuple() [constructor]
cls.add_constructor([])
## olsr-repositories.h (module 'olsr'): ns3::olsr::AssociationTuple::AssociationTuple(ns3::olsr::AssociationTuple const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::AssociationTuple const &', 'arg0')])
## olsr-repositories.h (module 'olsr'): ns3::olsr::AssociationTuple::expirationTime [variable]
cls.add_instance_attribute('expirationTime', 'ns3::Time', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::AssociationTuple::gatewayAddr [variable]
cls.add_instance_attribute('gatewayAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::AssociationTuple::netmask [variable]
cls.add_instance_attribute('netmask', 'ns3::Ipv4Mask', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::AssociationTuple::networkAddr [variable]
cls.add_instance_attribute('networkAddr', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3OlsrDuplicateTuple_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## olsr-repositories.h (module 'olsr'): ns3::olsr::DuplicateTuple::DuplicateTuple() [constructor]
cls.add_constructor([])
## olsr-repositories.h (module 'olsr'): ns3::olsr::DuplicateTuple::DuplicateTuple(ns3::olsr::DuplicateTuple const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::DuplicateTuple const &', 'arg0')])
## olsr-repositories.h (module 'olsr'): ns3::olsr::DuplicateTuple::address [variable]
cls.add_instance_attribute('address', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::DuplicateTuple::expirationTime [variable]
cls.add_instance_attribute('expirationTime', 'ns3::Time', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::DuplicateTuple::ifaceList [variable]
cls.add_instance_attribute('ifaceList', 'std::vector< ns3::Ipv4Address >', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::DuplicateTuple::retransmitted [variable]
cls.add_instance_attribute('retransmitted', 'bool', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::DuplicateTuple::sequenceNumber [variable]
cls.add_instance_attribute('sequenceNumber', 'uint16_t', is_const=False)
return
def register_Ns3OlsrIfaceAssocTuple_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_output_stream_operator()
## olsr-repositories.h (module 'olsr'): ns3::olsr::IfaceAssocTuple::IfaceAssocTuple() [constructor]
cls.add_constructor([])
## olsr-repositories.h (module 'olsr'): ns3::olsr::IfaceAssocTuple::IfaceAssocTuple(ns3::olsr::IfaceAssocTuple const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::IfaceAssocTuple const &', 'arg0')])
## olsr-repositories.h (module 'olsr'): ns3::olsr::IfaceAssocTuple::ifaceAddr [variable]
cls.add_instance_attribute('ifaceAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::IfaceAssocTuple::mainAddr [variable]
cls.add_instance_attribute('mainAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::IfaceAssocTuple::time [variable]
cls.add_instance_attribute('time', 'ns3::Time', is_const=False)
return
def register_Ns3OlsrLinkTuple_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_output_stream_operator()
## olsr-repositories.h (module 'olsr'): ns3::olsr::LinkTuple::LinkTuple() [constructor]
cls.add_constructor([])
## olsr-repositories.h (module 'olsr'): ns3::olsr::LinkTuple::LinkTuple(ns3::olsr::LinkTuple const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::LinkTuple const &', 'arg0')])
## olsr-repositories.h (module 'olsr'): ns3::olsr::LinkTuple::asymTime [variable]
cls.add_instance_attribute('asymTime', 'ns3::Time', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::LinkTuple::localIfaceAddr [variable]
cls.add_instance_attribute('localIfaceAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::LinkTuple::neighborIfaceAddr [variable]
cls.add_instance_attribute('neighborIfaceAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::LinkTuple::symTime [variable]
cls.add_instance_attribute('symTime', 'ns3::Time', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::LinkTuple::time [variable]
cls.add_instance_attribute('time', 'ns3::Time', is_const=False)
return
def register_Ns3OlsrMessageHeader_methods(root_module, cls):
cls.add_output_stream_operator()
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::MessageHeader(ns3::olsr::MessageHeader const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::MessageHeader const &', 'arg0')])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::MessageHeader() [constructor]
cls.add_constructor([])
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello & ns3::olsr::MessageHeader::GetHello() [member function]
cls.add_method('GetHello',
'ns3::olsr::MessageHeader::Hello &',
[])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello const & ns3::olsr::MessageHeader::GetHello() const [member function]
cls.add_method('GetHello',
'ns3::olsr::MessageHeader::Hello const &',
[],
is_const=True)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna & ns3::olsr::MessageHeader::GetHna() [member function]
cls.add_method('GetHna',
'ns3::olsr::MessageHeader::Hna &',
[])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna const & ns3::olsr::MessageHeader::GetHna() const [member function]
cls.add_method('GetHna',
'ns3::olsr::MessageHeader::Hna const &',
[],
is_const=True)
## olsr-header.h (module 'olsr'): uint8_t ns3::olsr::MessageHeader::GetHopCount() const [member function]
cls.add_method('GetHopCount',
'uint8_t',
[],
is_const=True)
## olsr-header.h (module 'olsr'): ns3::TypeId ns3::olsr::MessageHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## olsr-header.h (module 'olsr'): uint16_t ns3::olsr::MessageHeader::GetMessageSequenceNumber() const [member function]
cls.add_method('GetMessageSequenceNumber',
'uint16_t',
[],
is_const=True)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::MessageType ns3::olsr::MessageHeader::GetMessageType() const [member function]
cls.add_method('GetMessageType',
'ns3::olsr::MessageHeader::MessageType',
[],
is_const=True)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Mid & ns3::olsr::MessageHeader::GetMid() [member function]
cls.add_method('GetMid',
'ns3::olsr::MessageHeader::Mid &',
[])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Mid const & ns3::olsr::MessageHeader::GetMid() const [member function]
cls.add_method('GetMid',
'ns3::olsr::MessageHeader::Mid const &',
[],
is_const=True)
## olsr-header.h (module 'olsr'): ns3::Ipv4Address ns3::olsr::MessageHeader::GetOriginatorAddress() const [member function]
cls.add_method('GetOriginatorAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Tc & ns3::olsr::MessageHeader::GetTc() [member function]
cls.add_method('GetTc',
'ns3::olsr::MessageHeader::Tc &',
[])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Tc const & ns3::olsr::MessageHeader::GetTc() const [member function]
cls.add_method('GetTc',
'ns3::olsr::MessageHeader::Tc const &',
[],
is_const=True)
## olsr-header.h (module 'olsr'): uint8_t ns3::olsr::MessageHeader::GetTimeToLive() const [member function]
cls.add_method('GetTimeToLive',
'uint8_t',
[],
is_const=True)
## olsr-header.h (module 'olsr'): static ns3::TypeId ns3::olsr::MessageHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## olsr-header.h (module 'olsr'): ns3::Time ns3::olsr::MessageHeader::GetVTime() const [member function]
cls.add_method('GetVTime',
'ns3::Time',
[],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::SetHopCount(uint8_t hopCount) [member function]
cls.add_method('SetHopCount',
'void',
[param('uint8_t', 'hopCount')])
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::SetMessageSequenceNumber(uint16_t messageSequenceNumber) [member function]
cls.add_method('SetMessageSequenceNumber',
'void',
[param('uint16_t', 'messageSequenceNumber')])
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::SetMessageType(ns3::olsr::MessageHeader::MessageType messageType) [member function]
cls.add_method('SetMessageType',
'void',
[param('ns3::olsr::MessageHeader::MessageType', 'messageType')])
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::SetOriginatorAddress(ns3::Ipv4Address originatorAddress) [member function]
cls.add_method('SetOriginatorAddress',
'void',
[param('ns3::Ipv4Address', 'originatorAddress')])
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::SetTimeToLive(uint8_t timeToLive) [member function]
cls.add_method('SetTimeToLive',
'void',
[param('uint8_t', 'timeToLive')])
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::SetVTime(ns3::Time time) [member function]
cls.add_method('SetVTime',
'void',
[param('ns3::Time', 'time')])
return
def register_Ns3OlsrMessageHeaderHello_methods(root_module, cls):
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::Hello() [constructor]
cls.add_constructor([])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::Hello(ns3::olsr::MessageHeader::Hello const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::MessageHeader::Hello const &', 'arg0')])
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::Hello::Deserialize(ns3::Buffer::Iterator start, uint32_t messageSize) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'messageSize')])
## olsr-header.h (module 'olsr'): ns3::Time ns3::olsr::MessageHeader::Hello::GetHTime() const [member function]
cls.add_method('GetHTime',
'ns3::Time',
[],
is_const=True)
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::Hello::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Hello::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Hello::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Hello::SetHTime(ns3::Time time) [member function]
cls.add_method('SetHTime',
'void',
[param('ns3::Time', 'time')])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::hTime [variable]
cls.add_instance_attribute('hTime', 'uint8_t', is_const=False)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::linkMessages [variable]
cls.add_instance_attribute('linkMessages', 'std::vector< ns3::olsr::MessageHeader::Hello::LinkMessage >', is_const=False)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::willingness [variable]
cls.add_instance_attribute('willingness', 'uint8_t', is_const=False)
return
def register_Ns3OlsrMessageHeaderHelloLinkMessage_methods(root_module, cls):
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::LinkMessage::LinkMessage() [constructor]
cls.add_constructor([])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::LinkMessage::LinkMessage(ns3::olsr::MessageHeader::Hello::LinkMessage const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::MessageHeader::Hello::LinkMessage const &', 'arg0')])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::LinkMessage::linkCode [variable]
cls.add_instance_attribute('linkCode', 'uint8_t', is_const=False)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hello::LinkMessage::neighborInterfaceAddresses [variable]
cls.add_instance_attribute('neighborInterfaceAddresses', 'std::vector< ns3::Ipv4Address >', is_const=False)
return
def register_Ns3OlsrMessageHeaderHna_methods(root_module, cls):
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna::Hna() [constructor]
cls.add_constructor([])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna::Hna(ns3::olsr::MessageHeader::Hna const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::MessageHeader::Hna const &', 'arg0')])
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::Hna::Deserialize(ns3::Buffer::Iterator start, uint32_t messageSize) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'messageSize')])
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::Hna::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Hna::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Hna::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna::associations [variable]
cls.add_instance_attribute('associations', 'std::vector< ns3::olsr::MessageHeader::Hna::Association >', is_const=False)
return
def register_Ns3OlsrMessageHeaderHnaAssociation_methods(root_module, cls):
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna::Association::Association() [constructor]
cls.add_constructor([])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna::Association::Association(ns3::olsr::MessageHeader::Hna::Association const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::MessageHeader::Hna::Association const &', 'arg0')])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna::Association::address [variable]
cls.add_instance_attribute('address', 'ns3::Ipv4Address', is_const=False)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Hna::Association::mask [variable]
cls.add_instance_attribute('mask', 'ns3::Ipv4Mask', is_const=False)
return
def register_Ns3OlsrMessageHeaderMid_methods(root_module, cls):
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Mid::Mid() [constructor]
cls.add_constructor([])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Mid::Mid(ns3::olsr::MessageHeader::Mid const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::MessageHeader::Mid const &', 'arg0')])
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::Mid::Deserialize(ns3::Buffer::Iterator start, uint32_t messageSize) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'messageSize')])
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::Mid::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Mid::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Mid::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Mid::interfaceAddresses [variable]
cls.add_instance_attribute('interfaceAddresses', 'std::vector< ns3::Ipv4Address >', is_const=False)
return
def register_Ns3OlsrMessageHeaderTc_methods(root_module, cls):
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Tc::Tc() [constructor]
cls.add_constructor([])
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Tc::Tc(ns3::olsr::MessageHeader::Tc const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::MessageHeader::Tc const &', 'arg0')])
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::Tc::Deserialize(ns3::Buffer::Iterator start, uint32_t messageSize) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'messageSize')])
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::MessageHeader::Tc::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Tc::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::MessageHeader::Tc::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Tc::ansn [variable]
cls.add_instance_attribute('ansn', 'uint16_t', is_const=False)
## olsr-header.h (module 'olsr'): ns3::olsr::MessageHeader::Tc::neighborAddresses [variable]
cls.add_instance_attribute('neighborAddresses', 'std::vector< ns3::Ipv4Address >', is_const=False)
return
def register_Ns3OlsrMprSelectorTuple_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## olsr-repositories.h (module 'olsr'): ns3::olsr::MprSelectorTuple::MprSelectorTuple() [constructor]
cls.add_constructor([])
## olsr-repositories.h (module 'olsr'): ns3::olsr::MprSelectorTuple::MprSelectorTuple(ns3::olsr::MprSelectorTuple const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::MprSelectorTuple const &', 'arg0')])
## olsr-repositories.h (module 'olsr'): ns3::olsr::MprSelectorTuple::expirationTime [variable]
cls.add_instance_attribute('expirationTime', 'ns3::Time', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::MprSelectorTuple::mainAddr [variable]
cls.add_instance_attribute('mainAddr', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3OlsrNeighborTuple_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_output_stream_operator()
## olsr-repositories.h (module 'olsr'): ns3::olsr::NeighborTuple::NeighborTuple() [constructor]
cls.add_constructor([])
## olsr-repositories.h (module 'olsr'): ns3::olsr::NeighborTuple::NeighborTuple(ns3::olsr::NeighborTuple const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::NeighborTuple const &', 'arg0')])
## olsr-repositories.h (module 'olsr'): ns3::olsr::NeighborTuple::neighborMainAddr [variable]
cls.add_instance_attribute('neighborMainAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::NeighborTuple::status [variable]
cls.add_instance_attribute('status', 'ns3::olsr::NeighborTuple::Status', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::NeighborTuple::willingness [variable]
cls.add_instance_attribute('willingness', 'uint8_t', is_const=False)
return
def register_Ns3OlsrOlsrState_methods(root_module, cls):
## olsr-state.h (module 'olsr'): ns3::olsr::OlsrState::OlsrState(ns3::olsr::OlsrState const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::OlsrState const &', 'arg0')])
## olsr-state.h (module 'olsr'): ns3::olsr::OlsrState::OlsrState() [constructor]
cls.add_constructor([])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseAssociation(ns3::olsr::Association const & tuple) [member function]
cls.add_method('EraseAssociation',
'void',
[param('ns3::olsr::Association const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseAssociationTuple(ns3::olsr::AssociationTuple const & tuple) [member function]
cls.add_method('EraseAssociationTuple',
'void',
[param('ns3::olsr::AssociationTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseDuplicateTuple(ns3::olsr::DuplicateTuple const & tuple) [member function]
cls.add_method('EraseDuplicateTuple',
'void',
[param('ns3::olsr::DuplicateTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseIfaceAssocTuple(ns3::olsr::IfaceAssocTuple const & tuple) [member function]
cls.add_method('EraseIfaceAssocTuple',
'void',
[param('ns3::olsr::IfaceAssocTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseLinkTuple(ns3::olsr::LinkTuple const & tuple) [member function]
cls.add_method('EraseLinkTuple',
'void',
[param('ns3::olsr::LinkTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseMprSelectorTuple(ns3::olsr::MprSelectorTuple const & tuple) [member function]
cls.add_method('EraseMprSelectorTuple',
'void',
[param('ns3::olsr::MprSelectorTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseMprSelectorTuples(ns3::Ipv4Address const & mainAddr) [member function]
cls.add_method('EraseMprSelectorTuples',
'void',
[param('ns3::Ipv4Address const &', 'mainAddr')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseNeighborTuple(ns3::olsr::NeighborTuple const & neighborTuple) [member function]
cls.add_method('EraseNeighborTuple',
'void',
[param('ns3::olsr::NeighborTuple const &', 'neighborTuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseNeighborTuple(ns3::Ipv4Address const & mainAddr) [member function]
cls.add_method('EraseNeighborTuple',
'void',
[param('ns3::Ipv4Address const &', 'mainAddr')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseOlderTopologyTuples(ns3::Ipv4Address const & lastAddr, uint16_t ansn) [member function]
cls.add_method('EraseOlderTopologyTuples',
'void',
[param('ns3::Ipv4Address const &', 'lastAddr'), param('uint16_t', 'ansn')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseTopologyTuple(ns3::olsr::TopologyTuple const & tuple) [member function]
cls.add_method('EraseTopologyTuple',
'void',
[param('ns3::olsr::TopologyTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseTwoHopNeighborTuple(ns3::olsr::TwoHopNeighborTuple const & tuple) [member function]
cls.add_method('EraseTwoHopNeighborTuple',
'void',
[param('ns3::olsr::TwoHopNeighborTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseTwoHopNeighborTuples(ns3::Ipv4Address const & neighbor) [member function]
cls.add_method('EraseTwoHopNeighborTuples',
'void',
[param('ns3::Ipv4Address const &', 'neighbor')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::EraseTwoHopNeighborTuples(ns3::Ipv4Address const & neighbor, ns3::Ipv4Address const & twoHopNeighbor) [member function]
cls.add_method('EraseTwoHopNeighborTuples',
'void',
[param('ns3::Ipv4Address const &', 'neighbor'), param('ns3::Ipv4Address const &', 'twoHopNeighbor')])
## olsr-state.h (module 'olsr'): ns3::olsr::AssociationTuple * ns3::olsr::OlsrState::FindAssociationTuple(ns3::Ipv4Address const & gatewayAddr, ns3::Ipv4Address const & networkAddr, ns3::Ipv4Mask const & netmask) [member function]
cls.add_method('FindAssociationTuple',
'ns3::olsr::AssociationTuple *',
[param('ns3::Ipv4Address const &', 'gatewayAddr'), param('ns3::Ipv4Address const &', 'networkAddr'), param('ns3::Ipv4Mask const &', 'netmask')])
## olsr-state.h (module 'olsr'): ns3::olsr::DuplicateTuple * ns3::olsr::OlsrState::FindDuplicateTuple(ns3::Ipv4Address const & address, uint16_t sequenceNumber) [member function]
cls.add_method('FindDuplicateTuple',
'ns3::olsr::DuplicateTuple *',
[param('ns3::Ipv4Address const &', 'address'), param('uint16_t', 'sequenceNumber')])
## olsr-state.h (module 'olsr'): ns3::olsr::IfaceAssocTuple * ns3::olsr::OlsrState::FindIfaceAssocTuple(ns3::Ipv4Address const & ifaceAddr) [member function]
cls.add_method('FindIfaceAssocTuple',
'ns3::olsr::IfaceAssocTuple *',
[param('ns3::Ipv4Address const &', 'ifaceAddr')])
## olsr-state.h (module 'olsr'): ns3::olsr::IfaceAssocTuple const * ns3::olsr::OlsrState::FindIfaceAssocTuple(ns3::Ipv4Address const & ifaceAddr) const [member function]
cls.add_method('FindIfaceAssocTuple',
'ns3::olsr::IfaceAssocTuple const *',
[param('ns3::Ipv4Address const &', 'ifaceAddr')],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::LinkTuple * ns3::olsr::OlsrState::FindLinkTuple(ns3::Ipv4Address const & ifaceAddr) [member function]
cls.add_method('FindLinkTuple',
'ns3::olsr::LinkTuple *',
[param('ns3::Ipv4Address const &', 'ifaceAddr')])
## olsr-state.h (module 'olsr'): bool ns3::olsr::OlsrState::FindMprAddress(ns3::Ipv4Address const & address) [member function]
cls.add_method('FindMprAddress',
'bool',
[param('ns3::Ipv4Address const &', 'address')])
## olsr-state.h (module 'olsr'): ns3::olsr::MprSelectorTuple * ns3::olsr::OlsrState::FindMprSelectorTuple(ns3::Ipv4Address const & mainAddr) [member function]
cls.add_method('FindMprSelectorTuple',
'ns3::olsr::MprSelectorTuple *',
[param('ns3::Ipv4Address const &', 'mainAddr')])
## olsr-state.h (module 'olsr'): std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > ns3::olsr::OlsrState::FindNeighborInterfaces(ns3::Ipv4Address const & neighborMainAddr) const [member function]
cls.add_method('FindNeighborInterfaces',
'std::vector< ns3::Ipv4Address >',
[param('ns3::Ipv4Address const &', 'neighborMainAddr')],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::NeighborTuple * ns3::olsr::OlsrState::FindNeighborTuple(ns3::Ipv4Address const & mainAddr) [member function]
cls.add_method('FindNeighborTuple',
'ns3::olsr::NeighborTuple *',
[param('ns3::Ipv4Address const &', 'mainAddr')])
## olsr-state.h (module 'olsr'): ns3::olsr::NeighborTuple * ns3::olsr::OlsrState::FindNeighborTuple(ns3::Ipv4Address const & mainAddr, uint8_t willingness) [member function]
cls.add_method('FindNeighborTuple',
'ns3::olsr::NeighborTuple *',
[param('ns3::Ipv4Address const &', 'mainAddr'), param('uint8_t', 'willingness')])
## olsr-state.h (module 'olsr'): ns3::olsr::TopologyTuple * ns3::olsr::OlsrState::FindNewerTopologyTuple(ns3::Ipv4Address const & lastAddr, uint16_t ansn) [member function]
cls.add_method('FindNewerTopologyTuple',
'ns3::olsr::TopologyTuple *',
[param('ns3::Ipv4Address const &', 'lastAddr'), param('uint16_t', 'ansn')])
## olsr-state.h (module 'olsr'): ns3::olsr::LinkTuple * ns3::olsr::OlsrState::FindSymLinkTuple(ns3::Ipv4Address const & ifaceAddr, ns3::Time time) [member function]
cls.add_method('FindSymLinkTuple',
'ns3::olsr::LinkTuple *',
[param('ns3::Ipv4Address const &', 'ifaceAddr'), param('ns3::Time', 'time')])
## olsr-state.h (module 'olsr'): ns3::olsr::NeighborTuple const * ns3::olsr::OlsrState::FindSymNeighborTuple(ns3::Ipv4Address const & mainAddr) const [member function]
cls.add_method('FindSymNeighborTuple',
'ns3::olsr::NeighborTuple const *',
[param('ns3::Ipv4Address const &', 'mainAddr')],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::TopologyTuple * ns3::olsr::OlsrState::FindTopologyTuple(ns3::Ipv4Address const & destAddr, ns3::Ipv4Address const & lastAddr) [member function]
cls.add_method('FindTopologyTuple',
'ns3::olsr::TopologyTuple *',
[param('ns3::Ipv4Address const &', 'destAddr'), param('ns3::Ipv4Address const &', 'lastAddr')])
## olsr-state.h (module 'olsr'): ns3::olsr::TwoHopNeighborTuple * ns3::olsr::OlsrState::FindTwoHopNeighborTuple(ns3::Ipv4Address const & neighbor, ns3::Ipv4Address const & twoHopNeighbor) [member function]
cls.add_method('FindTwoHopNeighborTuple',
'ns3::olsr::TwoHopNeighborTuple *',
[param('ns3::Ipv4Address const &', 'neighbor'), param('ns3::Ipv4Address const &', 'twoHopNeighbor')])
## olsr-state.h (module 'olsr'): ns3::olsr::AssociationSet const & ns3::olsr::OlsrState::GetAssociationSet() const [member function]
cls.add_method('GetAssociationSet',
'ns3::olsr::AssociationSet const &',
[],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::Associations const & ns3::olsr::OlsrState::GetAssociations() const [member function]
cls.add_method('GetAssociations',
'ns3::olsr::Associations const &',
[],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::IfaceAssocSet const & ns3::olsr::OlsrState::GetIfaceAssocSet() const [member function]
cls.add_method('GetIfaceAssocSet',
'ns3::olsr::IfaceAssocSet const &',
[],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::IfaceAssocSet & ns3::olsr::OlsrState::GetIfaceAssocSetMutable() [member function]
cls.add_method('GetIfaceAssocSetMutable',
'ns3::olsr::IfaceAssocSet &',
[])
## olsr-state.h (module 'olsr'): ns3::olsr::LinkSet const & ns3::olsr::OlsrState::GetLinks() const [member function]
cls.add_method('GetLinks',
'ns3::olsr::LinkSet const &',
[],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::MprSelectorSet const & ns3::olsr::OlsrState::GetMprSelectors() const [member function]
cls.add_method('GetMprSelectors',
'ns3::olsr::MprSelectorSet const &',
[],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::MprSet ns3::olsr::OlsrState::GetMprSet() const [member function]
cls.add_method('GetMprSet',
'ns3::olsr::MprSet',
[],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::NeighborSet const & ns3::olsr::OlsrState::GetNeighbors() const [member function]
cls.add_method('GetNeighbors',
'ns3::olsr::NeighborSet const &',
[],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::NeighborSet & ns3::olsr::OlsrState::GetNeighbors() [member function]
cls.add_method('GetNeighbors',
'ns3::olsr::NeighborSet &',
[])
## olsr-state.h (module 'olsr'): ns3::olsr::TopologySet const & ns3::olsr::OlsrState::GetTopologySet() const [member function]
cls.add_method('GetTopologySet',
'ns3::olsr::TopologySet const &',
[],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::TwoHopNeighborSet const & ns3::olsr::OlsrState::GetTwoHopNeighbors() const [member function]
cls.add_method('GetTwoHopNeighbors',
'ns3::olsr::TwoHopNeighborSet const &',
[],
is_const=True)
## olsr-state.h (module 'olsr'): ns3::olsr::TwoHopNeighborSet & ns3::olsr::OlsrState::GetTwoHopNeighbors() [member function]
cls.add_method('GetTwoHopNeighbors',
'ns3::olsr::TwoHopNeighborSet &',
[])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::InsertAssociation(ns3::olsr::Association const & tuple) [member function]
cls.add_method('InsertAssociation',
'void',
[param('ns3::olsr::Association const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::InsertAssociationTuple(ns3::olsr::AssociationTuple const & tuple) [member function]
cls.add_method('InsertAssociationTuple',
'void',
[param('ns3::olsr::AssociationTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::InsertDuplicateTuple(ns3::olsr::DuplicateTuple const & tuple) [member function]
cls.add_method('InsertDuplicateTuple',
'void',
[param('ns3::olsr::DuplicateTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::InsertIfaceAssocTuple(ns3::olsr::IfaceAssocTuple const & tuple) [member function]
cls.add_method('InsertIfaceAssocTuple',
'void',
[param('ns3::olsr::IfaceAssocTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): ns3::olsr::LinkTuple & ns3::olsr::OlsrState::InsertLinkTuple(ns3::olsr::LinkTuple const & tuple) [member function]
cls.add_method('InsertLinkTuple',
'ns3::olsr::LinkTuple &',
[param('ns3::olsr::LinkTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::InsertMprSelectorTuple(ns3::olsr::MprSelectorTuple const & tuple) [member function]
cls.add_method('InsertMprSelectorTuple',
'void',
[param('ns3::olsr::MprSelectorTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::InsertNeighborTuple(ns3::olsr::NeighborTuple const & tuple) [member function]
cls.add_method('InsertNeighborTuple',
'void',
[param('ns3::olsr::NeighborTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::InsertTopologyTuple(ns3::olsr::TopologyTuple const & tuple) [member function]
cls.add_method('InsertTopologyTuple',
'void',
[param('ns3::olsr::TopologyTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::InsertTwoHopNeighborTuple(ns3::olsr::TwoHopNeighborTuple const & tuple) [member function]
cls.add_method('InsertTwoHopNeighborTuple',
'void',
[param('ns3::olsr::TwoHopNeighborTuple const &', 'tuple')])
## olsr-state.h (module 'olsr'): std::string ns3::olsr::OlsrState::PrintMprSelectorSet() const [member function]
cls.add_method('PrintMprSelectorSet',
'std::string',
[],
is_const=True)
## olsr-state.h (module 'olsr'): void ns3::olsr::OlsrState::SetMprSet(ns3::olsr::MprSet mprSet) [member function]
cls.add_method('SetMprSet',
'void',
[param('std::set< ns3::Ipv4Address >', 'mprSet')])
return
def register_Ns3OlsrPacketHeader_methods(root_module, cls):
cls.add_output_stream_operator()
## olsr-header.h (module 'olsr'): ns3::olsr::PacketHeader::PacketHeader(ns3::olsr::PacketHeader const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::PacketHeader const &', 'arg0')])
## olsr-header.h (module 'olsr'): ns3::olsr::PacketHeader::PacketHeader() [constructor]
cls.add_constructor([])
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::PacketHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## olsr-header.h (module 'olsr'): ns3::TypeId ns3::olsr::PacketHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## olsr-header.h (module 'olsr'): uint16_t ns3::olsr::PacketHeader::GetPacketLength() const [member function]
cls.add_method('GetPacketLength',
'uint16_t',
[],
is_const=True)
## olsr-header.h (module 'olsr'): uint16_t ns3::olsr::PacketHeader::GetPacketSequenceNumber() const [member function]
cls.add_method('GetPacketSequenceNumber',
'uint16_t',
[],
is_const=True)
## olsr-header.h (module 'olsr'): uint32_t ns3::olsr::PacketHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## olsr-header.h (module 'olsr'): static ns3::TypeId ns3::olsr::PacketHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::PacketHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::PacketHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## olsr-header.h (module 'olsr'): void ns3::olsr::PacketHeader::SetPacketLength(uint16_t length) [member function]
cls.add_method('SetPacketLength',
'void',
[param('uint16_t', 'length')])
## olsr-header.h (module 'olsr'): void ns3::olsr::PacketHeader::SetPacketSequenceNumber(uint16_t seqnum) [member function]
cls.add_method('SetPacketSequenceNumber',
'void',
[param('uint16_t', 'seqnum')])
return
def register_Ns3OlsrRoutingProtocol_methods(root_module, cls):
## olsr-routing-protocol.h (module 'olsr'): static ns3::TypeId ns3::olsr::RoutingProtocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingProtocol::RoutingProtocol() [constructor]
cls.add_constructor([])
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::SetMainInterface(uint32_t interface) [member function]
cls.add_method('SetMainInterface',
'void',
[param('uint32_t', 'interface')])
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::Dump() [member function]
cls.add_method('Dump',
'void',
[])
## olsr-routing-protocol.h (module 'olsr'): std::vector<ns3::olsr::RoutingTableEntry, std::allocator<ns3::olsr::RoutingTableEntry> > ns3::olsr::RoutingProtocol::GetRoutingTableEntries() const [member function]
cls.add_method('GetRoutingTableEntries',
'std::vector< ns3::olsr::RoutingTableEntry >',
[],
is_const=True)
## olsr-routing-protocol.h (module 'olsr'): int64_t ns3::olsr::RoutingProtocol::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## olsr-routing-protocol.h (module 'olsr'): std::set<unsigned int, std::less<unsigned int>, std::allocator<unsigned int> > ns3::olsr::RoutingProtocol::GetInterfaceExclusions() const [member function]
cls.add_method('GetInterfaceExclusions',
'std::set< unsigned int >',
[],
is_const=True)
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::SetInterfaceExclusions(std::set<unsigned int, std::less<unsigned int>, std::allocator<unsigned int> > exceptions) [member function]
cls.add_method('SetInterfaceExclusions',
'void',
[param('std::set< unsigned int >', 'exceptions')])
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::AddHostNetworkAssociation(ns3::Ipv4Address networkAddr, ns3::Ipv4Mask netmask) [member function]
cls.add_method('AddHostNetworkAssociation',
'void',
[param('ns3::Ipv4Address', 'networkAddr'), param('ns3::Ipv4Mask', 'netmask')])
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::RemoveHostNetworkAssociation(ns3::Ipv4Address networkAddr, ns3::Ipv4Mask netmask) [member function]
cls.add_method('RemoveHostNetworkAssociation',
'void',
[param('ns3::Ipv4Address', 'networkAddr'), param('ns3::Ipv4Mask', 'netmask')])
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::SetRoutingTableAssociation(ns3::Ptr<ns3::Ipv4StaticRouting> routingTable) [member function]
cls.add_method('SetRoutingTableAssociation',
'void',
[param('ns3::Ptr< ns3::Ipv4StaticRouting >', 'routingTable')])
## olsr-routing-protocol.h (module 'olsr'): ns3::Ptr<const ns3::Ipv4StaticRouting> ns3::olsr::RoutingProtocol::GetRoutingTableAssociation() const [member function]
cls.add_method('GetRoutingTableAssociation',
'ns3::Ptr< ns3::Ipv4StaticRouting const >',
[],
is_const=True)
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingProtocol::RoutingProtocol(ns3::olsr::RoutingProtocol const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::RoutingProtocol const &', 'arg0')])
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## olsr-routing-protocol.h (module 'olsr'): ns3::Ptr<ns3::Ipv4Route> ns3::olsr::RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function]
cls.add_method('RouteOutput',
'ns3::Ptr< ns3::Ipv4Route >',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')],
visibility='private', is_virtual=True)
## olsr-routing-protocol.h (module 'olsr'): bool ns3::olsr::RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function]
cls.add_method('RouteInput',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')],
visibility='private', is_virtual=True)
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceUp',
'void',
[param('uint32_t', 'interface')],
visibility='private', is_virtual=True)
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function]
cls.add_method('NotifyInterfaceDown',
'void',
[param('uint32_t', 'interface')],
visibility='private', is_virtual=True)
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyAddAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
visibility='private', is_virtual=True)
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('NotifyRemoveAddress',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
visibility='private', is_virtual=True)
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')],
visibility='private', is_virtual=True)
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function]
cls.add_method('PrintRoutingTable',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')],
is_const=True, visibility='private', is_virtual=True)
## olsr-routing-protocol.h (module 'olsr'): void ns3::olsr::RoutingProtocol::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3OlsrRoutingTableEntry_methods(root_module, cls):
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingTableEntry::RoutingTableEntry(ns3::olsr::RoutingTableEntry const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::RoutingTableEntry const &', 'arg0')])
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingTableEntry::RoutingTableEntry() [constructor]
cls.add_constructor([])
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingTableEntry::destAddr [variable]
cls.add_instance_attribute('destAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingTableEntry::distance [variable]
cls.add_instance_attribute('distance', 'uint32_t', is_const=False)
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingTableEntry::interface [variable]
cls.add_instance_attribute('interface', 'uint32_t', is_const=False)
## olsr-routing-protocol.h (module 'olsr'): ns3::olsr::RoutingTableEntry::nextAddr [variable]
cls.add_instance_attribute('nextAddr', 'ns3::Ipv4Address', is_const=False)
return
def register_Ns3OlsrTopologyTuple_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_output_stream_operator()
## olsr-repositories.h (module 'olsr'): ns3::olsr::TopologyTuple::TopologyTuple() [constructor]
cls.add_constructor([])
## olsr-repositories.h (module 'olsr'): ns3::olsr::TopologyTuple::TopologyTuple(ns3::olsr::TopologyTuple const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::TopologyTuple const &', 'arg0')])
## olsr-repositories.h (module 'olsr'): ns3::olsr::TopologyTuple::destAddr [variable]
cls.add_instance_attribute('destAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::TopologyTuple::expirationTime [variable]
cls.add_instance_attribute('expirationTime', 'ns3::Time', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::TopologyTuple::lastAddr [variable]
cls.add_instance_attribute('lastAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::TopologyTuple::sequenceNumber [variable]
cls.add_instance_attribute('sequenceNumber', 'uint16_t', is_const=False)
return
def register_Ns3OlsrTwoHopNeighborTuple_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## olsr-repositories.h (module 'olsr'): ns3::olsr::TwoHopNeighborTuple::TwoHopNeighborTuple() [constructor]
cls.add_constructor([])
## olsr-repositories.h (module 'olsr'): ns3::olsr::TwoHopNeighborTuple::TwoHopNeighborTuple(ns3::olsr::TwoHopNeighborTuple const & arg0) [constructor]
cls.add_constructor([param('ns3::olsr::TwoHopNeighborTuple const &', 'arg0')])
## olsr-repositories.h (module 'olsr'): ns3::olsr::TwoHopNeighborTuple::expirationTime [variable]
cls.add_instance_attribute('expirationTime', 'ns3::Time', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::TwoHopNeighborTuple::neighborMainAddr [variable]
cls.add_instance_attribute('neighborMainAddr', 'ns3::Ipv4Address', is_const=False)
## olsr-repositories.h (module 'olsr'): ns3::olsr::TwoHopNeighborTuple::twoHopNeighborAddr [variable]
cls.add_instance_attribute('twoHopNeighborAddr', 'ns3::Ipv4Address', is_const=False)
return
def register_functions(root_module):
module = root_module
register_functions_ns3_FatalImpl(module.add_cpp_namespace('FatalImpl'), root_module)
register_functions_ns3_Hash(module.add_cpp_namespace('Hash'), root_module)
register_functions_ns3_TracedValueCallback(module.add_cpp_namespace('TracedValueCallback'), root_module)
register_functions_ns3_olsr(module.add_cpp_namespace('olsr'), root_module)
register_functions_ns3_tests(module.add_cpp_namespace('tests'), 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.add_cpp_namespace('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_olsr(module, root_module):
## olsr-header.h (module 'olsr'): double ns3::olsr::EmfToSeconds(uint8_t emf) [free function]
module.add_function('EmfToSeconds',
'double',
[param('uint8_t', 'emf')])
## olsr-header.h (module 'olsr'): uint8_t ns3::olsr::SecondsToEmf(double seconds) [free function]
module.add_function('SecondsToEmf',
'uint8_t',
[param('double', 'seconds')])
return
def register_functions_ns3_tests(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()
| tomhenderson/ns-3-dev-git | src/olsr/bindings/modulegen__gcc_LP64.py | Python | gpl-2.0 | 542,189 | 0.014563 |
"""Python part of the warnings subsystem."""
# Note: function level imports should *not* be used
# in this module as it may cause import lock deadlock.
# See bug 683658.
import linecache
import sys
import types
__all__ = ["warn", "warn_explicit", "showwarning",
"formatwarning", "filterwarnings", "simplefilter",
"resetwarnings", "catch_warnings"]
def warnpy3k(message, category=None, stacklevel=1):
"""Issue a deprecation warning for Python 3.x related changes.
Warnings are omitted unless Python is started with the -3 option.
"""
if sys.py3kwarning:
if category is None:
category = DeprecationWarning
warn(message, category, stacklevel+1)
def _show_warning(message, category, filename, lineno, file=None, line=None):
"""Hook to write a warning to a file; replace if you like."""
if file is None:
file = sys.stderr
if file is None:
# sys.stderr is None - warnings get lost
return
try:
file.write(formatwarning(message, category, filename, lineno, line))
except (IOError, UnicodeError):
pass # the file (probably stderr) is invalid - this warning gets lost.
# Keep a working version around in case the deprecation of the old API is
# triggered.
showwarning = _show_warning
def formatwarning(message, category, filename, lineno, line=None):
"""Function to format a warning the standard way."""
try:
unicodetype = unicode
except NameError:
unicodetype = ()
try:
message = str(message)
except UnicodeEncodeError:
pass
s = "%s: %s: %s\n" % (lineno, category.__name__, message)
line = linecache.getline(filename, lineno) if line is None else line
if line:
line = line.strip()
if isinstance(s, unicodetype) and isinstance(line, str):
line = unicode(line, 'latin1')
s += " %s\n" % line
if isinstance(s, unicodetype) and isinstance(filename, str):
enc = sys.getfilesystemencoding()
if enc:
try:
filename = unicode(filename, enc)
except UnicodeDecodeError:
pass
s = "%s:%s" % (filename, s)
return s
def filterwarnings(action, message="", category=Warning, module="", lineno=0,
append=0):
"""Insert an entry into the list of warnings filters (at the front).
'action' -- one of "error", "ignore", "always", "default", "module",
or "once"
'message' -- a regex that the warning message must match
'category' -- a class that the warning must be a subclass of
'module' -- a regex that the module name must match
'lineno' -- an integer line number, 0 matches all warnings
'append' -- if true, append to the list of filters
"""
import re
assert action in ("error", "ignore", "always", "default", "module",
"once"), "invalid action: %r" % (action,)
assert isinstance(message, basestring), "message must be a string"
assert isinstance(category, (type, types.ClassType)), \
"category must be a class"
assert issubclass(category, Warning), "category must be a Warning subclass"
assert isinstance(module, basestring), "module must be a string"
assert isinstance(lineno, int) and lineno >= 0, \
"lineno must be an int >= 0"
item = (action, re.compile(message, re.I), category,
re.compile(module), lineno)
if append:
filters.append(item)
else:
filters.insert(0, item)
def simplefilter(action, category=Warning, lineno=0, append=0):
"""Insert a simple entry into the list of warnings filters (at the front).
A simple filter matches all modules and messages.
'action' -- one of "error", "ignore", "always", "default", "module",
or "once"
'category' -- a class that the warning must be a subclass of
'lineno' -- an integer line number, 0 matches all warnings
'append' -- if true, append to the list of filters
"""
assert action in ("error", "ignore", "always", "default", "module",
"once"), "invalid action: %r" % (action,)
assert isinstance(lineno, int) and lineno >= 0, \
"lineno must be an int >= 0"
item = (action, None, category, None, lineno)
if append:
filters.append(item)
else:
filters.insert(0, item)
def resetwarnings():
"""Clear the list of warning filters, so that no filters are active."""
filters[:] = []
class _OptionError(Exception):
"""Exception used by option processing helpers."""
pass
# Helper to process -W options passed via sys.warnoptions
def _processoptions(args):
for arg in args:
try:
_setoption(arg)
except _OptionError, msg:
print >>sys.stderr, "Invalid -W option ignored:", msg
# Helper for _processoptions()
def _setoption(arg):
import re
parts = arg.split(':')
if len(parts) > 5:
raise _OptionError("too many fields (max 5): %r" % (arg,))
while len(parts) < 5:
parts.append('')
action, message, category, module, lineno = [s.strip()
for s in parts]
action = _getaction(action)
message = re.escape(message)
category = _getcategory(category)
module = re.escape(module)
if module:
module = module + '$'
if lineno:
try:
lineno = int(lineno)
if lineno < 0:
raise ValueError
except (ValueError, OverflowError):
raise _OptionError("invalid lineno %r" % (lineno,))
else:
lineno = 0
filterwarnings(action, message, category, module, lineno)
# Helper for _setoption()
def _getaction(action):
if not action:
return "default"
if action == "all": return "always" # Alias
for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
if a.startswith(action):
return a
raise _OptionError("invalid action: %r" % (action,))
# Helper for _setoption()
def _getcategory(category):
import re
if not category:
return Warning
if re.match("^[a-zA-Z0-9_]+$", category):
try:
cat = eval(category)
except NameError:
raise _OptionError("unknown warning category: %r" % (category,))
else:
i = category.rfind(".")
module = category[:i]
klass = category[i+1:]
try:
m = __import__(module, None, None, [klass])
except ImportError:
raise _OptionError("invalid module name: %r" % (module,))
try:
cat = getattr(m, klass)
except AttributeError:
raise _OptionError("unknown warning category: %r" % (category,))
if not issubclass(cat, Warning):
raise _OptionError("invalid warning category: %r" % (category,))
return cat
# Code typically replaced by _warnings
def warn(message, category=None, stacklevel=1):
"""Issue a warning, or maybe ignore it or raise an exception."""
# Check if message is already a Warning object
if isinstance(message, Warning):
category = message.__class__
# Check category argument
if category is None:
category = UserWarning
assert issubclass(category, Warning)
# Get context information
try:
caller = sys._getframe(stacklevel)
except ValueError:
globals = sys.__dict__
lineno = 1
else:
globals = caller.f_globals
lineno = caller.f_lineno
if '__name__' in globals:
module = globals['__name__']
else:
module = "<string>"
filename = globals.get('__file__')
if filename:
fnl = filename.lower()
if fnl.endswith((".pyc", ".pyo")):
filename = filename[:-1]
else:
if module == "__main__":
try:
filename = sys.argv[0]
except AttributeError:
# embedded interpreters don't have sys.argv, see bug #839151
filename = '__main__'
if not filename:
filename = module
registry = globals.setdefault("__warningregistry__", {})
warn_explicit(message, category, filename, lineno, module, registry,
globals)
def warn_explicit(message, category, filename, lineno,
module=None, registry=None, module_globals=None):
lineno = int(lineno)
if module is None:
module = filename or "<unknown>"
if module[-3:].lower() == ".py":
module = module[:-3] # XXX What about leading pathname?
if registry is None:
registry = {}
if isinstance(message, Warning):
text = str(message)
category = message.__class__
else:
text = message
message = category(message)
key = (text, category, lineno)
# Quick test for common case
if registry.get(key):
return
# Search the filters
for item in filters:
action, msg, cat, mod, ln = item
if ((msg is None or msg.match(text)) and
issubclass(category, cat) and
(mod is None or mod.match(module)) and
(ln == 0 or lineno == ln)):
break
else:
action = defaultaction
# Early exit actions
if action == "ignore":
registry[key] = 1
return
# Prime the linecache for formatting, in case the
# "file" is actually in a zipfile or something.
linecache.getlines(filename, module_globals)
if action == "error":
raise message
# Other actions
if action == "once":
registry[key] = 1
oncekey = (text, category)
if onceregistry.get(oncekey):
return
onceregistry[oncekey] = 1
elif action == "always":
pass
elif action == "module":
registry[key] = 1
altkey = (text, category, 0)
if registry.get(altkey):
return
registry[altkey] = 1
elif action == "default":
registry[key] = 1
else:
# Unrecognized actions are errors
raise RuntimeError(
"Unrecognized action (%r) in warnings.filters:\n %s" %
(action, item))
# Print message and context
showwarning(message, category, filename, lineno)
class WarningMessage(object):
"""Holds the result of a single showwarning() call."""
_WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
"line")
def __init__(self, message, category, filename, lineno, file=None,
line=None):
local_values = locals()
for attr in self._WARNING_DETAILS:
setattr(self, attr, local_values[attr])
self._category_name = category.__name__ if category else None
def __str__(self):
return ("{message : %r, category : %r, filename : %r, lineno : %s, "
"line : %r}" % (self.message, self._category_name,
self.filename, self.lineno, self.line))
class catch_warnings(object):
"""A context manager that copies and restores the warnings filter upon
exiting the context.
The 'record' argument specifies whether warnings should be captured by a
custom implementation of warnings.showwarning() and be appended to a list
returned by the context manager. Otherwise None is returned by the context
manager. The objects appended to the list are arguments whose attributes
mirror the arguments to showwarning().
The 'module' argument is to specify an alternative module to the module
named 'warnings' and imported under that name. This argument is only useful
when testing the warnings module itself.
"""
def __init__(self, record=False, module=None):
"""Specify whether to record warnings and if an alternative module
should be used other than sys.modules['warnings'].
For compatibility with Python 3.0, please consider all arguments to be
keyword-only.
"""
self._record = record
self._module = sys.modules['warnings'] if module is None else module
self._entered = False
def __repr__(self):
args = []
if self._record:
args.append("record=True")
if self._module is not sys.modules['warnings']:
args.append("module=%r" % self._module)
name = type(self).__name__
return "%s(%s)" % (name, ", ".join(args))
def __enter__(self):
if self._entered:
raise RuntimeError("Cannot enter %r twice" % self)
self._entered = True
self._filters = self._module.filters
self._module.filters = self._filters[:]
self._showwarning = self._module.showwarning
if self._record:
log = []
def showwarning(*args, **kwargs):
log.append(WarningMessage(*args, **kwargs))
self._module.showwarning = showwarning
return log
else:
return None
def __exit__(self, *exc_info):
if not self._entered:
raise RuntimeError("Cannot exit %r without entering first" % self)
self._module.filters = self._filters
self._module.showwarning = self._showwarning
# filters contains a sequence of filter 5-tuples
# The components of the 5-tuple are:
# - an action: error, ignore, always, default, module, or once
# - a compiled regex that must match the warning message
# - a class representing the warning category
# - a compiled regex that must match the module that is being warned
# - a line number for the line being warning, or 0 to mean any line
# If either if the compiled regexs are None, match anything.
_warnings_defaults = False
try:
from _warnings import (filters, default_action, once_registry,
warn, warn_explicit)
defaultaction = default_action
onceregistry = once_registry
_warnings_defaults = True
except ImportError:
filters = []
defaultaction = "default"
onceregistry = {}
# Module initialization
_processoptions(sys.warnoptions)
if not _warnings_defaults:
silence = [ImportWarning, PendingDeprecationWarning]
# Don't silence DeprecationWarning if -3 or -Q was used.
if not sys.py3kwarning and not sys.flags.division_warning:
silence.append(DeprecationWarning)
for cls in silence:
simplefilter("ignore", category=cls)
bytes_warning = sys.flags.bytes_warning
if bytes_warning > 1:
bytes_action = "error"
elif bytes_warning:
bytes_action = "default"
else:
bytes_action = "ignore"
simplefilter(bytes_action, category=BytesWarning, append=1)
del _warnings_defaults
| gusai-francelabs/datafari | windows/python/Lib/warnings.py | Python | apache-2.0 | 14,748 | 0.001492 |
#!/usr/bin/env python
from setuptools import find_packages, setup
from eventlet import __version__
from os import path
setup(
name='eventlet',
version=__version__,
description='Highly concurrent networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://eventlet.net',
packages=find_packages(exclude=['benchmarks', 'tests', 'tests.*']),
install_requires=(
'greenlet >= 0.3',
),
zip_safe=False,
long_description=open(
path.join(
path.dirname(__file__),
'README.rst'
)
).read(),
test_suite='nose.collector',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta",
]
)
| collinstocks/eventlet | setup.py | Python | mit | 1,289 | 0 |
# -*- encoding: utf-8 -*-
#
# Copyright 2013 Jay Pipes
#
# 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 logging
import sys
import traceback
LOG = logging.getLogger(__name__)
def import_function(import_str):
"""
Attempts to import the specified class method or regular function,
and returns a callable.
:raises ImportError if the specified import_str cannot be found.
:raises TypeError if the specified import_str is found but is
not a callable.
"""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
fn = getattr(sys.modules[mod_str], class_str)
if not callable(fn):
msg = '{0} is not callable'
LOG.error(msg)
raise TypeError(msg)
except (ValueError, AttributeError):
msg = 'Method or function {0} cannot be found.'.format(import_str)
err_details = traceback.format_exception(*sys.exc_info())
LOG.error(msg + ' Details: (%s)'.format(err_details))
raise ImportError(msg)
except ImportError:
msg = 'Module {0} cannot be found.'.format(import_str)
err_details = traceback.format_exception(*sys.exc_info())
LOG.error(msg + ' Details: (%s)'.format(err_details))
raise
| openilabs/falconlab | env/lib/python2.7/site-packages/talons/helpers.py | Python | mit | 1,777 | 0 |
import DeepFried2 as df
from .. import dfext
def mknet(mkbn=lambda chan: df.BatchNormalization(chan, 0.95)):
kw = dict(mkbn=mkbn)
net = df.Sequential(
# -> 128x48
df.SpatialConvolutionCUDNN(3, 64, (7,7), border='same', bias=None),
dfext.resblock(64, **kw),
df.PoolingCUDNN((2,2)), # -> 64x24
dfext.resblock(64, **kw),
dfext.resblock(64, **kw),
dfext.resblock(64, 96, **kw),
df.PoolingCUDNN((2,2)), # -> 32x12
dfext.resblock(96, **kw),
dfext.resblock(96, **kw),
df.PoolingCUDNN((2,2)), # -> 16x6
dfext.resblock(96, **kw),
dfext.resblock(96, **kw),
dfext.resblock(96, 128, **kw),
df.PoolingCUDNN((2,2)), # -> 8x3
dfext.resblock(128, **kw),
dfext.resblock(128, **kw),
df.PoolingCUDNN((2,3)), # -> 4x1
dfext.resblock(128, **kw),
# Eq. to flatten + linear
df.SpatialConvolutionCUDNN(128, 256, (4,1), bias=None),
mkbn(256), df.ReLU(),
df.StoreOut(df.SpatialConvolutionCUDNN(256, 128, (1,1)))
)
net.emb_mod = net[-1]
net.in_shape = (128, 48)
net.scale_factor = (2*2*2*2*2, 2*2*2*2*3)
print("Net has {:.2f}M params".format(df.utils.count_params(net)/1000/1000), flush=True)
return net
def add_piou(lunet2):
newnet = lunet2[:-1]
newnet.emb_mod = lunet2[-1]
newnet.iou_mod = df.StoreOut(df.Sequential(df.SpatialConvolutionCUDNN(256, 1, (1,1)), df.Sigmoid()))
newnet.add(df.RepeatInput(newnet.emb_mod, newnet.iou_mod))
newnet.embs_from_out = lambda out: out[0]
newnet.ious_from_out = lambda out: out[1][:,0] # Also remove the first size-1 dimension.
newnet.in_shape = lunet2.in_shape
newnet.scale_factor = lunet2.scale_factor
print("Added {:.2f}k params".format(df.utils.count_params(newnet.iou_mod)/1000), flush=True)
return newnet
| VisualComputingInstitute/towards-reid-tracking | lib/models/lunet2.py | Python | mit | 1,896 | 0.007384 |
from utilities import docs, ftom, mtof, scale_val
from dynamic_value import *
from behaviors import *
from schedule import now, wait, sprout
from rtcmix_import.commands import *
from instruments import *
import busses
#__all__ = ["rtcmix_import", "utilities", "abstract", "dynamic_value", "instruments", "behaviors", "schedule"] | bennymartinson/Oort | oort/__init__.py | Python | gpl-3.0 | 335 | 0.008955 |
#!/usr/bin/env python
#Copyright (C) 2013 by Thomas Keane (tk2@sanger.ac.uk)
#
#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.
import os
import re
import subprocess
import time
import sys
import random
import string
from Queue import Queue, Empty
from threading import Thread
from datetime import date
from sonLib.bioio import logger
from sonLib.bioio import system
from jobTree.batchSystems.abstractBatchSystem import AbstractBatchSystem
from jobTree.src.master import getParasolResultsFileName
class MemoryString:
def __init__(self, string):
if string[-1] == 'K' or string[-1] == 'M' or string[-1] == 'G':
self.unit = string[-1]
self.val = float(string[:-1])
else:
self.unit = 'B'
self.val = float(string)
self.bytes = self.byteVal()
def __str__(self):
if self.unit != 'B':
return str(self.val) + self.unit
else:
return str(self.val)
def byteVal(self):
if self.unit == 'B':
return self.val
elif self.unit == 'K':
return self.val * 1000
elif self.unit == 'M':
return self.val * 1000000
elif self.unit == 'G':
return self.val * 1000000000
def __cmp__(self, other):
return cmp(self.bytes, other.bytes)
def prepareBsub(cpu, mem):
mem = '' if mem is None else '-R "select[type==X86_64 && mem > ' + str(int(mem/ 1000000)) + '] rusage[mem=' + str(int(mem/ 1000000)) + ']" -M' + str(int(mem/ 1000000)) + '000'
cpu = '' if cpu is None else '-n ' + str(int(cpu))
bsubline = ["bsub", mem, cpu,"-cwd", ".", "-o", "/dev/null", "-e", "/dev/null"]
return bsubline
def bsub(bsubline):
process = subprocess.Popen(" ".join(bsubline), shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
liney = process.stdout.readline()
logger.info("BSUB: " + liney)
result = int(liney.strip().split()[1].strip('<>'))
logger.debug("Got the job id: %s" % (str(result)))
return result
def getjobexitcode(lsfJobID):
job, task = lsfJobID
#first try bjobs to find out job state
args = ["bjobs", "-l", str(job)]
logger.info("Checking job exit code for job via bjobs: " + str(job))
process = subprocess.Popen(" ".join(args), shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
started = 0
for line in process.stdout:
if line.find("Done successfully") > -1:
logger.info("bjobs detected job completed for job: " + str(job))
return 0
elif line.find("Completed <exit>") > -1:
logger.info("bjobs detected job failed for job: " + str(job))
return 1
elif line.find("New job is waiting for scheduling") > -1:
logger.info("bjobs detected job pending scheduling for job: " + str(job))
return None
elif line.find("PENDING REASONS") > -1:
logger.info("bjobs detected job pending for job: " + str(job))
return None
elif line.find("Started on ") > -1:
started = 1
if started == 1:
logger.info("bjobs detected job started but not completed: " + str(job))
return None
#if not found in bjobs, then try bacct (slower than bjobs)
logger.info("bjobs failed to detect job - trying bacct: " + str(job))
args = ["bacct", "-l", str(job)]
logger.info("Checking job exit code for job via bacct:" + str(job))
process = subprocess.Popen(" ".join(args), shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
for line in process.stdout:
if line.find("Completed <done>") > -1:
logger.info("Detected job completed for job: " + str(job))
return 0
elif line.find("Completed <exit>") > -1:
logger.info("Detected job failed for job: " + str(job))
return 1
logger.info("Cant determine exit code for job or job still running: " + str(job))
return None
class Worker(Thread):
def __init__(self, newJobsQueue, updatedJobsQueue, boss):
Thread.__init__(self)
self.newJobsQueue = newJobsQueue
self.updatedJobsQueue = updatedJobsQueue
self.currentjobs = list()
self.runningjobs = set()
self.boss = boss
def run(self):
while True:
# Load new job ids:
while not self.newJobsQueue.empty():
self.currentjobs.append(self.newJobsQueue.get())
# Launch jobs as necessary:
while len(self.currentjobs) > 0:
jobID, bsubline = self.currentjobs.pop()
lsfJobID = bsub(bsubline)
self.boss.jobIDs[(lsfJobID, None)] = jobID
self.boss.lsfJobIDs[jobID] = (lsfJobID, None)
self.runningjobs.add((lsfJobID, None))
# Test known job list
for lsfJobID in list(self.runningjobs):
exit = getjobexitcode(lsfJobID)
if exit is not None:
self.updatedJobsQueue.put((lsfJobID, exit))
self.runningjobs.remove(lsfJobID)
time.sleep(10)
class LSFBatchSystem(AbstractBatchSystem):
"""The interface for running jobs on lsf, runs all the jobs you
give it as they come in, but in parallel.
"""
@classmethod
def getDisplayNames(cls):
"""
Names used to select this batch system.
"""
return ["lsf","LSF"]
def __init__(self, config, maxCpus, maxMemory):
AbstractBatchSystem.__init__(self, config, maxCpus, maxMemory) #Call the parent constructor
self.lsfResultsFile = getParasolResultsFileName(config.attrib["job_tree"])
#Reset the job queue and results (initially, we do this again once we've killed the jobs)
self.lsfResultsFileHandle = open(self.lsfResultsFile, 'w')
self.lsfResultsFileHandle.close() #We lose any previous state in this file, and ensure the files existence
self.currentjobs = set()
self.obtainSystemConstants()
self.jobIDs = dict()
self.lsfJobIDs = dict()
self.nextJobID = 0
self.newJobsQueue = Queue()
self.updatedJobsQueue = Queue()
self.worker = Worker(self.newJobsQueue, self.updatedJobsQueue, self)
self.worker.setDaemon(True)
self.worker.start()
def __des__(self):
#Closes the file handle associated with the results file.
self.lsfResultsFileHandle.close() #Close the results file, cos were done.
def issueJob(self, command, memory, cpu):
jobID = self.nextJobID
self.nextJobID += 1
self.currentjobs.add(jobID)
bsubline = prepareBsub(cpu, memory) + [command]
self.newJobsQueue.put((jobID, bsubline))
logger.info("Issued the job command: %s with job id: %s " % (command, str(jobID)))
return jobID
def getLsfID(self, jobID):
if not jobID in self.lsfJobIDs:
RuntimeError("Unknown jobID, could not be converted")
(job,task) = self.lsfJobIDs[jobID]
if task is None:
return str(job)
else:
return str(job) + "." + str(task)
def killJobs(self, jobIDs):
"""Kills the given job IDs.
"""
for jobID in jobIDs:
logger.info("DEL: " + str(self.getLsfID(jobID)))
self.currentjobs.remove(jobID)
process = subprocess.Popen(["bkill", self.getLsfID(jobID)])
del self.jobIDs[self.lsfJobIDs[jobID]]
del self.lsfJobIDs[jobID]
toKill = set(jobIDs)
while len(toKill) > 0:
for jobID in list(toKill):
if getjobexitcode(self.lsfJobIDs[jobID]) is not None:
toKill.remove(jobID)
if len(toKill) > 0:
logger.critical("Tried to kill some jobs, but something happened and they are still going, so I'll try again")
time.sleep(5)
def getIssuedJobIDs(self):
"""A list of jobs (as jobIDs) currently issued (may be running, or maybe
just waiting).
"""
return self.currentjobs
def getRunningJobIDs(self):
"""Gets a map of jobs (as jobIDs) currently running (not just waiting)
and a how long they have been running for (in seconds).
"""
times = {}
currentjobs = set(self.lsfJobIDs[x] for x in self.getIssuedJobIDs())
process = subprocess.Popen(["bjobs"], stdout = subprocess.PIPE)
for currline in process.stdout:
items = curline.strip().split()
if (len(items) > 9 and (items[0]) in currentjobs) and items[2] == 'RUN':
jobstart = "/".join(items[7:9]) + '/' + str(date.today().year)
jobstart = jobstart + ' ' + items[9]
jobstart = time.mktime(time.strptime(jobstart,"%b/%d/%Y %H:%M"))
jobstart = time.mktime(time.strptime(jobstart,"%m/%d/%Y %H:%M:%S"))
times[self.jobIDs[(items[0])]] = time.time() - jobstart
return times
def getUpdatedJob(self, maxWait):
i = None
try:
sgeJobID, retcode = self.updatedJobsQueue.get(timeout=maxWait)
self.updatedJobsQueue.task_done()
i = (self.jobIDs[sgeJobID], retcode)
self.currentjobs -= set([self.jobIDs[sgeJobID]])
except Empty:
pass
return i
def getWaitDuration(self):
"""We give parasol a second to catch its breath (in seconds)
"""
#return 0.0
return 15
def getRescueJobFrequency(self):
"""Parasol leaks jobs, but rescuing jobs involves calls to parasol list jobs and pstat2,
making it expensive. We allow this every 10 minutes..
"""
return 1800
def obtainSystemConstants(self):
p = subprocess.Popen(["lshosts"], stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
line = p.stdout.readline()
items = line.strip().split()
num_columns = len(items)
cpu_index = None
mem_index = None
for i in range(num_columns):
if items[i] == 'ncpus':
cpu_index = i
elif items[i] == 'maxmem':
mem_index = i
if cpu_index is None or mem_index is None:
RuntimeError("lshosts command does not return ncpus or maxmem columns")
p.stdout.readline()
self.maxCPU = 0
self.maxMEM = MemoryString("0")
for line in p.stdout:
items = line.strip().split()
if len(items) < num_columns:
RuntimeError("lshosts output has a varying number of columns")
if items[cpu_index] != '-' and items[cpu_index] > self.maxCPU:
self.maxCPU = items[cpu_index]
if items[mem_index] != '-' and MemoryString(items[mem_index]) > self.maxMEM:
self.maxMEM = MemoryString(items[mem_index])
if self.maxCPU is 0 or self.maxMEM is 0:
RuntimeError("lshosts returns null ncpus or maxmem info")
logger.info("Got the maxCPU: %s" % (self.maxMEM))
def main():
pass
def _test():
import doctest
return doctest.testmod()
if __name__ == '__main__':
_test()
main()
| harvardinformatics/jobTree | batchSystems/lsf.py | Python | mit | 12,569 | 0.010661 |
from src.platform.weblogic.interfaces import WINTERFACES, WLConsole
class FPrint(WLConsole):
""" WebLogic 10 is bugged when using Oracle's custom implementation of SSL.
Only if the default Java implementation is set will this work; otherwise,
Oracle sends an SSL23_GET_SERVER_HELLO and breaks OpenSSL.
"""
def __init__(self):
super(FPrint, self).__init__()
self.version = "10"
self.title = WINTERFACES.WLS
self.port = 9002
self.ssl = True
| GHubgenius/clusterd | src/platform/weblogic/fingerprints/WL10s.py | Python | mit | 510 | 0.001961 |
import pytest
from waterbutler.providers.onedrive.path import OneDrivePath
from tests.providers.onedrive.fixtures import (path_fixtures,
root_provider_fixtures,
subfolder_provider_fixtures)
class TestApiIdentifier:
def test_api_identifier_none(self):
path = OneDrivePath('/foo', _ids=('root', None,))
assert path.api_identifier is None
def test_api_identifier_root(self):
path = OneDrivePath('/', _ids=('root',))
assert path.api_identifier == ('root',)
def test_api_identifier_folder_id(self):
path = OneDrivePath('/', _ids=('123456',))
assert path.api_identifier == ('items', '123456',)
def test_api_identifier_file_id(self):
path = OneDrivePath('/foo', _ids=('123456','7891011',))
assert path.api_identifier == ('items', '7891011',)
class TestNewFromResponseRootProvider:
def test_file_in_root(self, root_provider_fixtures):
od_path = OneDrivePath.new_from_response(root_provider_fixtures['file_metadata'], 'root')
assert od_path.identifier == root_provider_fixtures['file_id']
assert str(od_path) == '/toes.txt'
assert len(od_path.parts) == 2
ids = [x.identifier for x in od_path.parts]
assert ids == ['root', root_provider_fixtures['file_id']]
def test_folder_in_root(self, root_provider_fixtures):
od_path = OneDrivePath.new_from_response(root_provider_fixtures['folder_metadata'], 'root')
assert od_path.identifier == root_provider_fixtures['folder_id']
assert str(od_path) == '/teeth/'
assert len(od_path.parts) == 2
ids = [x.identifier for x in od_path.parts]
assert ids == ['root', root_provider_fixtures['folder_id']]
def test_file_in_subdir(self, root_provider_fixtures):
od_path = OneDrivePath.new_from_response(root_provider_fixtures['subfile_metadata'], 'root')
assert od_path.identifier == root_provider_fixtures['subfile_id']
assert str(od_path) == '/teeth/bicuspid.txt'
assert len(od_path.parts) == 3
ids = [x.identifier for x in od_path.parts]
assert ids == ['root',
root_provider_fixtures['folder_id'],
root_provider_fixtures['subfile_id']]
def test_fails_without_base_folder(self, root_provider_fixtures):
with pytest.raises(Exception):
od_path = OneDrivePath.new_from_response(root_provider_fixtures['file_metadata'])
def test_insert_zero_ids(self, path_fixtures):
file_metadata = path_fixtures['deeply_nested_file_metadata']
od_path = OneDrivePath.new_from_response(file_metadata, 'root')
file_id = path_fixtures['deeply_nested_file_id']
assert od_path.identifier == file_id
assert str(od_path) == '/deep/deeper/deepest/positively abyssyal/the kraken.txt'
assert len(od_path.parts) == 6
ids = [x.identifier for x in od_path.parts]
assert ids == ['root', None, None, None, 'F4D50E400DFE7D4E!298', file_id]
class TestNewFromResponseSubfolderProvider:
def test_file_in_root(self, subfolder_provider_fixtures):
od_path = OneDrivePath.new_from_response(subfolder_provider_fixtures['file_metadata'],
subfolder_provider_fixtures['root_id'])
assert od_path.identifier == subfolder_provider_fixtures['file_id']
assert str(od_path) == '/bicuspid.txt'
assert len(od_path.parts) == 2
ids = [x.identifier for x in od_path.parts]
assert ids == [subfolder_provider_fixtures['root_id'],
subfolder_provider_fixtures['file_id']]
def test_subfolder_base_is_folder(self, subfolder_provider_fixtures):
od_path = OneDrivePath.new_from_response(subfolder_provider_fixtures['folder_metadata'],
subfolder_provider_fixtures['root_id'])
assert od_path.identifier == subfolder_provider_fixtures['folder_id']
assert str(od_path) == '/crushers/'
assert len(od_path.parts) == 2
ids = [x.identifier for x in od_path.parts]
assert ids == [subfolder_provider_fixtures['root_id'],
subfolder_provider_fixtures['folder_id']]
def test_file_in_subdir(self, subfolder_provider_fixtures):
od_path = OneDrivePath.new_from_response(subfolder_provider_fixtures['subfile_metadata'],
subfolder_provider_fixtures['root_id'],
base_folder_metadata=subfolder_provider_fixtures['root_metadata'])
assert od_path.identifier == subfolder_provider_fixtures['subfile_id']
assert str(od_path) == '/crushers/molars.txt'
assert len(od_path.parts) == 3
ids = [x.identifier for x in od_path.parts]
assert ids == [subfolder_provider_fixtures['root_id'],
subfolder_provider_fixtures['folder_id'],
subfolder_provider_fixtures['subfile_id']]
| rdhyee/waterbutler | tests/providers/onedrive/test_path.py | Python | apache-2.0 | 5,141 | 0.003307 |
import logging
# Disable logging in unit tests
logging.disable(logging.CRITICAL)
| bramfoo/solarstats | tests/__init__.py | Python | gpl-2.0 | 82 | 0 |
import math
def square_root ( a ):
"""Computes squar root of a
"""
espilon = 0.1e-11
x = a
while True:
y = ( x + a / x ) / 2.0
if abs( y - x ) < espilon:
return y
x = y
def test_square_root():
"""Compares custom square and math.sqrt.
"""
a = 1.0
while a < 10.0:
print a, '{:<13}'.format( square_root( a ) ), \
'{:<13}'.format( math.sqrt( a ) ), \
abs( square_root( a ) - math.sqrt( a ) )
a += 1
test_square_root()
| hacpai/show-me-the-code | Python/0033/main.py | Python | gpl-2.0 | 540 | 0.038889 |
from sendit.logger import bot
from sendit.apps.main.models import Batch
from django.core.management.base import (
BaseCommand
)
from sendit.apps.main.models import Batch
from sendit.apps.main.tasks import import_dicomdir
from sendit.apps.main.utils import ls_fullpath
from sendit.apps.api.utils import get_size
import sys
import os
import datetime
import pandas
class Command(BaseCommand):
help = '''export metrics about size and times to file'''
def handle(self,*args, **options):
df = pandas.DataFrame(columns=['batch_id','status','size_mb',
'start_time','finish_time',
'total_time_sec','total_time_min'])
output_file = 'sendit-process-time-%s.tsv' %datetime.datetime.today().strftime('%Y-%m-%d')
for batch in Batch.objects.all():
df.loc[batch.id,'batch_id'] = batch.id
df.loc[batch.id,'status'] = batch.status
if batch.status == "DONE":
df.loc[batch.id,'size_gb'] = get_size(batch)
df.loc[batch.id,'start_time'] = batch.qa['StartTime']
df.loc[batch.id,'finish_time'] = batch.qa['FinishTime']
time = batch.qa['FinishTime'] - batch.qa['StartTime']
df.loc[batch.id,'total_time_sec'] = time
df.loc[batch.id,'total_time_min'] = time/60.0
df.sort_values(by=['status'],inplace=True)
df.to_csv(output_file,sep='\t')
| pydicom/sendit | sendit/apps/main/management/commands/export_metrics.py | Python | mit | 1,497 | 0.014028 |
"""
ProofResourceStrategy is the real implementation of initializing the resource
data for ProofResource. There can be multiple strategies for one ProofResource.
Main considerations are configure file, database (may use a ProofInstance),
XML file.
This is the base class with all interfaces needed by ProofResource. Each different
strategies can futher extend from this class to include strategic specific
functions.
By separating the strategy process from resource interfaces, we can make
ProofInstance work both as stand-alone and shared persistent data layer.
It also make testing easier by creating some dummy strategy implementations.
"""
__version__='$Revision: 117 $'[11:-2]
__author__ = "Duan Guoqiang (mattgduan@gmail.com)"
import logging
class ProofResourceStrategy:
def __init__(self, logger=None):
pass
def __parseXMLDBMap(self, schema, xml):
pass
def getDatabaseMap(self, schema):
pass
| mattduan/proof | ProofResourceStrategy.py | Python | bsd-3-clause | 946 | 0.004228 |
# -*- coding: utf-8 -*-
# Copyright(C) 2015 Vincent A
#
# This file is part of weboob.
#
# weboob 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.
#
# weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>.
import math
from urlparse import urljoin
from StringIO import StringIO
from weboob.browser import PagesBrowser, URL
from .pages import ImagePage, UploadPage
class LutimBrowser(PagesBrowser):
BASEURL = 'https://lut.im'
VERIFY = False # XXX SNI is not supported
image_page = URL('/(?P<id>.+)', ImagePage)
upload_page = URL('/', UploadPage)
def __init__(self, base_url, *args, **kw):
PagesBrowser.__init__(self, *args, **kw)
self.base_url = self.BASEURL = base_url
def fetch(self, paste):
self.location(paste.id)
assert self.image_page.is_here()
paste.contents = unicode(self.page.contents.encode('base64'))
paste.title = self.page.filename
def post(self, paste, max_age=0):
bin = paste.contents.decode('base64')
name = paste.title or 'file' # filename is mandatory
filefield = {'file': (name, StringIO(bin))}
params = {'format': 'json'}
if max_age:
params['delete-day'] = math.ceil(max_age / 86400.)
self.location('/', data=params, files=filefield)
assert self.upload_page.is_here()
info = self.page.fetch_info()
paste.id = urljoin(self.base_url, info['short'])
| sputnick-dev/weboob | modules/lutim/browser.py | Python | agpl-3.0 | 1,959 | 0.001021 |
import pandas as pd
from enviropy import Enviropy
def read_csv(fname):
df = pd.read_csv(fname)
return Enviropy(df) | jentjr/enviropy | enviropy/io/file.py | Python | mit | 123 | 0.01626 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.forms import ModelForm, TextInput
from django.contrib import admin
from blog.models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'created', 'status']
list_filter = ('status', )
admin.site.register(Post, PostAdmin) | pythonvlc/PyConES-2015 | pycones/blog/admin.py | Python | mit | 336 | 0.002976 |
#!/usr/bin/python
'''test that the build and run results are OK'''
# threads.heapprof should have 2 call stacks allocating 1024 blocks each
import commands, sys
print 'testing that *.heapprof files contain the expected results...'
assert commands.getoutput("grep ' 1024 ' threads.heapprof | wc -l").strip() == '2'
second = open('second.heapprof').read()
if 'no heap blocks found' in second:
print "threads.heapprof is OK but second.heapprof is not - perhaps gdb's gcore command doesn't work? Is it gdb 7.2 and up?"
print "anyway, this test failed but presumably heapprof itself works correctly."
sys.exit()
assert '1048576 [1048576]' in second
assert '1048576 [131073, 131073, 131071, 131073, 131071, 131073, 131071, 131071]' in second
assert 'example_func' in second
assert 'another_func' in second
print 'ok.'
| yosefk/heapprof | ok.py | Python | bsd-2-clause | 823 | 0.010936 |
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD license as follows:
##
## "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 Digia Plc and its Subsidiary(-ies) 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."
## $QT_END_LICENSE$
##
#############################################################################
from PyQt5.QtCore import pyqtProperty, pyqtSignal, QPointF, QUrl
from PyQt5.QtGui import QColor, QGuiApplication
from PyQt5.QtQml import qmlRegisterType
from PyQt5.QtQuick import (QQuickItem, QQuickView, QSGFlatColorMaterial,
QSGGeometry, QSGGeometryNode, QSGNode)
import customgeometry_rc
class BezierCurve(QQuickItem):
p1Changed = pyqtSignal(QPointF)
@pyqtProperty(QPointF, notify=p1Changed)
def p1(self):
return self._p1
@p1.setter
def p1(self, p):
if self._p1 != p:
self._p1 = QPointF(p)
self.p1Changed.emit(p)
self.update()
p2Changed = pyqtSignal(QPointF)
@pyqtProperty(QPointF, notify=p2Changed)
def p2(self):
return self._p2
@p2.setter
def p2(self, p):
if self._p2 != p:
self._p2 = QPointF(p)
self.p2Changed.emit(p)
self.update()
p3Changed = pyqtSignal(QPointF)
@pyqtProperty(QPointF, notify=p3Changed)
def p3(self):
return self._p3
@p3.setter
def p3(self, p):
if self._p3 != p:
self._p3 = QPointF(p)
self.p3Changed.emit(p)
self.update()
p4Changed = pyqtSignal(QPointF)
@pyqtProperty(QPointF, notify=p4Changed)
def p4(self):
return self._p4
@p4.setter
def p4(self, p):
if self._p4 != p:
self._p4 = QPointF(p)
self.p4Changed.emit(p)
self.update()
segmentCountChanged = pyqtSignal(int)
@pyqtProperty(int, notify=segmentCountChanged)
def segmentCount(self):
return self._segmentCount
@segmentCount.setter
def segmentCount(self, count):
if self._segmentCount != count:
self._segmentCount = count
self.segmentCountChanged.emit(count)
self.update()
def __init__(self, parent=None):
super(BezierCurve, self).__init__(parent)
self._p1 = QPointF(0, 0)
self._p2 = QPointF(1, 0)
self._p3 = QPointF(0, 1)
self._p4 = QPointF(1, 1)
self._segmentCount = 32
self._root_node = None
self.setFlag(QQuickItem.ItemHasContents, True)
def updatePaintNode(self, oldNode, nodeData):
if self._root_node is None:
self._root_node = QSGGeometryNode()
geometry = QSGGeometry(QSGGeometry.defaultAttributes_Point2D(),
self._segmentCount)
geometry.setLineWidth(2)
geometry.setDrawingMode(QSGGeometry.GL_LINE_STRIP)
self._root_node.setGeometry(geometry)
self._root_node.setFlag(QSGNode.OwnsGeometry)
material = QSGFlatColorMaterial()
material.setColor(QColor(255, 0, 0))
self._root_node.setMaterial(material)
self._root_node.setFlag(QSGNode.OwnsMaterial)
else:
geometry = self._root_node.geometry()
geometry.allocate(self._segmentCount)
w = self.width()
h = self.height()
vertices = geometry.vertexDataAsPoint2D()
for i in range(self._segmentCount):
t = i / float(self._segmentCount - 1)
invt = 1 - t
pos = invt * invt * invt * self._p1 \
+ 3 * invt * invt * t * self._p2 \
+ 3 * invt * t * t * self._p3 \
+ t * t * t * self._p4
vertices[i].set(pos.x() * w, pos.y() * h)
self._root_node.markDirty(QSGNode.DirtyGeometry)
return self._root_node
if __name__ == '__main__':
import sys
app = QGuiApplication(sys.argv)
qmlRegisterType(BezierCurve, "CustomGeometry", 1, 0, "BezierCurve")
view = QQuickView()
format = view.format()
format.setSamples(16)
view.setFormat(format)
view.setSource(QUrl('qrc:///scenegraph/customgeometry/main.qml'))
view.show()
sys.exit(app.exec_())
| DevinDewitt/pyqt5 | examples/quick/scenegraph/customgeometry/customgeometry.py | Python | gpl-3.0 | 5,911 | 0.005414 |
import os, sys, commands
def print_debug( msg, verbose ):
data_dir_root = os.environ.get('DATADIR')
debug_level = int(os.environ.get('DEBUGLEVEL'))
#print the message to debug log if debug variable is set
#add 'from debug import *' to header
# call with print_debug("my message",5)
# outputs to Datadir/debug.log if the number above is > than the number in Datadir/debug.level
if int(verbose) < debug_level:
commands.getoutput('echo '+msg+' >> '+data_dir_root+'/debug.log')
return 1
return 0
| achamely/omniwallet | api/debug.py | Python | agpl-3.0 | 530 | 0.032075 |
# Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Authors:
# Michael Cohen <scudette@google.com>
#
# 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
#
"""This file implements an xls renderer based on the openpyxl project.
We produce xls (Excel spreadsheet files) with the output from Rekall plugins.
"""
import time
import openpyxl
from openpyxl import styles
from openpyxl.styles import colors
from openpyxl.styles import fills
from rekall import utils
from rekall.ui import renderer
from rekall.ui import text
# pylint: disable=unexpected-keyword-arg,no-value-for-parameter
# pylint: disable=redefined-outer-name
HEADER_STYLE = styles.Style(font=styles.Font(bold=True))
SECTION_STYLE = styles.Style(
fill=styles.PatternFill(
fill_type=fills.FILL_SOLID, start_color=styles.Color(colors.RED)))
FORMAT_STYLE = styles.Style(
alignment=styles.Alignment(vertical="top", wrap_text=False))
class XLSObjectRenderer(renderer.ObjectRenderer):
"""By default the XLS renderer delegates to the text renderer."""
renders_type = "object"
renderers = ["XLSRenderer"]
STYLE = None
def _GetDelegateObjectRenderer(self, item):
return self.ForTarget(item, "TextRenderer")(
session=self.session, renderer=self.renderer.delegate_text_renderer)
def RenderHeader(self, worksheet, column):
cell = worksheet.cell(
row=worksheet.current_row, column=worksheet.current_column)
cell.value = column.name
cell.style = HEADER_STYLE
# Advance the pointer by 1 cell.
worksheet.current_column += 1
def RenderCell(self, value, worksheet, **options):
# By default just render a single value into the current cell.
cell = worksheet.cell(
row=worksheet.current_row, column=worksheet.current_column)
cell.value = self.GetData(value, **options)
if self.STYLE:
cell.style = self.STYLE
# Advance the pointer by 1 cell.
worksheet.current_column += 1
def GetData(self, value, **options):
if isinstance(value, (int, float, long)):
return value
return unicode(self._GetDelegateObjectRenderer(value).render_row(
value, **options))
class XLSColumn(text.TextColumn):
def __init__(self, type=None, table=None, renderer=None, session=None,
**options):
super(XLSColumn, self).__init__(table=table, renderer=renderer,
session=session, **options)
if type:
self.object_renderer = self.renderer.get_object_renderer(
type=type, target_renderer="XLSRenderer", **options)
class XLSTable(text.TextTable):
column_class = XLSColumn
def render_header(self):
current_ws = self.renderer.current_ws
for column in self.columns:
if column.object_renderer:
object_renderer = column.object_renderer
else:
object_renderer = XLSObjectRenderer(
session=self.session, renderer=self.renderer)
object_renderer.RenderHeader(self.renderer.current_ws, column)
current_ws.current_row += 1
current_ws.current_column = 1
def render_row(self, row=None, highlight=None, **options):
merged_opts = self.options.copy()
merged_opts.update(options)
# Get each column to write its own header.
current_ws = self.renderer.current_ws
for item in row:
# Get the object renderer for the item.
object_renderer = self.renderer.get_object_renderer(
target=item, type=merged_opts.get("type"), **merged_opts)
object_renderer.RenderCell(item, current_ws, **options)
current_ws.current_row += 1
current_ws.current_column = 1
class XLSRenderer(renderer.BaseRenderer):
"""A Renderer for xls files."""
name = "xls"
table_class = XLSTable
tablesep = ""
def __init__(self, output=None, **kwargs):
super(XLSRenderer, self).__init__(**kwargs)
# Make a single delegate text renderer for reuse. Most of the time we
# will just replicate the output from the TextRenderer inside the
# spreadsheet cell.
self.delegate_text_renderer = text.TextRenderer(session=self.session)
self.output = output or self.session.GetParameter("output")
# If no output filename was give, just make a name based on the time
# stamp.
if self.output == None:
self.output = "%s.xls" % time.ctime()
try:
self.wb = openpyxl.load_workbook(self.output)
self.current_ws = self.wb.create_sheet()
except IOError:
self.wb = openpyxl.Workbook()
self.current_ws = self.wb.active
def start(self, plugin_name=None, kwargs=None):
super(XLSRenderer, self).start(plugin_name=plugin_name, kwargs=kwargs)
# Make a new worksheet for this run.
if self.current_ws is None:
self.current_ws = self.wb.create_sheet()
ws = self.current_ws
ws.title = plugin_name or ""
ws.current_row = 1
ws.current_column = 1
return self
def flush(self):
super(XLSRenderer, self).flush()
self.current_ws = None
# Write the spreadsheet to a file.
self.wb.save(self.output)
def section(self, name=None, **_):
ws = self.current_ws
for i in range(10):
cell = ws.cell(row=ws.current_row, column=i + 1)
if i == 0:
cell.value = name
cell.style = SECTION_STYLE
ws.current_row += 1
ws.current_column = 1
def format(self, formatstring, *data):
worksheet = self.current_ws
if "%" in formatstring:
data = formatstring % data
else:
data = formatstring.format(*data)
cell = worksheet.cell(
row=worksheet.current_row, column=worksheet.current_column)
cell.value = data
cell.style = FORMAT_STYLE
worksheet.current_column += 1
if "\n" in data:
worksheet.current_row += 1
worksheet.current_column = 1
def table_header(self, *args, **options):
super(XLSRenderer, self).table_header(*args, **options)
self.table.render_header()
# Following here are object specific renderers.
class XLSEProcessRenderer(XLSObjectRenderer):
"""Expands an EPROCESS into three columns (address, name and PID)."""
renders_type = "_EPROCESS"
def RenderHeader(self, worksheet, column):
for heading in ["_EPROCESS", "Name", "PID"]:
cell = worksheet.cell(
row=worksheet.current_row, column=worksheet.current_column)
cell.value = heading
cell.style = HEADER_STYLE
worksheet.current_column += 1
def RenderCell(self, item, worksheet, **options):
for value in ["%#x" % item.obj_offset, item.name, item.pid]:
object_renderer = self.ForTarget(value, self.renderer)(
session=self.session, renderer=self.renderer, **options)
object_renderer.RenderCell(value, worksheet, **options)
class XLSStringRenderer(XLSObjectRenderer):
renders_type = "String"
def GetData(self, item, **_):
return utils.SmartStr(item)
class XLSStructRenderer(XLSObjectRenderer):
"""Hex format struct's offsets."""
renders_type = "Struct"
def GetData(self, item, **_):
return "%#x" % item.obj_offset
class XLSPointerRenderer(XLSObjectRenderer):
"""Renders the address of the pointer target as a hex string."""
renders_type = "Pointer"
def GetData(self, item, **_):
result = item.v()
if result == None:
return "-"
return "%#x" % result
class XLSNativeTypeRenderer(XLSObjectRenderer):
"""Renders native types as python objects."""
renders_type = "NativeType"
def GetData(self, item, **options):
result = item.v()
if result != None:
return result
class XLS_UNICODE_STRING_Renderer(XLSNativeTypeRenderer):
renders_type = "_UNICODE_STRING"
class XLSNoneObjectRenderer(XLSObjectRenderer):
renders_type = "NoneObject"
def GetData(self, item, **_):
_ = item
return "-"
class XLSDateTimeRenderer(XLSObjectRenderer):
"""Renders timestamps as python datetime objects."""
renders_type = "UnixTimeStamp"
STYLE = styles.Style(number_format='MM/DD/YYYY HH:MM:SS')
def GetData(self, item, **options):
if item.v() == 0:
return None
return item.as_datetime()
| dsweet04/rekall | rekall-core/rekall/plugins/renderers/xls.py | Python | gpl-2.0 | 9,365 | 0.000427 |
"""
Module responsible for translating reference sequence data into GA4GH native
objects.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import hashlib
import json
import os
import random
import pysam
import ga4gh.datamodel as datamodel
import ga4gh.protocol as protocol
import ga4gh.exceptions as exceptions
DEFAULT_REFERENCESET_NAME = "Default"
"""
This is the name used for any reference set referred to in a BAM
file that does not provide the 'AS' tag in the @SQ header.
"""
class AbstractReferenceSet(datamodel.DatamodelObject):
"""
Class representing ReferenceSets. A ReferenceSet is a set of
References which typically comprise a reference assembly, such as
GRCh38.
"""
compoundIdClass = datamodel.ReferenceSetCompoundId
def __init__(self, localId):
super(AbstractReferenceSet, self).__init__(None, localId)
self._referenceIdMap = {}
self._referenceNameMap = {}
self._referenceIds = []
self._assemblyId = None
self._description = None
self._isDerived = False
self._ncbiTaxonId = None
self._sourceAccessions = []
self._sourceUri = None
def addReference(self, reference):
"""
Adds the specified reference to this ReferenceSet.
"""
id_ = reference.getId()
self._referenceIdMap[id_] = reference
self._referenceNameMap[reference.getLocalId()] = reference
self._referenceIds.append(id_)
def getReferences(self):
"""
Returns the References in this ReferenceSet.
"""
return [self._referenceIdMap[id_] for id_ in self._referenceIds]
def getNumReferences(self):
"""
Returns the number of references in this ReferenceSet.
"""
return len(self._referenceIds)
def getReferenceByIndex(self, index):
"""
Returns the reference at the specified index in this ReferenceSet.
"""
return self._referenceIdMap[self._referenceIds[index]]
def getReferenceByName(self, name):
"""
Returns the reference with the specified name.
"""
if name not in self._referenceNameMap:
raise exceptions.ReferenceNameNotFoundException(name)
return self._referenceNameMap[name]
def getReference(self, id_):
"""
Returns the Reference with the specified ID or raises a
ReferenceNotFoundException if it does not exist.
"""
if id_ not in self._referenceIdMap:
raise exceptions.ReferenceNotFoundException(id_)
return self._referenceIdMap[id_]
def getMd5Checksum(self):
"""
Returns the MD5 checksum for this reference set. This checksum is
calculated by making a list of `Reference.md5checksum` for all
`Reference`s in this set. We then sort this list, and take the
MD5 hash of all the strings concatenated together.
"""
references = sorted(
self.getReferences(),
key=lambda ref: ref.getMd5Checksum())
checksums = ''.join([ref.getMd5Checksum() for ref in references])
md5checksum = hashlib.md5(checksums).hexdigest()
return md5checksum
def getAssemblyId(self):
"""
Returns the assembly ID for this reference set.
This is the public id of this reference set, such as `GRCh37`
"""
return self._assemblyId
def getDescription(self):
"""
Returns the free text description of this reference set.
"""
return self._description
def getIsDerived(self):
"""
Returns True if this ReferenceSet is derived. A ReferenceSet
may be derived from a source if it contains additional sequences,
or some of the sequences within it are derived.
"""
return self._isDerived
def getSourceAccessions(self):
"""
Returns the list of source accession strings. These are all known
corresponding accession IDs in INSDC (GenBank/ENA/DDBJ) ideally
with a version number, e.g. `NC_000001.11`.
"""
return self._sourceAccessions
def getSourceUri(self):
"""
Returns the sourceURI for this ReferenceSet.
"""
return self._sourceUri
def getNcbiTaxonId(self):
"""
Returns the NCBI Taxon ID for this reference set. This is the
ID from http://www.ncbi.nlm.nih.gov/taxonomy (e.g. 9606->human)
indicating the species which this assembly is intended to model.
Note that contained `Reference`s may specify a different
`ncbiTaxonId`, as assemblies may contain reference sequences
which do not belong to the modeled species, e.g. EBV in a
human reference genome.
"""
return self._ncbiTaxonId
def toProtocolElement(self):
"""
Returns the GA4GH protocol representation of this ReferenceSet.
"""
ret = protocol.ReferenceSet()
ret.assemblyId = self.getAssemblyId()
ret.description = self.getDescription()
ret.id = self.getId()
ret.isDerived = self.getIsDerived()
ret.md5checksum = self.getMd5Checksum()
ret.ncbiTaxonId = self.getNcbiTaxonId()
ret.referenceIds = self._referenceIds
ret.sourceAccessions = self.getSourceAccessions()
ret.sourceURI = self.getSourceUri()
ret.name = self.getLocalId()
return ret
class AbstractReference(datamodel.DatamodelObject):
"""
Class representing References. A Reference is a canonical
assembled contig, intended to act as a reference coordinate space
for other genomic annotations. A single Reference might represent
the human chromosome 1, for instance.
"""
compoundIdClass = datamodel.ReferenceCompoundId
def __init__(self, parentContainer, localId):
super(AbstractReference, self).__init__(parentContainer, localId)
self._length = -1
self._md5checksum = ""
self._sourceUri = None
self._sourceAccessions = []
self._isDerived = False
self._sourceDivergence = None
self._ncbiTaxonId = None
def getLength(self):
"""
Returns the length of this reference's sequence string.
"""
return self._length
def getName(self):
"""
Returns the name of this reference, e.g., '22'.
"""
return self.getLocalId()
def getIsDerived(self):
"""
Returns True if this Reference is derived. A sequence X is said to be
derived from source sequence Y, if X and Y are of the same length and
the per-base sequence divergence at A/C/G/T bases is sufficiently
small. Two sequences derived from the same official sequence share the
same coordinates and annotations, and can be replaced with the official
sequence for certain use cases.
"""
return self._isDerived
def getSourceDivergence(self):
"""
Returns the source divergence for this reference. The sourceDivergence
is the fraction of non-indel bases that do not match the
reference this record was derived from.
"""
return self._sourceDivergence
def getSourceAccessions(self):
"""
Returns the list of source accession strings. These are all known
corresponding accession IDs in INSDC (GenBank/ENA/DDBJ) ideally
with a version number, e.g. `NC_000001.11`.
"""
return self._sourceAccessions
def getSourceUri(self):
"""
The URI from which the sequence was obtained. Specifies a FASTA format
file/string with one name, sequence pair.
"""
return self._sourceUri
def getNcbiTaxonId(self):
"""
Returns the NCBI Taxon ID for this reference. This is the
ID from http://www.ncbi.nlm.nih.gov/taxonomy (e.g. 9606->human)
indicating the species which this assembly is intended to model.
Note that contained `Reference`s may specify a different
`ncbiTaxonId`, as assemblies may contain reference sequences
which do not belong to the modeled species, e.g. EBV in a
human reference genome.
"""
return self._ncbiTaxonId
def getMd5Checksum(self):
"""
Returns the MD5 checksum uniquely representing this `Reference` as a
lower-case hexadecimal string, calculated as the MD5 of the upper-case
sequence excluding all whitespace characters.
"""
return self._md5checksum
def toProtocolElement(self):
"""
Returns the GA4GH protocol representation of this Reference.
"""
reference = protocol.Reference()
reference.id = self.getId()
reference.isDerived = self.getIsDerived()
reference.length = self.getLength()
reference.md5checksum = self.getMd5Checksum()
reference.name = self.getName()
reference.ncbiTaxonId = self.getNcbiTaxonId()
reference.sourceAccessions = self.getSourceAccessions()
reference.sourceDivergence = self.getSourceDivergence()
reference.sourceURI = self.getSourceUri()
return reference
def checkQueryRange(self, start, end):
"""
Checks to ensure that the query range is valid within this reference.
If not, raise ReferenceRangeErrorException.
"""
condition = (
(start < 0 or end > self.getLength()) or
start > end)
if condition:
raise exceptions.ReferenceRangeErrorException(
self.getId(), start, end)
def getBases(self, start, end):
"""
Returns the string representing the bases of this reference from
start (inclusive) to end (exclusive).
"""
raise NotImplemented()
##################################################################
#
# Simulated references
#
##################################################################
class SimulatedReferenceSet(AbstractReferenceSet):
"""
A simulated referenceSet
"""
def __init__(self, localId, randomSeed=0, numReferences=1):
super(SimulatedReferenceSet, self).__init__(localId)
self._randomSeed = randomSeed
self._randomGenerator = random.Random()
self._randomGenerator.seed(self._randomSeed)
self._description = "Simulated reference set"
self._assemblyId = str(random.randint(0, 2**32))
self._isDerived = bool(random.randint(0, 1))
self._ncbiTaxonId = random.randint(0, 2**16)
self._sourceAccessions = []
for i in range(random.randint(1, 3)):
self._sourceAccessions.append("sim_accession_{}".format(
random.randint(1, 2**32)))
self._sourceUri = "http://example.com/reference.fa"
for i in range(numReferences):
referenceSeed = self._randomGenerator.getrandbits(32)
referenceLocalId = "srs{}".format(i)
reference = SimulatedReference(
self, referenceLocalId, referenceSeed)
self.addReference(reference)
class SimulatedReference(AbstractReference):
"""
A simulated reference. Stores a random sequence of a given length, and
generates remaining attributes randomly.
"""
def __init__(self, parentContainer, localId, randomSeed=0, length=200):
super(SimulatedReference, self).__init__(parentContainer, localId)
rng = random.Random()
rng.seed(randomSeed)
self._length = length
bases = [rng.choice('ACGT') for _ in range(self._length)]
self._bases = ''.join(bases)
self._md5checksum = hashlib.md5(self._bases).hexdigest()
self._isDerived = bool(rng.randint(0, 1))
self._sourceDivergence = 0
if self._isDerived:
self._sourceDivergence = rng.uniform(0, 0.1)
self._ncbiTaxonId = random.randint(0, 2**16)
self._sourceAccessions = []
for i in range(random.randint(1, 3)):
self._sourceAccessions.append("sim_accession_{}".format(
random.randint(1, 2**32)))
self._sourceUri = "http://example.com/reference.fa"
def getBases(self, start, end):
self.checkQueryRange(start, end)
return self._bases[start:end]
##################################################################
#
# References based on htslib's FASTA file handling.
#
##################################################################
class HtslibReferenceSet(datamodel.PysamDatamodelMixin, AbstractReferenceSet):
"""
A referenceSet based on data on a file system
"""
def __init__(self, localId, dataDir, backend):
super(HtslibReferenceSet, self).__init__(localId)
self._dataDir = dataDir
self._setMetadata()
self._scanDataFiles(dataDir, ["*.fa.gz"])
def _setMetadata(self):
metadataFileName = '{}.json'.format(self._dataDir)
with open(metadataFileName) as metadataFile:
metadata = json.load(metadataFile)
try:
self._assemblyId = metadata['assemblyId']
self._description = metadata['description']
self._isDerived = metadata['isDerived']
self._ncbiTaxonId = metadata['ncbiTaxonId']
self._sourceAccessions = metadata['sourceAccessions']
self._sourceUri = metadata['sourceUri']
except KeyError as err:
raise exceptions.MissingReferenceSetMetadata(
metadataFileName, str(err))
def _addDataFile(self, path):
dirname, filename = os.path.split(path)
localId = filename.split(".")[0]
metadataFileName = os.path.join(dirname, "{}.json".format(localId))
with open(metadataFileName) as metadataFile:
metadata = json.load(metadataFile)
reference = HtslibReference(self, localId, path, metadata)
self.addReference(reference)
class HtslibReference(datamodel.PysamDatamodelMixin, AbstractReference):
"""
A reference based on data stored in a file on the file system
"""
def __init__(self, parentContainer, localId, dataFile, metadata):
super(HtslibReference, self).__init__(parentContainer, localId)
self._fastaFilePath = dataFile
fastaFile = self.getFileHandle(dataFile)
numReferences = len(fastaFile.references)
if numReferences != 1:
raise exceptions.NotExactlyOneReferenceException(
self._fastaFilePath, numReferences)
if fastaFile.references[0] != localId:
raise exceptions.InconsistentReferenceNameException(
self._fastaFilePath)
self._length = fastaFile.lengths[0]
try:
self._md5checksum = metadata["md5checksum"]
self._sourceUri = metadata["sourceUri"]
self._ncbiTaxonId = metadata["ncbiTaxonId"]
self._isDerived = metadata["isDerived"]
self._sourceDivergence = metadata["sourceDivergence"]
self._sourceAccessions = metadata["sourceAccessions"]
except KeyError as err:
raise exceptions.MissingReferenceMetadata(dataFile, str(err))
def getFastaFilePath(self):
"""
Returns the fasta file that this reference is derived from.
"""
return self._fastaFilePath
def openFile(self, dataFile):
return pysam.FastaFile(dataFile)
def getBases(self, start, end):
self.checkQueryRange(start, end)
fastaFile = self.getFileHandle(self._fastaFilePath)
# TODO we should have some error checking here...
bases = fastaFile.fetch(self.getLocalId(), start, end)
return bases
| diekhans/ga4gh-server | ga4gh/datamodel/references.py | Python | apache-2.0 | 15,873 | 0.000126 |
from concurrency.get_websites import get_number_of_links
import time
# Run get_number_of_links and compare it to a serial version
# stub out load_url with a sleep function so the time is always the same
# Show that the concurrent version takes less time than the serial
import unittest
from unittest.mock import patch, MagicMock
from bs4 import BeautifulSoup
from concurrency.get_websites import get_number_of_links, get_number_of_links_serial
class TestConcurrency(unittest.TestCase):
def setUp(self):
self.loadtime = 1
self.fake_urls = ['url1','url2', 'url3']
@patch('concurrency.get_websites.BeautifulSoup')
@patch('concurrency.get_websites.load_url')
def test_concurrent_slower_than_serial(self, mock_load_url, bs_mock):
""" Time the collection of data from websites """
bs_data = MagicMock(return_value="<html><a href='foo'>Baz</a></html>")
bs_mock.return_value = bs_data
mock_load_url.side_effect = lambda foo: time.sleep(self.loadtime)
concurrent_start = time.time()
list(get_number_of_links(self.fake_urls))
concurrent_total = time.time() - concurrent_start
serial_start = time.time()
get_number_of_links_serial(self.fake_urls)
serial_total = time.time() - serial_start
print("Concurrent collection: {}".format(concurrent_total))
print("Serial collection: {}".format(serial_total))
self.assertLess(concurrent_total, serial_total)
if __name__ == "__main__":
unittest.main() | b-ritter/python-notes | concurrency/tests_integration/test_collection_times.py | Python | mit | 1,528 | 0.003272 |
#!/usr/bin/env python
"""
C to C++ Translator
Convert a C program or whole project to C++
Copyright (C) 2001-2009 Denis Sureau
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., 675 Mass Ave, Cambridge, MA 02139, USA.
webmaster@scriptol.com
http://www.scriptol.com
PMAKE
Compile a list of sources
"""
import os
import string
import sys
# remove unwanted codes from lines
def chop(n):
while (len(n) > 1) & (n[-1] in ("\n", "\r")):
n = n[0:-1]
return n
path = os.getcwd()
# read the list of files
fic = open("cdlist.prj","r")
liste = fic.readlines()
fic.close()
sortie = open("test", "w")
sys.stdout = sortie
# scan the list of sources and compile each .C one
for n in liste:
n = chop(n)
if os.path.isdir(n): continue
node, ext = os.path.splitext(n)
ext = string.upper(ext)
if ext in [ ".c", ".C" ]:
print "compiling " + n,
os.system("bcc32 -c " + node)
sortie.close()
| 2Habibie/ctocpp | c2cpp/pmake.py | Python | gpl-2.0 | 1,606 | 0.009963 |
from django.conf import settings
from django.db.models import Prefetch
from midnight_catalog.models import Product, ParamValue
def get_all(slug=None):
"""
Возвращает QuerySet содержащий выборку товаров
:param slug: символьный код категории каталога, если не задан выбираются товары в не зависимости от категории
:return:
"""
if slug is None:
q = Product.objects.published()
else:
q = Product.objects.published().filter(sections__slug=slug)
if getattr(settings, 'MIDNIGHT_CATALOG_PREFETCH_PARAMS', False):
q = q.prefetch_related(Prefetch("paramvalue_set", queryset=ParamValue.objects.published().order_by('sort').prefetch_related("param")))
q = q.prefetch_related('sections').order_by('sort', '-id')
return q.all()
def get_one(slug):
"""
Возвращает один товар
:param slug: символьный код товара
:return:
"""
item = Product.objects.published()\
.prefetch_related(Prefetch("paramvalue_set", queryset=ParamValue.objects.published().order_by('sort').prefetch_related("param")))\
.filter(slug=slug).first()
return item
| webadmin87/midnight | midnight_catalog/services.py | Python | bsd-3-clause | 1,282 | 0.00266 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 Nicira Networks, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
from neutron.api.v2 import attributes
MAC_LEARNING = 'mac_learning_enabled'
EXTENDED_ATTRIBUTES_2_0 = {
'ports': {
MAC_LEARNING: {'allow_post': True, 'allow_put': True,
'convert_to': attributes.convert_to_boolean,
'default': attributes.ATTR_NOT_SPECIFIED,
'is_visible': True},
}
}
class Maclearning(object):
"""Extension class supporting port mac learning."""
@classmethod
def get_name(cls):
return "MAC Learning"
@classmethod
def get_alias(cls):
return "mac-learning"
@classmethod
def get_description(cls):
return "Provides mac learning capabilities"
@classmethod
def get_namespace(cls):
return "http://docs.openstack.org/ext/maclearning/api/v1.0"
@classmethod
def get_updated(cls):
return "2013-05-1T10:00:00-00:00"
@classmethod
def get_resources(cls):
"""Returns Ext Resources."""
return []
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
| oeeagle/quantum | neutron/plugins/nicira/extensions/maclearning.py | Python | apache-2.0 | 1,838 | 0 |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **GUI Test Cases.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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.
"""
__author__ = 'tim@kartoza.com'
__date__ = '10/01/2011'
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
'Disaster Reduction')
import unittest
import sys
import os
import logging
import codecs
from os.path import join
from unittest import TestCase, skipIf
# this import required to enable PyQt API v2
# noinspection PyUnresolvedReferences
import qgis # pylint: disable=unused-import
from qgis.core import (
QgsVectorLayer,
QgsMapLayerRegistry,
QgsRectangle,
QgsCoordinateReferenceSystem)
from PyQt4 import QtCore
from safe.impact_functions import register_impact_functions
from safe.common.utilities import format_int, unique_filename
from safe.test.utilities import (
test_data_path,
load_standard_layers,
setup_scenario,
set_canvas_crs,
combos_to_string,
populate_dock,
canvas_list,
GEOCRS,
GOOGLECRS,
load_layer,
load_layers,
set_jakarta_extent,
set_jakarta_google_extent,
set_yogya_extent,
get_ui_state,
set_small_jakarta_extent,
get_qgis_app,
TESTDATA,
HAZDATA)
# AG: get_qgis_app() should be called before importing modules from
# safe.gui.widgets.dock
QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()
from safe.gui.widgets.dock import Dock
from safe.utilities.keyword_io import KeywordIO
from safe.utilities.styling import setRasterStyle
from safe.utilities.gis import read_impact_layer, qgis_version
LOGGER = logging.getLogger('InaSAFE')
DOCK = Dock(IFACE)
# noinspection PyArgumentList
class TestDock(TestCase):
"""Test the InaSAFE GUI."""
def setUp(self):
"""Fixture run before all tests"""
register_impact_functions()
DOCK.show_only_visible_layers_flag = True
load_standard_layers(DOCK)
DOCK.cboHazard.setCurrentIndex(0)
DOCK.cboExposure.setCurrentIndex(0)
DOCK.cboFunction.setCurrentIndex(0)
DOCK.run_in_thread_flag = False
DOCK.show_only_visible_layers_flag = False
DOCK.set_layer_from_title_flag = False
DOCK.zoom_to_impact_flag = False
DOCK.hide_exposure_flag = False
DOCK.show_intermediate_layers = False
DOCK.user_extent = None
DOCK.user_extent_crs = None
def tearDown(self):
"""Fixture run after each test"""
QgsMapLayerRegistry.instance().removeAllMapLayers()
DOCK.cboHazard.clear()
DOCK.cboExposure.clear()
# DOCK.cboAggregation.clear() #dont do this because the cboAggregation
# need to be able to react to the status changes of the other combos
def test_defaults(self):
"""Test the GUI in its default state"""
print combos_to_string(DOCK)
self.assertEqual(DOCK.cboHazard.currentIndex(), 0)
self.assertEqual(DOCK.cboExposure.currentIndex(), 0)
self.assertEqual(DOCK.cboFunction.currentIndex(), 0)
self.assertEqual(DOCK.cboAggregation.currentIndex(), 0)
def test_validate(self):
"""Validate function work as expected"""
self.tearDown()
# First check that we DONT validate a clear DOCK
flag, message = DOCK.validate()
self.assertTrue(message is not None, 'No reason for failure given')
message = 'Validation expected to fail on a cleared DOCK.'
self.assertEquals(flag, False, message)
# Now check we DO validate a populated DOCK
populate_dock(DOCK)
flag = DOCK.validate()
message = (
'Validation expected to pass on a populated dock with selections.')
self.assertTrue(flag, message)
def test_set_ok_button_status(self):
"""OK button changes properly according to DOCK validity"""
# First check that we ok ISNT enabled on a clear DOCK
self.tearDown()
flag, message = DOCK.validate()
self.assertTrue(message is not None, 'No reason for failure given')
message = 'Validation expected to fail on a cleared DOCK.'
self.assertEquals(flag, False, message)
# Now check OK IS enabled on a populated DOCK
populate_dock(DOCK)
flag = DOCK.validate()
message = (
'Validation expected to pass on a populated DOCK with selections.')
self.assertTrue(flag, message)
def test_insufficient_overlap(self):
"""Test Insufficient overlap errors are caught.
..note:: See https://github.com/AIFDR/inasafe/issues/372
"""
# Push OK with the left mouse button
button = DOCK.pbnRunStop
message = 'Run button was not enabled'
self.assertTrue(button.isEnabled(), message)
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction')
self.assertTrue(result, message)
# Enable on-the-fly reprojection
set_canvas_crs(GEOCRS, True)
# Zoom to an area where there is no overlap with layers
rectangle = QgsRectangle(
106.635434302702, -6.101567666986,
106.635434302817, -6.101567666888)
CANVAS.setExtent(rectangle)
crs = QgsCoordinateReferenceSystem('EPSG:4326')
DOCK.define_user_analysis_extent(rectangle, crs)
# Press RUN
DOCK.accept()
result = DOCK.wvResults.page_to_text()
# Check for an error containing InsufficientOverlapError
expected_string = 'InsufficientOverlapError'
message = 'Result not as expected %s not in: %s' % (
expected_string, result)
# This is the expected impact number
self.assertIn(expected_string, result, message)
# disabled this test until further coding
def xtest_print_map(self):
"""Test print map, especially on Windows."""
result, message = setup_scenario(
DOCK,
hazard='Flood in Jakarta',
exposure='Essential buildings',
function='Be affected',
function_id='Categorised Hazard Building Impact Function')
self.assertTrue(result, message)
# Enable on-the-fly reprojection
set_canvas_crs(GEOCRS, True)
set_jakarta_extent(DOCK)
# Press RUN
button = DOCK.pbnRunStop
# noinspection PyCallByClass,PyTypeChecker
button.click()
print_button = DOCK.pbnPrint
try:
# noinspection PyCallByClass,PyTypeChecker
print_button.click()
except OSError:
LOGGER.debug('OSError')
# pass
except Exception, e:
raise Exception('Exception is not expected, %s' % e)
def test_result_styling(self):
"""Test that ouputs from a model are correctly styled (colours and
opacity. """
# Push OK with the left mouse button
print '--------------------'
print combos_to_string(DOCK)
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction')
self.assertTrue(result, message)
# Enable on-the-fly reprojection
set_canvas_crs(GEOCRS, True)
set_jakarta_extent(DOCK)
DOCK.accept()
# DOCK.analysis.get_impact_layer()
safe_layer = DOCK.analysis.get_impact_layer()
qgis_layer = read_impact_layer(safe_layer)
style = safe_layer.get_style_info()
setRasterStyle(qgis_layer, style)
# simple test for now - we could test explicity for style state
# later if needed.
message = (
'Raster layer was not assigned a Singleband pseudocolor'
' renderer as expected.')
self.assertTrue(
qgis_layer.renderer().type() == 'singlebandpseudocolor', message)
# Commenting out because we changed impact function to use floating
# point quantities. Revisit in QGIS 2.0 where range based transparency
# will have been implemented
# message = ('Raster layer was not assigned transparency'
# 'classes as expected.')
# myTransparencyList = (qgis_layer.rasterTransparency().
# transparentSingleValuePixelList())
# print "Transparency list:" + str(myTransparencyList)
# assert (len(myTransparencyList) > 0)
def test_issue47(self):
"""Issue47: Hazard & exposure data are in different proj to viewport.
See https://github.com/AIFDR/inasafe/issues/47"""
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction')
self.assertTrue(result, message)
# Enable on-the-fly reprojection
set_canvas_crs(GOOGLECRS, True)
set_jakarta_google_extent(DOCK)
# Press RUN
DOCK.accept()
result = DOCK.wvResults.page_to_text()
message = 'Result not as expected: %s' % result
# searching for values 6700 clean water [l] in result
self.assertTrue(format_int(6700) in result, message)
def test_issue306(self):
"""Issue306: CANVAS doesnt add generated layers in tests.
See https://github.com/AIFDR/inasafe/issues/306"""
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction')
self.assertTrue(result, message)
LOGGER.info("Canvas list before:\n%s" % canvas_list())
# Enable on-the-fly reprojection
set_canvas_crs(GOOGLECRS, True)
set_jakarta_google_extent(DOCK)
before_count = len(CANVAS.layers())
# print 'Before count %s' % before_count
# Press RUN
DOCK.accept()
# test issue #306
after_count = len(CANVAS.layers())
LOGGER.info("Canvas list after:\n%s" % canvas_list())
message = ('Layer was not added to canvas (%s before, %s after)' % (
before_count, after_count))
# print 'After count %s' % after_count
self.assertTrue(before_count == after_count - 1, message)
def test_load_layers(self):
"""Layers can be loaded and list widget was updated appropriately
"""
hazard_layer_count, exposure_layer_count = load_standard_layers()
message = 'Expect %s layer(s) in hazard list widget but got %s' % (
hazard_layer_count, DOCK.cboHazard.count())
# pylint: disable=W0106
self.assertEqual(DOCK.cboHazard.count(),
hazard_layer_count), message
message = 'Expect %s layer(s) in exposure list widget but got %s' % (
exposure_layer_count, DOCK.cboExposure.count())
self.assertEqual(DOCK.cboExposure.count(),
exposure_layer_count), message
# pylint: disable=W0106
def test_issue71(self):
"""Test issue #71 in github - cbo changes should update ok button."""
# See https://github.com/AIFDR/inasafe/issues/71
# Push OK with the left mouse button
print 'Using QGIS: %s' % qgis_version()
self.tearDown()
button = DOCK.pbnRunStop
# First part of scenario should have enabled run
file_list = [
join(HAZDATA, 'Flood_Current_Depth_Jakarta_geographic.asc'),
join(TESTDATA, 'Population_Jakarta_geographic.asc')]
hazard_layer_count, exposure_layer_count = load_layers(file_list)
message = (
'Incorrect number of Hazard layers: expected 1 got %s'
% hazard_layer_count)
self.assertTrue(hazard_layer_count == 1, message)
message = (
'Incorrect number of Exposure layers: expected 1 got %s'
% exposure_layer_count)
self.assertTrue(exposure_layer_count == 1, message)
message = 'Run button was not enabled'
self.assertTrue(button.isEnabled(), message)
# Second part of scenario - run disabled when adding invalid layer
# and select it - run should be disabled
path = os.path.join(TESTDATA, 'issue71.tif')
file_list = [path] # This layer has incorrect keywords
clear_flag = False
_, _ = load_layers(file_list, clear_flag)
# set exposure to : Population Count (5kmx5km)
# by moving one down
DOCK.cboExposure.setCurrentIndex(DOCK.cboExposure.currentIndex() + 1)
actual_dict = get_ui_state(DOCK)
expected_dict = {
'Run Button Enabled': False,
'Impact Function Id': '',
'Impact Function Title': '',
'Hazard': 'A flood in Jakarta like in 2007',
'Exposure': 'Population Count (5kmx5km)'}
message = ((
'Run button was not disabled when exposure set to \n%s'
'\nUI State: \n%s\nExpected State:\n%s\n%s') % (
DOCK.cboExposure.currentText(),
actual_dict,
expected_dict,
combos_to_string(DOCK)))
self.assertTrue(expected_dict == actual_dict, message)
# Now select again a valid layer and the run button
# should be enabled
DOCK.cboExposure.setCurrentIndex(DOCK.cboExposure.currentIndex() - 1)
message = (
'Run button was not enabled when exposure set to \n%s' %
DOCK.cboExposure.currentText())
self.assertTrue(button.isEnabled(), message)
def test_issue160(self):
"""Test that multipart features can be used in a scenario - issue #160
"""
exposure = test_data_path('exposure', 'buildings.shp')
hazard = test_data_path('hazard', 'flood_multipart_polygons.shp')
# See https://github.com/AIFDR/inasafe/issues/71
# Push OK with the left mouse button
# print 'Using QGIS: %s' % qgis_version()
self.tearDown()
button = DOCK.pbnRunStop
# First part of scenario should have enabled run
file_list = [hazard, exposure]
hazard_layer_count, exposure_layer_count = load_layers(file_list)
message = (
'Incorrect number of Hazard layers: expected 1 got %s'
% hazard_layer_count)
self.assertTrue(hazard_layer_count == 1, message)
message = (
'Incorrect number of Exposure layers: expected 1 got %s'
% exposure_layer_count)
self.assertTrue(exposure_layer_count == 1, message)
message = 'Run button was not enabled'
self.assertTrue(button.isEnabled(), message)
# Second part of scenario - run disabled when adding invalid layer
# and select it - run should be disabled
path = os.path.join(TESTDATA, 'issue71.tif')
file_list = [path] # This layer has incorrect keywords
clear_flag = False
_, _ = load_layers(file_list, clear_flag)
result, message = setup_scenario(
DOCK,
hazard='Flood Polygon',
exposure='Buildings',
function='Be flooded',
function_id='FloodPolygonBuildingFunction')
self.assertTrue(result, message)
# Enable on-the-fly reprojection
set_canvas_crs(GEOCRS, True)
expected_extent = QgsRectangle(
106.80801, -6.19531, 106.83456946836641, -6.167526)
CANVAS.setExtent(expected_extent)
crs = QgsCoordinateReferenceSystem('EPSG:4326')
DOCK.define_user_analysis_extent(expected_extent, crs)
# Press RUN
# noinspection PyCallByClass,PyCallByClass,PyTypeChecker
DOCK.accept()
result = DOCK.wvResults.page_to_text()
message = 'Result not as expected: %s' % result
self.assertTrue(format_int(33) in result, message)
def test_issue581(self):
"""Test issue #581 in github - Humanize can produce IndexError : list
index out of range
"""
# See https://github.com/AIFDR/inasafe/issues/581
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction')
self.assertTrue(result, message)
# Enable on-the-fly reprojection
set_canvas_crs(GEOCRS, True)
set_small_jakarta_extent(DOCK)
# Press RUN
DOCK.accept()
result = DOCK.wvResults.page().currentFrame().toPlainText()
message = 'Result not as expected: %s' % result
self.assertTrue('IndexError' not in result, message)
self.assertTrue(
'It appears that no Population are affected by Continuous Flood.'
' You may want to consider:' in result, message)
def test_state(self):
"""Check if the save/restore state methods work. See also
https://github.com/AIFDR/inasafe/issues/58
"""
# default selected layer is the third layer exposure
# so, decrease the index by one to change it
DOCK.cboExposure.setCurrentIndex(DOCK.cboExposure.currentIndex() - 1)
DOCK.save_state()
expected_dict = get_ui_state(DOCK)
# myState = DOCK.state
# Now reset and restore and check that it gets the old state
# Html is not considered in restore test since the ready
# message overwrites it in dock implementation
DOCK.cboExposure.setCurrentIndex(DOCK.cboExposure.currentIndex() - 1)
DOCK.restore_state()
result_dict = get_ui_state(DOCK)
message = 'Got unexpected state: %s\nExpected: %s\n%s' % (
result_dict, expected_dict, combos_to_string(DOCK))
self.assertTrue(expected_dict == result_dict, message)
# Corner case test when two layers can have the
# same functions - when switching layers the selected function should
# remain unchanged
self.tearDown()
file_list = [
test_data_path('hazard', 'jakarta_flood_design.tif'),
test_data_path('hazard', 'continuous_flood_20_20.asc'),
test_data_path('exposure', 'pop_binary_raster_20_20.asc')
]
hazard_layer_count, exposure_layer_count = load_layers(file_list)
message = 'Expecting 2 hazard layers, got %s' % hazard_layer_count
self.assertTrue(hazard_layer_count == 2, message)
message = 'Expecting 1 exposure layer, got %s' % exposure_layer_count
self.assertTrue(exposure_layer_count == 1, message)
# we will have 2 impact function available right now:
# - ContinuousHazardPopulationFunction, titled: 'Be impacted'
# - FloodEvacuationRasterHazardFunction, titled: 'Need evacuation'
# set it to the second for testing purposes
DOCK.cboFunction.setCurrentIndex(1)
DOCK.cboHazard.setCurrentIndex(0)
DOCK.cboExposure.setCurrentIndex(0)
expected_function = str(DOCK.cboFunction.currentText())
# Now move down one hazard in the combo then verify
# the function remains unchanged
DOCK.cboHazard.setCurrentIndex(1)
current_function = str(DOCK.cboFunction.currentText())
message = (
'Expected selected impact function to remain unchanged when '
'choosing a different hazard of the same category:'
' %s\nExpected: %s\n%s' % (
expected_function, current_function, combos_to_string(DOCK)))
self.assertTrue(expected_function == current_function, message)
DOCK.cboHazard.setCurrentIndex(0)
# Selected function should remain the same
# RM: modified it, because there is generic one right now as the first.
# the selected one should be FloodEvacuationRasterHazardFunction
DOCK.cboFunction.setCurrentIndex(1)
expected = 'Need evacuation'
function = DOCK.cboFunction.currentText()
message = 'Expected: %s, Got: %s' % (expected, function)
self.assertTrue(function == expected, message)
def test_full_run_pyzstats(self):
"""Aggregation results correct using our own python zonal stats code.
"""
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction',
aggregation_layer=u'D\xedstr\xedct\'s of Jakarta',
aggregation_enabled_flag=True)
self.assertTrue(result, message)
# Enable on-the-fly reprojection
set_canvas_crs(GEOCRS, True)
set_jakarta_extent(DOCK)
# Press RUN
# noinspection PyCallByClass,PyTypeChecker
DOCK.accept()
result = DOCK.wvResults.page_to_text()
control_file_path = test_data_path(
'control',
'files',
'test-full-run-results.txt')
expected_result = codecs.open(
control_file_path,
mode='r',
encoding='utf-8').readlines()
result = result.replace(
'</td> <td>', ' ').replace('</td><td>', ' ')
for line in expected_result:
line = line.replace('\n', '')
self.assertIn(line, result)
@skipIf(sys.platform == 'win32', "Test cannot run on Windows")
def test_full_run_qgszstats(self):
"""Aggregation results are correct using native QGIS zonal stats.
.. note:: We know this is going to fail (hence the decorator) as
QGIS1.8 zonal stats are broken. We expect this to pass when we
have ported to the QGIS 2.0 api at which time we can remove the
decorator. TS July 2013
"""
# TODO check that the values are similar enough to the python stats
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction',
aggregation_layer=u'D\xedstr\xedct\'s of Jakarta',
aggregation_enabled_flag=True)
self.assertTrue(result, message)
# Enable on-the-fly reprojection
set_canvas_crs(GEOCRS, True)
set_jakarta_extent(DOCK)
# Press RUN
# noinspection PyCallByClass,PyTypeChecker
# use QGIS zonal stats only in the test
qgis_zonal_flag = bool(QtCore.QSettings().value(
'inasafe/use_native_zonal_stats', False, type=bool))
QtCore.QSettings().setValue('inasafe/use_native_zonal_stats', True)
DOCK.accept()
QtCore.QSettings().setValue('inasafe/use_native_zonal_stats',
qgis_zonal_flag)
result = DOCK.wvResults.page_to_text()
control_file_path = test_data_path(
'control',
'files',
'test-full-run-results-qgis.txt')
expected_result = codecs.open(
control_file_path,
mode='r',
encoding='utf-8').readlines()
result = result.replace(
'</td> <td>', ' ').replace('</td><td>', ' ')
for line in expected_result:
line = line.replace('\n', '')
self.assertIn(line, result)
def test_layer_changed(self):
"""Test the metadata is updated as the user highlights different
QGIS layers. For inasafe outputs, the table of results should be shown
See also
https://github.com/AIFDR/inasafe/issues/58
"""
layer_path = os.path.join(TESTDATA, 'issue58.tif')
layer, layer_type = load_layer(layer_path)
message = (
'Unexpected category for issue58.tif.\nGot:'
' %s\nExpected: undefined' % layer_type)
self.assertTrue(layer_type == 'undefined', message)
DOCK.layer_changed(layer)
DOCK.save_state()
html = DOCK.state['report']
expected = '4229'
message = "%s\nDoes not contain:\n%s" % (
html,
expected)
self.assertTrue(expected in html, message)
def test_layer_saved_as_with_keywords_and_xml(self):
"""Check that auxiliary files are well copied when they exist and the
'saved as' is used.
"""
layer_path = os.path.join(TESTDATA, 'tsunami_building_assessment.shp')
# pylint: disable=unused-variable
layer, layer_type = load_layer(layer_path)
# pylint: enable=unused-variable
new_name = unique_filename(
prefix='tsunami_building_assessment_saved_as_')
DOCK.save_auxiliary_files(
layer, join(TESTDATA, '%s.shp' % new_name))
new_keywords_filepath = os.path.join(
TESTDATA, '%s.keywords' % new_name)
new_xml_filepath = os.path.join(TESTDATA, '%s.xml' % new_name)
message = 'New auxiliary file does not exist : '
self.assertTrue(
os.path.isfile(new_keywords_filepath), '%s keywords' % message)
self.assertTrue(os.path.isfile(new_xml_filepath), '%s xml' % message)
def test_layer_saved_as_without_keywords_and_xml(self):
"""Check that auxiliary files aren't created when they don't exist and
the 'saved as' is used.
"""
layer_path = os.path.join(TESTDATA, 'kecamatan_jakarta_osm.shp')
# pylint: disable=unused-variable
layer, layer_type = load_layer(layer_path)
# pylint: enable=unused-variable
new_name = unique_filename(prefix='kecamatan_jakarta_osm_saved_as')
DOCK.save_auxiliary_files(
layer, join(TESTDATA, '%s.shp' % new_name))
new_keywords_file_path = os.path.join(
TESTDATA, '%s.keywords' % new_name)
new_xml_file_path = os.path.join(TESTDATA, '%s.xml' % new_name)
message = 'New auxiliary file exist : '
self.assertFalse(
os.path.isfile(new_keywords_file_path), '%s keywords' % message)
self.assertFalse(os.path.isfile(new_xml_file_path), '%s xml' % message)
def test_new_layers_show_in_canvas(self):
"""Check that when we add a layer we can see it in the canvas list."""
LOGGER.info("Canvas list before:\n%s" % canvas_list())
before_count = len(CANVAS.layers())
layer_path = join(TESTDATA, 'polygon_0.shp')
layer = QgsVectorLayer(layer_path, 'foo', 'ogr')
QgsMapLayerRegistry.instance().addMapLayers([layer])
after_count = len(CANVAS.layers())
LOGGER.info("Canvas list after:\n%s" % canvas_list())
message = (
'Layer was not added to canvas (%s before, %s after)' %
(before_count, after_count))
self.assertTrue(before_count == after_count - 1, message)
QgsMapLayerRegistry.instance().removeMapLayer(layer.id())
def test_issue317(self):
"""Points near the edge of a raster hazard layer are interpolated OK"""
set_canvas_crs(GEOCRS, True)
set_jakarta_extent(DOCK)
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Buildings',
function='Be flooded',
function_id='FloodRasterBuildingFunction')
DOCK.get_functions()
self.assertTrue(result, message)
def test_has_parameters_button_disabled(self):
"""Function configuration button is disabled when layers not
compatible."""
set_canvas_crs(GEOCRS, True)
setup_scenario(
DOCK,
hazard='Earthquake',
exposure='Roads',
function='',
function_id='')
tool_button = DOCK.toolFunctionOptions
flag = tool_button.isEnabled()
self.assertTrue(
not flag,
'Expected configuration options button to be disabled')
def test_has_parameters_button_enabled(self):
"""Function configuration button is enabled when layers are compatible.
"""
set_canvas_crs(GEOCRS, True)
set_jakarta_extent(DOCK)
setup_scenario(
DOCK,
hazard='A flood in Jakarta like in 2007',
exposure='Penduduk Jakarta',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction')
tool_button = DOCK.toolFunctionOptions
flag = tool_button.isEnabled()
self.assertTrue(
flag,
'Expected configuration options button to be enabled')
# I disabled the test for now as checkMemory now returns None unless
# there is a problem. TS
def xtest_extents_changed(self):
"""Memory requirements are calculated correctly when extents change.
"""
set_canvas_crs(GEOCRS, True)
set_jakarta_extent(DOCK)
setup_scenario(
DOCK,
hazard='A flood in Jakarta like in 2007',
exposure='Penduduk Jakarta',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction')
result = DOCK.checkMemoryUsage()
message = 'Expected "3mb" to apear in : %s' % result
self.assertTrue(result is not None, 'Check memory reported None')
self.assertTrue('3mb' in result, message)
def test_cbo_aggregation_empty_project(self):
"""Aggregation combo changes properly according on no loaded layers"""
self.tearDown()
message = (
'The aggregation combobox should have only the "Entire '
'area" item when the project has no layer. Found:'
' %s' % (DOCK.cboAggregation.currentText()))
self.assertEqual(DOCK.cboAggregation.currentText(), DOCK.tr(
'Entire area'), message)
message = (
'The aggregation combobox should be disabled when the '
'project has no layer.')
self.assertTrue(not DOCK.cboAggregation.isEnabled(), message)
def test_cbo_aggregation_toggle(self):
"""Aggregation Combobox toggles on and off as expected."""
# With aggregation layer
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction',
aggregation_layer=u'D\xedstr\xedct\'s of Jakarta',
aggregation_enabled_flag=True)
message += ' when an aggregation layer is defined.'
self.assertTrue(result, message)
# With no aggregation layer
layer = DOCK.get_aggregation_layer()
layer_id = layer.id()
QgsMapLayerRegistry.instance().removeMapLayer(layer_id)
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction',
aggregation_enabled_flag=False)
message += ' when no aggregation layer is defined.'
self.assertTrue(result, message)
def test_set_dock_title(self):
"""Test the dock title gets set properly."""
DOCK.set_dock_title()
self.assertIn('InaSAFE', str(DOCK.windowTitle()))
def wkt_to_coordinates(self, wkt):
"""Convert a wkt into a nested array of float pairs."""
expected_coords = []
wkt = wkt.replace('LINESTRING(', '').replace(')', '')
coords = wkt.split(',')
for item in coords:
item = item.strip()
tokens = item.split(' ')
# print tokens[0].strip()
# print tokens[1].strip()
expected_coords.append([
float(tokens[0].strip()),
float(tokens[1].strip())])
return expected_coords
def test_rubber_bands(self):
"""Test that the rubber bands get updated."""
setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction',
aggregation_layer=u'D\xedstr\xedct\'s of Jakarta',
aggregation_enabled_flag=True)
DOCK.extent.show_rubber_bands = True
expected_vertex_count = 5
# 4326 with enabled on-the-fly reprojection - check next
set_canvas_crs(GEOCRS, True)
set_small_jakarta_extent(DOCK)
DOCK.show_next_analysis_extent()
next_band = DOCK.extent.next_analysis_rubberband
self.assertEqual(expected_vertex_count, next_band.numberOfVertices())
# 4326 with disabled on-the-fly reprojection - check next
set_canvas_crs(GEOCRS, False)
set_small_jakarta_extent(DOCK)
DOCK.show_next_analysis_extent()
next_band = DOCK.extent.next_analysis_rubberband
self.assertEqual(expected_vertex_count, next_band.numberOfVertices())
# 900913 with enabled on-the-fly reprojection - check next
set_canvas_crs(GOOGLECRS, True)
set_jakarta_google_extent(DOCK)
next_band = DOCK.extent.next_analysis_rubberband
self.assertEqual(expected_vertex_count, next_band.numberOfVertices())
# 900913 with enabled on-the-fly reprojection - check last
set_canvas_crs(GOOGLECRS, True)
set_jakarta_google_extent(DOCK)
# Press RUN
# noinspection PyCallByClass,PyTypeChecker
DOCK.accept()
# DOCK.show_extent()
last_band = DOCK.extent.last_analysis_rubberband
geometry = last_band.asGeometry().exportToWkt()
expected = (
'LINESTRING(11889533.87392097897827625 -691251.80866545776370913, '
'11893986.65355271473526955 -691251.80866545776370913, '
'11893986.65355271473526955 -686773.02196401008404791, '
'11889533.87392097897827625 -686773.02196401008404791, '
'11889533.87392097897827625 -691251.80866545776370913)')
expected_list = self.wkt_to_coordinates(expected)
actual_list = self.wkt_to_coordinates(geometry)
for item in xrange(0, len(expected_list)):
print item, expected_list[item], actual_list[item]
self.assertAlmostEqual(
expected_list[item][0],
actual_list[item][0])
self.assertAlmostEqual(
expected_list[item][1],
actual_list[item][1])
self.assertEqual(
expected_vertex_count,
last_band.numberOfVertices()
)
def test_user_defined_extent(self):
"""Test that analysis honours user defined extents.
Note that when testing on a desktop system this will overwrite your
user defined analysis extent.
"""
settings = QtCore.QSettings()
extents = '106.772279, -6.237576, 106.885165, -6.165415'
settings.setValue('inasafe/analysis_extent', extents)
settings.setValue('inasafe/analysis_extent_crs', 'EPSG:4326')
DOCK.read_settings()
setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
function='Need evacuation',
function_id='FloodEvacuationRasterHazardFunction',
aggregation_layer=u'D\xedstr\xedct\'s of Jakarta',
aggregation_enabled_flag=True)
DOCK.extent.show_rubber_bands = True
expected_vertex_count = 2
# 4326 with disabled on-the-fly reprojection
set_canvas_crs(GEOCRS, True)
# User extent should override this
set_small_jakarta_extent(DOCK)
DOCK.extent.show_user_analysis_extent()
user_band = DOCK.extent.user_analysis_rubberband
self.assertEqual(expected_vertex_count, user_band.numberOfVertices())
def test_issue1191(self):
"""Test setting a layer's title in the kw directly from qgis api"""
DOCK.set_layer_from_title_flag = True
set_canvas_crs(GEOCRS, True)
set_yogya_extent(DOCK)
result, message = setup_scenario(
DOCK,
hazard='Earthquake',
exposure='Buildings',
function='Be affected',
function_id='EarthquakeBuildingFunction')
self.assertTrue(result, message)
layer = DOCK.get_hazard_layer()
keyword_io = KeywordIO()
original_title = 'Earthquake'
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
# change layer name as if done in the legend
expected_title = 'TEST'
layer.setLayerName(expected_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, expected_title)
# reset KW file to original state
layer.setLayerName(original_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
DOCK.set_layer_from_title_flag = False
if __name__ == '__main__':
suite = unittest.makeSuite(TestDock)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
| Jannes123/inasafe | safe/gui/widgets/test/test_dock.py | Python | gpl-3.0 | 37,784 | 0.000106 |
import os
from multiprocessing import cpu_count
_cpu_count = cpu_count()
if hasattr(os, 'getloadavg'):
def load_fair():
return 'load', os.getloadavg()[0] / _cpu_count
else:
from winperfmon import PerformanceCounter
from threading import Thread
from collections import deque
from time import sleep
class SystemLoadThread(Thread):
def __init__(self):
super(SystemLoadThread, self).__init__()
self.daemon = True
self.samples = deque(maxlen=10)
self.load = 0.5
self.counter = PerformanceCounter(r'\System\Processor Queue Length', r'\Processor(_Total)\% Processor Time')
def run(self):
while True:
pql, pt = self.counter.query()
self.samples.append(pql)
if pt >= 100:
self.load = max(sum(self.samples) / len(self.samples) / _cpu_count, pt / 100.)
else:
self.load = pt / 100.
sleep(1)
_load_thread = SystemLoadThread()
_load_thread.start()
def load_fair():
return 'load', _load_thread.load
def cpu_count():
return 'cpu-count', _cpu_count
report_callbacks = [load_fair, cpu_count]
| buhe/judge | sysinfo.py | Python | agpl-3.0 | 1,249 | 0.001601 |
from django.contrib import admin
# Register your models here.
from polls.models import Question,Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fields = ["question_text", "pub_date"]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
search_fields = ['question_text']
list_filter = ['pub_date']
admin.site.register(Question, QuestionAdmin)
| Tassemble/jewelry | polls/admin.py | Python | mit | 475 | 0.023158 |
from people.models import Person
from optparse import make_option
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
raise ImportError("Neither json or simplejson are available on your system")
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
class Command(BaseCommand):
args = 'NAME'
help = 'Export speakers from the database'
option_list = BaseCommand.option_list + (
make_option('--staff',
action='store_true',
dest='staff',
default=False,
help='This person is staff'),
)
def handle(self, *args, **options):
name = u" ".join(map(lambda s: s.decode("utf8"),args))
print options
person = Person(name=name, staff=options['staff'])
person.save()
print person.pk
| gdetrez/MyConf | apps/people/management/commands/addperson.py | Python | agpl-3.0 | 933 | 0.004287 |
#!/usr/bin/env pythonw
#from __future__ import print_function
import sys
import wx
import os
import matplotlib
if matplotlib.get_backend() != "WXAgg":
matplotlib.use("WXAgg")
import matplotlib.pyplot as plt
from pmagpy import pmagplotlib
import pmagpy.command_line_extractor as extractor
import pmagpy.ipmag as ipmag
import dialogs.pmag_widgets as pw
import dialogs.pmag_menu_dialogs as pmag_menu_dialogs
def main():
"""
NAME
core_depthplot.py
DESCRIPTION
plots various measurements versus core_depth or age. plots data flagged as 'FS-SS-C' as discrete samples.
SYNTAX
core_depthplot.py [command line options]
# or, for Anaconda users:
core_depthplot_anaconda [command line options]
OPTIONS
-h prints help message and quits
-f FILE: specify input measurments format file
-fsum FILE: specify input LIMS database (IODP) core summary csv file
-fwig FILE: specify input depth,wiggle to plot, in magic format with sample_core_depth key for depth
-fsa FILE: specify input er_samples format file from magic for depth
-fa FILE: specify input ages format file from magic for age
NB: must have either -fsa OR -fa (not both)
-fsp FILE sym size: specify input zeq_specimen format file from magic, sym and size
NB: PCAs will have specified color, while fisher means will be white with specified color as the edgecolor
-fres FILE specify input pmag_results file from magic, sym and size
-LP [AF,T,ARM,IRM, X] step [in mT,C,mT,mT, mass/vol] to plot
-S do not plot blanket treatment data (if this is set, you don't need the -LP)
-sym SYM SIZE, symbol, size for continuous points (e.g., ro 5, bs 10, g^ 10 for red dot, blue square, green triangle), default is blue dot at 5 pt
-D do not plot declination
-M do not plot magnetization
-log plot magnetization on a log scale
-L do not connect dots with a line
-I do not plot inclination
-d min max [in m] depth range to plot
-n normalize by weight in er_specimen table
-Iex: plot the expected inc at lat - only available for results with lat info in file
-ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma)
TS: [ck95, gts04, gts12]
-ds [mbsf,mcd] specify depth scale, mbsf default
-fmt [svg, eps, pdf, png] specify output format for plot (default: svg)
-sav save plot silently
DEFAULTS:
Measurements file: measurements.txt
Samples file: samples.txt
NRM step
Summary file: none
"""
args = sys.argv
if '-h' in args:
print(main.__doc__)
sys.exit()
dataframe = extractor.command_line_dataframe([ ['f', False, 'measurements.txt'], ['fsum', False, ''],
['fwig', False, ''], ['fsa', False, ''],
['fa', False, ''], ['fsp', False, ''],
['fres', False, '' ], ['fmt', False, 'svg'],
['LP', False, ''], ['n', False, False],
['d', False, '-1 -1'], ['ts', False, ''],
['WD', False, '.'], ['L', False, True],
['S', False, True], ['D', False, True],
['I', False, True], ['M', False, True],
['log', False, 0],
['ds', False, 'sample_core_depth'],
['sym', False, 'bo 5'], ['ID', False, '.'],
['sav', False, False], ['DM', False, 3]])
checked_args = extractor.extract_and_check_args(args, dataframe)
meas_file, sum_file, wig_file, samp_file, age_file, spc_file, res_file, fmt, meth, norm, depth, timescale, dir_path, pltLine, pltSus, pltDec, pltInc, pltMag, logit, depth_scale, symbol, input_dir, save, data_model_num = extractor.get_vars(
['f', 'fsum', 'fwig', 'fsa', 'fa', 'fsp', 'fres', 'fmt', 'LP', 'n', 'd', 'ts', 'WD', 'L', 'S', 'D', 'I', 'M', 'log', 'ds', 'sym', 'ID', 'sav', 'DM'], checked_args)
# format some variables
# format symbol/size
try:
sym, size = symbol.split()
size = int(size)
except:
print('you should provide -sym in this format: ro 5')
print('using defaults instead')
sym, size = 'ro', 5
# format result file, symbol, size
if res_file:
try:
res_file, res_sym, res_size = res_file.split()
except:
print('you must provide -fres in this format: -fres filename symbol size')
print(
'could not parse {}, defaulting to using no result file'.format(res_file))
res_file, res_sym, res_size = '', '', 0
else:
res_file, res_sym, res_size = '', '', 0
# format specimen file, symbol, size
if spc_file:
try:
spc_file, spc_sym, spc_size = spc_file.split()
except:
print('you must provide -fsp in this format: -fsp filename symbol size')
print(
'could not parse {}, defaulting to using no specimen file'.format(spc_file))
spc_file, spc_sym, spc_size = '', '', 0
else:
spc_file, spc_sym, spc_size = '', '', 0
# format min/max depth
try:
dmin, dmax = depth.split()
except:
print('you must provide -d in this format: -d dmin dmax')
print('could not parse {}, defaulting to plotting all depths'.format(depth))
dmin, dmax = -1, -1
# format timescale, min/max time
if timescale:
try:
timescale, amin, amax = timescale.split()
pltTime = True
except:
print(
'you must provide -ts in this format: -ts timescale minimum_age maximum_age')
print(
'could not parse {}, defaulting to using no timescale'.format(timescale))
timescale, amin, amax = None, -1, -1
pltTime = False
else:
timescale, amin, amax = None, -1, -1
pltTime = False
# format norm and wt_file
if norm and not isinstance(norm, bool):
wt_file = norm
norm = True
else:
norm = False
wt_file = ''
# format list of protcols and step
try:
method, step = meth.split()
except:
print(
'To use the -LP flag you must provide both the protocol and the step in this format:\n-LP [AF,T,ARM,IRM, X] step [in mT,C,mT,mT, mass/vol] to plot')
print('Defaulting to using no protocol')
method, step = 'LT-NO', 0
# list of varnames
#['f', 'fsum', 'fwig', 'fsa', 'fa', 'fsp', 'fres', 'fmt', 'LP', 'n', 'd', 'ts', 'WD', 'L', 'S', 'D', 'I', 'M', 'log', 'ds', 'sym' ]
#meas_file, sum_file, wig_file, samp_file, age_file, spc_file, res_file, fmt, meth, norm, depth, timescale, dir_path, pltLine, pltSus, pltDec, pltInc, pltMag, logit, depth_scale, symbol
fig, figname = ipmag.core_depthplot(input_dir, meas_file, spc_file, samp_file, age_file, sum_file, wt_file, depth_scale, dmin, dmax, sym, size,
spc_sym, spc_size, method, step, fmt, pltDec, pltInc, pltMag, pltLine, pltSus, logit, pltTime, timescale, amin, amax, norm, data_model_num)
if not pmagplotlib.isServer:
figname = figname.replace(':', '_')
if fig and save:
print('-I- Created plot: {}'.format(figname))
plt.savefig(figname)
return
app = wx.App(redirect=False)
if not fig:
pw.simple_warning(
'No plot was able to be created with the data you provided.\nMake sure you have given all the required information and try again')
return False
dpi = fig.get_dpi()
pixel_width = dpi * fig.get_figwidth()
pixel_height = dpi * fig.get_figheight()
figname = os.path.join(dir_path, figname)
plot_frame = pmag_menu_dialogs.PlotFrame((int(pixel_width), int(pixel_height + 50)),
fig, figname, standalone=True)
app.MainLoop()
if __name__ == "__main__":
main()
| lfairchild/PmagPy | programs/core_depthplot.py | Python | bsd-3-clause | 8,467 | 0.005551 |
from kivy.app import App
from kivy.factory import Factory
from kivy.lang import Builder
Factory.register('QRScanner', module='electrum.gui.kivy.qr_scanner')
class QrScannerDialog(Factory.AnimatedPopup):
__events__ = ('on_complete', )
def on_symbols(self, instance, value):
instance.stop()
self.dismiss()
data = value[0].data
self.dispatch('on_complete', data)
def on_complete(self, x):
''' Default Handler for on_complete event.
'''
print(x)
Builder.load_string('''
<QrScannerDialog>
title:
_(\
'[size=18dp]Hold your QRCode up to the camera[/size][size=7dp]\\n[/size]')
title_size: '24sp'
border: 7, 7, 7, 7
size_hint: None, None
size: '340dp', '290dp'
pos_hint: {'center_y': .53}
#separator_color: .89, .89, .89, 1
#separator_height: '1.2dp'
#title_color: .437, .437, .437, 1
#background: 'atlas://electrum/gui/kivy/theming/light/dialog'
on_activate:
qrscr.start()
qrscr.size = self.size
on_deactivate: qrscr.stop()
QRScanner:
id: qrscr
on_symbols: root.on_symbols(*args)
''')
| cryptapus/electrum | electrum/gui/kivy/uix/dialogs/qr_scanner.py | Python | mit | 1,153 | 0.001735 |
"""
Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
"""
import common
from conf import const
def setUp():
"""
set env
"""
common.print_debug_msg(1, "setup()")
def test_create_user():
cmd = "./teracli user create z1 z1pwd --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 0)
cmd = "./teracli user show z1"
common.check_show_user_result(cmd, True, "z1")
# user already exists
cmd = "./teracli user create z1 z1pwd --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 255)
def test_change_pwd():
cmd = "./teracli user changepwd root rootpassword --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 0)
#now, using old password can not get root permission
cmd = "./teracli user create dummy dummypwd --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 255)
#update flag file
cmd = ("sed -i 's/^--tera_user_passcode=.*/--tera_user_passcode=rootpassword/' "
+ const.user_root_flag_path)
common.execute_and_check_returncode(cmd, 0)
#now, using new password should work
cmd = "./teracli user changepwd root helloroot --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 0)
#restore the original root password in flag file
cmd = ("sed -i 's/^--tera_user_passcode=.*/--tera_user_passcode=helloroot/' "
+ const.user_root_flag_path)
common.execute_and_check_returncode(cmd, 0)
# user not found
cmd = "./teracli user changepwd oops z1pw2 --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 255)
def test_addtogroup():
cmd = "./teracli user addtogroup z1 z1g --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 0)
cmd = "./teracli user show z1"
common.check_show_user_result(cmd, True, "z1g")
common.execute_and_check_returncode(cmd, 0)
# user not found
cmd = "./teracli user addtogroup z2 z1g --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 255)
# user already in group
cmd = "./teracli user addtogroup z1 z1g --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 255)
def test_deletefromgroup():
cmd = "./teracli user deletefromgroup z1 z1g --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 0)
cmd = "./teracli user show z1"
common.check_show_user_result(cmd, False, "z1g")
# user not found
cmd = "./teracli user deletefromgroup z2 z1g --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 255)
# user not in group
cmd = "./teracli user deletefromgroup z1 z1g --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 255)
def test_delete_user():
cmd = "./teracli user delete z1 --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 0)
cmd = "./teracli user show z1"
common.check_show_user_result(cmd, False, "z1")
# can not delete root
cmd = "./teracli user delete root --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 255)
cmd = "./teracli user show root"
common.check_show_user_result(cmd, True, "root")
# user not found
cmd = "./teracli user delete z1 --flagfile=" + const.user_root_flag_path
common.execute_and_check_returncode(cmd, 255)
def tearDown():
"""
tear down
"""
common.print_debug_msg(1, "teardown()")
| linyvxiang/tera | test/testcase/test_root.py | Python | bsd-3-clause | 3,730 | 0.006702 |
# -*- coding: utf-8 -*-
from . import models
from . import controllers
from . import wizard
| ddico/odoo | addons/sale_product_configurator/__init__.py | Python | agpl-3.0 | 93 | 0 |
# -*- coding: utf-8 -*-
#
# django-timegraph - monitoring graphs for django
# Copyright (c) 2011-2012, Wifirst
# Copyright (c) 2013, Jeremy Lainé
# All rights reserved.
#
# See AUTHORS file for a full list of contributors.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. 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 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.
#
from django.contrib import admin
from timegraph.models import Graph, Metric
class GraphAdmin(admin.ModelAdmin):
list_display = ('slug', 'title', 'is_visible')
list_filter = ('is_visible',)
search_fields = ('slug', 'title')
class MetricAdmin(admin.ModelAdmin):
list_display = ('name', 'parameter', 'type', 'unit', 'rrd_enabled', 'graph_order')
list_filter = ('type', 'unit', 'rrd_enabled')
search_fields = ('name', 'parameter')
admin.site.register(Graph, GraphAdmin)
admin.site.register(Metric, MetricAdmin)
| jlaine/django-timegraph | timegraph/admin.py | Python | bsd-2-clause | 2,072 | 0.005794 |
import qctests.EN_stability_check
import util.testingProfile
import numpy
import util.main as main
##### EN_stability_check ----------------------------------------------
class TestClass():
parameters = {
"table": 'unit'
}
def setUp(self):
# this qc test will go looking for the profile in question in the db, needs to find something sensible
main.faketable('unit')
main.fakerow('unit')
def tearDown(self):
main.dbinteract('DROP TABLE unit;')
def test_mcdougallEOS(self):
'''
check the test values provided for the EOS in McDougall 2003
'''
eos = round(qctests.EN_stability_check.mcdougallEOS(35,25,2000), 6)
assert eos == 1031.654229, 'mcdougallEOS(35,25,2000) should be 1031.654229, instead got %f' % eos
eos = round(qctests.EN_stability_check.mcdougallEOS(20,20,1000), 6)
assert eos == 1017.726743, 'mcdougallEOS(20,20,1000) should be 1017.726743, instead got %f' % eos
eos = round(qctests.EN_stability_check.mcdougallEOS(40,12,8000), 6)
assert eos == 1062.928258, 'mcdougallEOS(40,12,8000) should be 1062.928258, instead got %f' % eos
def test_mcdougall_potential_temperature(self):
'''
check the test values provided for the potential temperature approximation in McDougall 2003
'''
pt = round(qctests.EN_stability_check.potentialTemperature(35, 20, 2000), 6)
assert pt == 19.621967, 'potential temperarure for S = 35 psu, T = 20C, p = 2000 db should be 19621967, instead got %f' % pt
def test_EN_stability_check_padded(self):
'''
check some behavior near the test values provided in McDougall
padded with the same level to avoid flagging the entire profile
'''
p = util.testingProfile.fakeProfile([13.5, 25.5, 20.4, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5], [0, 10, 20, 30, 40, 50, 60, 70, 80], salinities=[40, 35, 20, 40, 40, 40, 40, 40, 40], pressures=[8000, 2000, 1000, 8000, 8000, 8000, 8000, 8000, 8000], uid=8888)
qc = qctests.EN_stability_check.test(p, self.parameters)
truth = numpy.ma.array([False, True, True, False, False, False, False, False, False], mask=False)
assert numpy.array_equal(qc, truth), 'failed to flag padded stability example'
def test_EN_stability_check_unpadded(self):
'''
check same four levels as above,
but don't pad with extra levels, so that the whole profile ends up getting rejected at the last step.
'''
p = util.testingProfile.fakeProfile([13.5, 25.5, 20.4, 13.5], [0, 10, 20, 30], salinities=[40, 35, 20, 40], pressures=[8000, 2000, 1000, 8000], uid=8888)
qc = qctests.EN_stability_check.test(p, self.parameters)
truth = numpy.ma.array([True, True, True, True], mask=False)
assert numpy.array_equal(qc, truth), 'failed to flag unpadded stability example'
| s-good/AutoQC | tests/EN_stability_check_validation.py | Python | mit | 2,925 | 0.008547 |
# -*- coding: utf-8 -*-
"""
Script to cache anonymous houseprint data into hp_anonymous.pkl
Created on 05/07/2014 by Roel De Coninck
"""
import os, sys
import inspect
script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# add the path to opengrid to sys.path
sys.path.append(os.path.join(script_dir, os.pardir, os.pardir))
from opengrid.library.houseprint import Houseprint
##############################################################################
hp = Houseprint()
all_sensordata = hp.get_all_fluksosensors()
print('Sensor data fetched')
hp.save('/usr/local/src/opengrid/scripts/hp_anonymous.pkl')
hp.save('/var/www/private/hp_anonymous.pkl')
| EnergyID/opengrid | scripts/job_cache_anonymous_houseprint.py | Python | gpl-2.0 | 730 | 0.005479 |
#!/usr/bin/env python
from keyring import get_password
from boto.iam.connection import IAMConnection
import lib.LoadBotoConfig as BotoConfig
from sys import exit
envs = ['dev', 'qa', 'staging', 'demo', 'prod']
for env in envs:
id = BotoConfig.config.get(env, 'aws_access_key_id')
key = get_password(BotoConfig.config.get(env, 'keyring'), id)
conn = IAMConnection(aws_access_key_id=id, aws_secret_access_key=key)
print(conn.get_signin_url()) | johnkastler/aws | get_account_urls.py | Python | gpl-3.0 | 456 | 0.013158 |
import time
import picamera
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, False)
while True:
if(GPIO.input(23) == 1):
print "motion"
GPIO.output(18, True)
with picamera.PiCamera() as camera:
# Turn the camera's LED off
camera.led = False
# Take video
camera.resolution = (1280, 720)
filename = 'video%02d.h264' % i
camera.start_recording(filename)
while(GPIO.input(23) == 1):
camera.wait_recording(5)
camera.stop_recording()
i = i + 1
elif(GPIO.input(23) == 0):
print "no motion"
GPIO.output(18, False)
#
#
# import time
# import picamera
# import RPi.GPIO as GPIO
#
# GPIO.setmode(GPIO.BCM)
# GPIO.setup(23, GPIO.IN)
# GPIO.setup(18, GPIO.OUT)
#
# while True:
# if(GPIO.input(23) == 1):
# print "motion"
# GPIO.output(18, True)
# elif(GPIO.input(23) == 0):
# print "no motion"
# GPIO.output(18, False)
#
#
| jmbott/test-repo | motion_cam.py | Python | mit | 1,069 | 0 |
import os.path
from uuid import uuid4
import shutil
import logging
logger = logging.getLogger(__name__)
_MARKER = object()
class FileUploadTempStore(object):
session_storage_slug = 'websauna.tempstore'
def __init__(self, request):
self.tempdir = request.registry.settings['websauna.uploads_tempdir']
if os.path.os.makedirs(self.tempdir, mode=0o777, exist_ok=True):
logger.warning("Creating dir: '%s'", self.tempdir)
self.request = request
self.session = request.session
def preview_url(self, _uid):
# pylint: disable=no-self-use
return None
def __contains__(self, name):
return name in self.session.get(self.session_storage_slug, {})
def __setitem__(self, name, data):
newdata = data.copy()
stream = newdata.pop('fp', None)
if stream is not None:
newdata['randid'] = uuid4().hex
file_name = os.path.join(self.tempdir, newdata['randid'])
shutil.copyfileobj(stream, open(file_name, 'wb'))
self._tempstore_set(name, newdata)
def _tempstore_set(self, name, data):
# cope with sessioning implementations that cant deal with
# in-place mutation of mutable values (temporarily?)
existing = self.session.get(self.session_storage_slug, {})
existing[name] = data
self.session[self.session_storage_slug] = existing
def clear(self):
data = self.session.pop('substanced.tempstore', {})
for cookie in data.items():
randid = cookie.get('randid')
file_name = os.path.join(self.tempdir, randid)
try:
os.remove(file_name)
except OSError:
pass
def get(self, name, default=None):
data = self.session.get(self.session_storage_slug, {}).get(name)
if data is None:
return default
newdata = data.copy()
randid = newdata.get('randid')
if randid is not None:
file_name = os.path.join(self.tempdir, randid)
try:
newdata['fp'] = open(file_name, 'rb')
except IOError:
pass
return newdata
def __getitem__(self, name):
data = self.get(name, _MARKER)
if data is _MARKER:
raise KeyError(name)
return data
| enkidulan/enkiblog | src/enkiblog/core/deform/tempstorage.py | Python | apache-2.0 | 2,365 | 0 |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Presidentielcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test BIP68 implementation
#
from test_framework.test_framework import PresidentielcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
from test_framework.blocktools import *
SEQUENCE_LOCKTIME_DISABLE_FLAG = (1<<31)
SEQUENCE_LOCKTIME_TYPE_FLAG = (1<<22) # this means use time (0 means height)
SEQUENCE_LOCKTIME_GRANULARITY = 9 # this is a bit-shift
SEQUENCE_LOCKTIME_MASK = 0x0000ffff
# RPC error for non-BIP68 final transactions
NOT_FINAL_ERROR = "64: non-BIP68-final"
class BIP68Test(PresidentielcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 2
self.setup_clean_chain = False
def setup_network(self):
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-blockprioritysize=0"]))
self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-blockprioritysize=0", "-acceptnonstdtxn=0"]))
self.is_network_split = False
self.relayfee = self.nodes[0].getnetworkinfo()["relayfee"]
connect_nodes(self.nodes[0], 1)
def run_test(self):
# Generate some coins
self.nodes[0].generate(110)
print("Running test disable flag")
self.test_disable_flag()
print("Running test sequence-lock-confirmed-inputs")
self.test_sequence_lock_confirmed_inputs()
print("Running test sequence-lock-unconfirmed-inputs")
self.test_sequence_lock_unconfirmed_inputs()
print("Running test BIP68 not consensus before versionbits activation")
self.test_bip68_not_consensus()
print("Verifying nVersion=2 transactions aren't standard")
self.test_version2_relay(before_activation=True)
print("Activating BIP68 (and 112/113)")
self.activateCSV()
print("Verifying nVersion=2 transactions are now standard")
self.test_version2_relay(before_activation=False)
print("Passed\n")
# Test that BIP68 is not in effect if tx version is 1, or if
# the first sequence bit is set.
def test_disable_flag(self):
# Create some unconfirmed inputs
new_addr = self.nodes[0].getnewaddress()
self.nodes[0].sendtoaddress(new_addr, 2) # send 2 PRC
utxos = self.nodes[0].listunspent(0, 0)
assert(len(utxos) > 0)
utxo = utxos[0]
tx1 = CTransaction()
value = int(satoshi_round(utxo["amount"] - self.relayfee)*COIN)
# Check that the disable flag disables relative locktime.
# If sequence locks were used, this would require 1 block for the
# input to mature.
sequence_value = SEQUENCE_LOCKTIME_DISABLE_FLAG | 1
tx1.vin = [CTxIn(COutPoint(int(utxo["txid"], 16), utxo["vout"]), nSequence=sequence_value)]
tx1.vout = [CTxOut(value, CScript([b'a']))]
tx1_signed = self.nodes[0].signrawtransaction(ToHex(tx1))["hex"]
tx1_id = self.nodes[0].sendrawtransaction(tx1_signed)
tx1_id = int(tx1_id, 16)
# This transaction will enable sequence-locks, so this transaction should
# fail
tx2 = CTransaction()
tx2.nVersion = 2
sequence_value = sequence_value & 0x7fffffff
tx2.vin = [CTxIn(COutPoint(tx1_id, 0), nSequence=sequence_value)]
tx2.vout = [CTxOut(int(value-self.relayfee*COIN), CScript([b'a']))]
tx2.rehash()
try:
self.nodes[0].sendrawtransaction(ToHex(tx2))
except JSONRPCException as exp:
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
else:
assert(False)
# Setting the version back down to 1 should disable the sequence lock,
# so this should be accepted.
tx2.nVersion = 1
self.nodes[0].sendrawtransaction(ToHex(tx2))
# Calculate the median time past of a prior block ("confirmations" before
# the current tip).
def get_median_time_past(self, confirmations):
block_hash = self.nodes[0].getblockhash(self.nodes[0].getblockcount()-confirmations)
return self.nodes[0].getblockheader(block_hash)["mediantime"]
# Test that sequence locks are respected for transactions spending confirmed inputs.
def test_sequence_lock_confirmed_inputs(self):
# Create lots of confirmed utxos, and use them to generate lots of random
# transactions.
max_outputs = 50
addresses = []
while len(addresses) < max_outputs:
addresses.append(self.nodes[0].getnewaddress())
while len(self.nodes[0].listunspent()) < 200:
import random
random.shuffle(addresses)
num_outputs = random.randint(1, max_outputs)
outputs = {}
for i in range(num_outputs):
outputs[addresses[i]] = random.randint(1, 20)*0.01
self.nodes[0].sendmany("", outputs)
self.nodes[0].generate(1)
utxos = self.nodes[0].listunspent()
# Try creating a lot of random transactions.
# Each time, choose a random number of inputs, and randomly set
# some of those inputs to be sequence locked (and randomly choose
# between height/time locking). Small random chance of making the locks
# all pass.
for i in range(400):
# Randomly choose up to 10 inputs
num_inputs = random.randint(1, 10)
random.shuffle(utxos)
# Track whether any sequence locks used should fail
should_pass = True
# Track whether this transaction was built with sequence locks
using_sequence_locks = False
tx = CTransaction()
tx.nVersion = 2
value = 0
for j in range(num_inputs):
sequence_value = 0xfffffffe # this disables sequence locks
# 50% chance we enable sequence locks
if random.randint(0,1):
using_sequence_locks = True
# 10% of the time, make the input sequence value pass
input_will_pass = (random.randint(1,10) == 1)
sequence_value = utxos[j]["confirmations"]
if not input_will_pass:
sequence_value += 1
should_pass = False
# Figure out what the median-time-past was for the confirmed input
# Note that if an input has N confirmations, we're going back N blocks
# from the tip so that we're looking up MTP of the block
# PRIOR to the one the input appears in, as per the BIP68 spec.
orig_time = self.get_median_time_past(utxos[j]["confirmations"])
cur_time = self.get_median_time_past(0) # MTP of the tip
# can only timelock this input if it's not too old -- otherwise use height
can_time_lock = True
if ((cur_time - orig_time) >> SEQUENCE_LOCKTIME_GRANULARITY) >= SEQUENCE_LOCKTIME_MASK:
can_time_lock = False
# if time-lockable, then 50% chance we make this a time lock
if random.randint(0,1) and can_time_lock:
# Find first time-lock value that fails, or latest one that succeeds
time_delta = sequence_value << SEQUENCE_LOCKTIME_GRANULARITY
if input_will_pass and time_delta > cur_time - orig_time:
sequence_value = ((cur_time - orig_time) >> SEQUENCE_LOCKTIME_GRANULARITY)
elif (not input_will_pass and time_delta <= cur_time - orig_time):
sequence_value = ((cur_time - orig_time) >> SEQUENCE_LOCKTIME_GRANULARITY)+1
sequence_value |= SEQUENCE_LOCKTIME_TYPE_FLAG
tx.vin.append(CTxIn(COutPoint(int(utxos[j]["txid"], 16), utxos[j]["vout"]), nSequence=sequence_value))
value += utxos[j]["amount"]*COIN
# Overestimate the size of the tx - signatures should be less than 120 bytes, and leave 50 for the output
tx_size = len(ToHex(tx))//2 + 120*num_inputs + 50
tx.vout.append(CTxOut(int(value-self.relayfee*tx_size*COIN/1000), CScript([b'a'])))
rawtx = self.nodes[0].signrawtransaction(ToHex(tx))["hex"]
try:
self.nodes[0].sendrawtransaction(rawtx)
except JSONRPCException as exp:
assert(not should_pass and using_sequence_locks)
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
else:
assert(should_pass or not using_sequence_locks)
# Recalculate utxos if we successfully sent the transaction
utxos = self.nodes[0].listunspent()
# Test that sequence locks on unconfirmed inputs must have nSequence
# height or time of 0 to be accepted.
# Then test that BIP68-invalid transactions are removed from the mempool
# after a reorg.
def test_sequence_lock_unconfirmed_inputs(self):
# Store height so we can easily reset the chain at the end of the test
cur_height = self.nodes[0].getblockcount()
# Create a mempool tx.
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 2)
tx1 = FromHex(CTransaction(), self.nodes[0].getrawtransaction(txid))
tx1.rehash()
# Anyone-can-spend mempool tx.
# Sequence lock of 0 should pass.
tx2 = CTransaction()
tx2.nVersion = 2
tx2.vin = [CTxIn(COutPoint(tx1.sha256, 0), nSequence=0)]
tx2.vout = [CTxOut(int(tx1.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))]
tx2_raw = self.nodes[0].signrawtransaction(ToHex(tx2))["hex"]
tx2 = FromHex(tx2, tx2_raw)
tx2.rehash()
self.nodes[0].sendrawtransaction(tx2_raw)
# Create a spend of the 0th output of orig_tx with a sequence lock
# of 1, and test what happens when submitting.
# orig_tx.vout[0] must be an anyone-can-spend output
def test_nonzero_locks(orig_tx, node, relayfee, use_height_lock):
sequence_value = 1
if not use_height_lock:
sequence_value |= SEQUENCE_LOCKTIME_TYPE_FLAG
tx = CTransaction()
tx.nVersion = 2
tx.vin = [CTxIn(COutPoint(orig_tx.sha256, 0), nSequence=sequence_value)]
tx.vout = [CTxOut(int(orig_tx.vout[0].nValue - relayfee*COIN), CScript([b'a']))]
tx.rehash()
try:
node.sendrawtransaction(ToHex(tx))
except JSONRPCException as exp:
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
assert(orig_tx.hash in node.getrawmempool())
else:
# orig_tx must not be in mempool
assert(orig_tx.hash not in node.getrawmempool())
return tx
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True)
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False)
# Now mine some blocks, but make sure tx2 doesn't get mined.
# Use prioritisetransaction to lower the effective feerate to 0
self.nodes[0].prioritisetransaction(tx2.hash, -1e15, int(-self.relayfee*COIN))
cur_time = int(time.time())
for i in range(10):
self.nodes[0].setmocktime(cur_time + 600)
self.nodes[0].generate(1)
cur_time += 600
assert(tx2.hash in self.nodes[0].getrawmempool())
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True)
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False)
# Mine tx2, and then try again
self.nodes[0].prioritisetransaction(tx2.hash, 1e15, int(self.relayfee*COIN))
# Advance the time on the node so that we can test timelocks
self.nodes[0].setmocktime(cur_time+600)
self.nodes[0].generate(1)
assert(tx2.hash not in self.nodes[0].getrawmempool())
# Now that tx2 is not in the mempool, a sequence locked spend should
# succeed
tx3 = test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False)
assert(tx3.hash in self.nodes[0].getrawmempool())
self.nodes[0].generate(1)
assert(tx3.hash not in self.nodes[0].getrawmempool())
# One more test, this time using height locks
tx4 = test_nonzero_locks(tx3, self.nodes[0], self.relayfee, use_height_lock=True)
assert(tx4.hash in self.nodes[0].getrawmempool())
# Now try combining confirmed and unconfirmed inputs
tx5 = test_nonzero_locks(tx4, self.nodes[0], self.relayfee, use_height_lock=True)
assert(tx5.hash not in self.nodes[0].getrawmempool())
utxos = self.nodes[0].listunspent()
tx5.vin.append(CTxIn(COutPoint(int(utxos[0]["txid"], 16), utxos[0]["vout"]), nSequence=1))
tx5.vout[0].nValue += int(utxos[0]["amount"]*COIN)
raw_tx5 = self.nodes[0].signrawtransaction(ToHex(tx5))["hex"]
try:
self.nodes[0].sendrawtransaction(raw_tx5)
except JSONRPCException as exp:
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
else:
assert(False)
# Test mempool-BIP68 consistency after reorg
#
# State of the transactions in the last blocks:
# ... -> [ tx2 ] -> [ tx3 ]
# tip-1 tip
# And currently tx4 is in the mempool.
#
# If we invalidate the tip, tx3 should get added to the mempool, causing
# tx4 to be removed (fails sequence-lock).
self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())
assert(tx4.hash not in self.nodes[0].getrawmempool())
assert(tx3.hash in self.nodes[0].getrawmempool())
# Now mine 2 empty blocks to reorg out the current tip (labeled tip-1 in
# diagram above).
# This would cause tx2 to be added back to the mempool, which in turn causes
# tx3 to be removed.
tip = int(self.nodes[0].getblockhash(self.nodes[0].getblockcount()-1), 16)
height = self.nodes[0].getblockcount()
for i in range(2):
block = create_block(tip, create_coinbase(height), cur_time)
block.nVersion = 3
block.rehash()
block.solve()
tip = block.sha256
height += 1
self.nodes[0].submitblock(ToHex(block))
cur_time += 1
mempool = self.nodes[0].getrawmempool()
assert(tx3.hash not in mempool)
assert(tx2.hash in mempool)
# Reset the chain and get rid of the mocktimed-blocks
self.nodes[0].setmocktime(0)
self.nodes[0].invalidateblock(self.nodes[0].getblockhash(cur_height+1))
self.nodes[0].generate(10)
# Make sure that BIP68 isn't being used to validate blocks, prior to
# versionbits activation. If more blocks are mined prior to this test
# being run, then it's possible the test has activated the soft fork, and
# this test should be moved to run earlier, or deleted.
def test_bip68_not_consensus(self):
assert(get_bip9_status(self.nodes[0], 'csv')['status'] != 'active')
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 2)
tx1 = FromHex(CTransaction(), self.nodes[0].getrawtransaction(txid))
tx1.rehash()
# Make an anyone-can-spend transaction
tx2 = CTransaction()
tx2.nVersion = 1
tx2.vin = [CTxIn(COutPoint(tx1.sha256, 0), nSequence=0)]
tx2.vout = [CTxOut(int(tx1.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))]
# sign tx2
tx2_raw = self.nodes[0].signrawtransaction(ToHex(tx2))["hex"]
tx2 = FromHex(tx2, tx2_raw)
tx2.rehash()
self.nodes[0].sendrawtransaction(ToHex(tx2))
# Now make an invalid spend of tx2 according to BIP68
sequence_value = 100 # 100 block relative locktime
tx3 = CTransaction()
tx3.nVersion = 2
tx3.vin = [CTxIn(COutPoint(tx2.sha256, 0), nSequence=sequence_value)]
tx3.vout = [CTxOut(int(tx2.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))]
tx3.rehash()
try:
self.nodes[0].sendrawtransaction(ToHex(tx3))
except JSONRPCException as exp:
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
else:
assert(False)
# make a block that violates bip68; ensure that the tip updates
tip = int(self.nodes[0].getbestblockhash(), 16)
block = create_block(tip, create_coinbase(self.nodes[0].getblockcount()+1))
block.nVersion = 3
block.vtx.extend([tx1, tx2, tx3])
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.nodes[0].submitblock(ToHex(block))
assert_equal(self.nodes[0].getbestblockhash(), block.hash)
def activateCSV(self):
# activation should happen at block height 432 (3 periods)
min_activation_height = 432
height = self.nodes[0].getblockcount()
assert(height < 432)
self.nodes[0].generate(432-height)
assert(get_bip9_status(self.nodes[0], 'csv')['status'] == 'active')
sync_blocks(self.nodes)
# Use self.nodes[1] to test standardness relay policy
def test_version2_relay(self, before_activation):
inputs = [ ]
outputs = { self.nodes[1].getnewaddress() : 1.0 }
rawtx = self.nodes[1].createrawtransaction(inputs, outputs)
rawtxfund = self.nodes[1].fundrawtransaction(rawtx)['hex']
tx = FromHex(CTransaction(), rawtxfund)
tx.nVersion = 2
tx_signed = self.nodes[1].signrawtransaction(ToHex(tx))["hex"]
try:
tx_id = self.nodes[1].sendrawtransaction(tx_signed)
assert(before_activation == False)
except:
assert(before_activation)
if __name__ == '__main__':
BIP68Test().main()
| presidentielcoin/presidentielcoin | qa/rpc-tests/bip68-sequence.py | Python | mit | 18,409 | 0.003477 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.netsvc
class ifrs_report_wizard(osv.osv_memory):
""" Wizard que permite al usuario elegir que periodo quiere imprimir del año fiscal """
_name = 'ifrs.report.wizard'
_description = 'IFRS Report'
def onchange_company_id(self, cr, uid, ids, company_id, context=None):
context = context or {}
context['company_id'] = company_id
res = {'value': {}}
if not company_id:
return res
cur_id = self.pool.get('res.company').browse(
cr, uid, company_id, context=context).currency_id.id
fy_id = self.pool.get('account.fiscalyear').find(
cr, uid, context=context)
res['value'].update({'fiscalyear_id': fy_id})
res['value'].update({'currency_id': cur_id})
return res
_columns = {
'period': fields.many2one('account.period', 'Force period', help='Fiscal period to assign to the invoice. Keep empty to use the period of the current date.'),
'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal Year', help='Fiscal Year'),
'company_id': fields.many2one('res.company', string='Company', ondelete='cascade', required=True, help='Company name'),
'currency_id': fields.many2one('res.currency', 'Currency', help="Currency at which this report will be expressed. If not selected will be used the one set in the company"),
'exchange_date': fields.date('Exchange Date', help='Date of change that will be printed in the report, with respect to the currency of the company'),
'report_type': fields.selection([
('all', 'All Fiscalyear'),
('per', 'Force Period')],
string='Type', required=True, help='Indicates if the report it will be printed for the entire fiscal year, or for a particular period'),
'columns': fields.selection([
('ifrs', 'Two Columns'),
('webkitaccount.ifrs_12', 'Twelve Columns'),
#('ifrs_12_partner_detail', 'With Partner Detail')
],
string='Number of Columns',
help='Number of columns that will be printed in the report:'
" -Two Colums(02),-Twelve Columns(12)"),
'target_move': fields.selection([('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Target Moves', help='Print All Accounting Entries or just Posted Accounting Entries'),
'report_format' : fields.selection([
('pdf', 'PDF'),
('spreadsheet', 'Spreadsheet')], 'Report Format')
}
_defaults = {
'report_type': 'all',
'target_move': 'posted',
'company_id': lambda self, cr, uid, c: self.pool.get('ifrs.ifrs').browse(cr, uid, c.get('active_id')).company_id.id,
'fiscalyear_id': lambda self, cr, uid, c: self.pool.get('ifrs.ifrs').browse(cr, uid, c.get('active_id')).fiscalyear_id.id,
'exchange_date': fields.date.today,
'columns': 'ifrs',
'report_format' : 'pdf'
}
def default_get(self, cr, uid, fields, context=None):
if context is None:
context = {}
res = super(ifrs_report_wizard, self).default_get(
cr, uid, fields, context=context)
# res.update({'uid_country':
# self._get_country_code(cr,uid,context=context)})
return res
def _get_period(self, cr, uid, context={}):
""" Return the current period id """
account_period_obj = self.pool.get('account.period')
ids = account_period_obj.find(
cr, uid, time.strftime('%Y-%m-%d'), context=context)
period_id = ids[0]
return period_id
def _get_fiscalyear(self, cr, uid, context={}, period_id=False):
""" Return fiscalyear id for the period_id given.
If period_id is nor given then return the current fiscalyear """
if period_id:
period_obj = self.pool.get(
'account.period').browse(cr, uid, period_id)
fiscalyear_id = period_obj.fiscalyear_id.id
else:
fiscalyear_obj = self.pool.get('account.fiscalyear')
ids = fiscalyear_obj.find(cr, uid, time.strftime(
'%Y-%m-%d'), context=context)
fiscalyear_id = ids
return fiscalyear_id
def print_report(self, cr, uid, ids, context={}):
datas = {'ids': context.get('active_ids', [])}
wizard_ifrs = self.browse(cr, uid, ids, context=context)[0]
datas['report_type'] = str(wizard_ifrs.report_type)
datas['company'] = wizard_ifrs.company_id.id
datas['columns'] = str(wizard_ifrs.columns)
datas['target_move'] = wizard_ifrs.target_move
datas['exchange_date'] = wizard_ifrs.exchange_date
datas['currency_wizard'] = wizard_ifrs.currency_id.id
datas['currency_wizard_name'] = wizard_ifrs.currency_id.name
if datas['report_type'] == 'all':
datas['fiscalyear'] = wizard_ifrs.fiscalyear_id.id or self._get_fiscalyear(
cr, uid, context=context)
datas['period'] = False
else:
datas['columns'] = 'ifrs'
datas['period'] = wizard_ifrs.period.id or self._get_period(
cr, uid, context=context)
datas['fiscalyear'] = self._get_fiscalyear(
cr, uid, context=context, period_id=datas['period'])
if str(wizard_ifrs.columns) == 'webkitaccount.ifrs_12' and wizard_ifrs.report_format == 'spreadsheet':
datas['columns'] = 'webkitaccount.ifrs_12_html'
if str(wizard_ifrs.columns) == 'ifrs' and wizard_ifrs.report_format == 'spreadsheet':
datas['columns'] = 'ifrs_report_html'
return {
'type': 'ir.actions.report.xml',
'report_name': datas['columns'],
'datas': datas
}
ifrs_report_wizard()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| Jgarcia-IAS/SAT | openerp/addons-extra/odoo-pruebas/odoo-server/addons-extra/ifrs_report/wizard/ifrs_report_wizard.py | Python | agpl-3.0 | 7,032 | 0.002418 |
## Changemonger: An OpenStreetMap change analyzer
## Copyright (C) 2012 Serge Wroclawski
##
## 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/>.
"""Contains functions related to Changemonger features for a yaml backend"""
import inflect
import yaml
import os.path
import imp
inflection = inflect.engine()
class BaseFeature:
"""The base feature class"""
def __init__(self, name):
"Init the object"
self.name = name
self.types = []
self.categories = []
self.named = True
self.id = unicode(id(self))
self._prominence = 0
@property
def prominence(self, ele):
"""How important a feature is"""
score = 0
tags = ele['tags']
if len(ele['tags']) > 0:
score += 1
if ( tags.get('name') or tags.get('brand') or tags.get('operator') ):
score += 2
if tags.get('historical') or tags.get('wikipedia'):
score += 3
return score + self._prominence
def _typecheck(self, ele):
"Check that the element matches this feature's type"
if self.types:
if ele['type'] in self.types:
return True
else:
return False
else:
return True
def category(self, cat):
"Add a category to this feature"
self.categories.append(cat)
def match(self, element):
"Generic function"
# Never use this directly
return True
@property
def plural(self):
"Returns the plural version of the feature's name"
return inflection.plural(self.name)
@property
def precision(self):
"Returns the precision of the object. This should be set"
return 0
class SimpleFeature(BaseFeature):
"""A simple feature (most objects in the yaml files are SimpleFeatures"""
def __init__(self, name):
"Init simple feature"
self.tags = []
BaseFeature.__init__(self, name)
def tag(self, tg):
"Add a tag to object's tags"
self.tags.append(tg)
def match(self, element):
"Matches for simple features uses tags"
if self._typecheck(element):
for tag in self.tags:
if not tag in element['_tags']:
return False
else:
return True
else:
return False
@property
def precision(self):
"Simple features have a precision of 10 + # of tags by default"
return 10 + len(self.tags)
class Category(BaseFeature):
"Feature categories"
def __init__(self, name):
"Init a category"
self.features = []
BaseFeature.__init__(self, name)
def register(self, feature):
"Register a feature to this category"
self.features.append(feature)
def match(self, element):
"The category checks all features for matches"
for feature in self.features:
if feature.match(element):
return True
return False
@property
def precision(self):
"Categories are precision 3 by default"
return 3
def compare_precision(a, b):
"""Compare the precision of two features"""
return b.precision - a.precision
class FeatureDB:
"""This is the abstraction against using the features"""
def __init__(self, directory = 'features'):
"""Initialize feature database, use the argument as the directory"""
self._simple = []
self._magic = []
# We almost never iterate through categories, but we do call
# them by name a lot
self._categories = {}
# The index contains unique IDs for features
self._index = {}
# Now load the actual features
if not os.path.isabs(directory):
directory = os.path.abspath(directory)
# We're going to just assume the directory exists for now
if os.path.exists(os.path.join(directory, 'features.yaml')):
self._load_yaml_simple_features(
os.path.join(directory, 'simple.yaml'))
elif os.path.isdir(os.path.join(directory, 'simple')):
self._load_simple_directory(os.path.join(directory, 'simple'))
if os.path.exists(os.path.join(directory, 'categories.yaml')):
self._load_yaml_categories(os.path.join(directory,
'categories.yaml'))
if os.path.exists(os.path.join(directory, 'magic.py')):
self._load_magic_file(directory)
@property
def all(self):
"""Return all objects in the database"""
return self._simple + self._categories.values() + self._magic
def _load_magic_file(self, directory):
"""Load a magic (plain python) features file"""
fp, pathname, description = imp.find_module('magic', [directory])
try:
module = imp.load_module('magic', fp, pathname, description)
features = module.magic()
for feature in features:
self._magic.append(feature)
self._index[feature.id] = feature
finally:
if fp:
fp.close()
def _load_simple_directory(self, dirname):
"""Load a directory of feature files"""
for subdir, dirs, files in os.walk(dirname):
for fname in files:
name, ext = os.path.splitext(fname)
if ext == '.yaml' and name[0] != '.':
self._load_yaml_simple_features(
os.path.join(dirname, fname))
def _get_or_make_category(self, name):
"""Either retrieve a category or create one as necessary"""
category = self._categories.get(name)
if not category:
category = Category(name)
self._categories[name] = category
self._index[category.id] = category
return category
def _yaml_item_to_feature(self, item):
"""Takes a yaml item and returns a Feature object"""
feature = SimpleFeature(item['name'])
# type
if item.has_key('types'):
if isinstance(item['types'], basestring):
feature.types = item['types'].split(',')
else:
feature.types = item['types']
# id (virtually unused)
if item.has_key('id'):
feature.id = unicode(item['id'])
# tags
if isinstance(item['tags'], basestring):
tags = item['tags'].split(',')
else:
tags = item['tags']
for tag in tags:
feature.tag(tag)
# plural
if item.has_key('plural'):
feature.plural = item['plural']
# precision
if item.has_key('precision'):
feature.precision = int(item['precision'])
# categories
if item.has_key('categories'):
if isinstance(item['categories'], basestring):
categories = item['categories'].split(',')
else:
categories = item['categories']
for cat_name in categories:
category = self._get_or_make_category(cat_name)
category.register(feature)
feature.category(category)
# Named?
if item.has_key('named'):
feature.named = item['named']
# Prominence
if item.has_key('promience'):
feature._promience = item['prominence']
return feature
def _load_yaml_categories(self, fname):
"""Load a yaml file full of categories into the database"""
with open(fname) as fd:
data = fd.read()
yamldata = yaml.safe_load(data)
for item in yamldata:
category = self._get_or_make_category(item['name'])
def _load_yaml_simple_features(self, fname):
"""Load a yaml of features file into the database"""
with open(fname) as fd:
data = fd.read()
yamldata = yaml.safe_load(data)
for item in yamldata:
# Make this a feature
feature = self._yaml_item_to_feature(item)
self._simple.append(feature)
self._index[feature.id] = feature
def add_index(self, feature):
"""Add feature id to internal id index"""
if self.get(feature.id):
### We need a real way to handle this...
print "BAD BAD BAD!!!! ID CONFLICT BETWEEN %s and %s" % (self.get(feature.id).name, feature.name)
self._index[feature.id] = feature
def matchBestSolo(self, ele):
"""Returns the best matching feature for an element"""
# This function is not optimized in any way. Ideally it should
# run in mongodb or maybe even some other way, but it's quick
# and dirty and it works.
match = None
match_val = -10
for feature in self.all:
if feature.precision > match_val and feature.match(ele):
match = feature
match_val = feature.precision
return match
def matchAllSolo(self, ele):
"""Return all the matching features and categories for an
element, sorted by precision
"""
features = []
for feature in self.features:
if feature.match(ele):
features.append(feature)
return(sorted(features, cmp=compare_precision))
def matchEach(self, coll):
"""Returns all the matches for all the elements in the collection"""
return [self.matchAllSolo(ele) for ele in coll]
def get(self, id):
"Retrieve an object by index id"
return self._index[id]
@property
def simple(self):
"Retrieve the simple features"
return self._simple
@property
def categories(self):
"Retrieve the categories"
return self._categories.values()
@property
def magic(self):
"Retrieve the magic features"
return self._magic
@property
def features(self):
"Return all features"
return self._simple + self._categories.values() + self._magic
| emacsen/changemonger | features.py | Python | agpl-3.0 | 10,844 | 0.003689 |
"""
A client/server code for Raspberry Pi ADC input
Xaratustrah@GitHUB
2016
adapted from:
https://wiki.python.org/moin/PyQt/Writing%20a%20client%20for%20a%20zeromq%20service
"""
from PyQt5.QtCore import pyqtSignal, QThread
import zmq
class ZMQListener(QThread):
message = pyqtSignal(str)
err_msg = pyqtSignal(str)
def __init__(self, host, port, topic_filter):
QThread.__init__(self)
self.host = host
self.port = port
self.topic_filter = topic_filter
self.running = True
context = zmq.Context()
try:
self.sock = context.socket(zmq.SUB)
self.sock.connect("tcp://{}:{}".format(self.host, self.port))
self.sock.setsockopt_string(zmq.SUBSCRIBE, self.topic_filter)
except(ConnectionRefusedError):
self.err_msg.emit('Server not running. Aborting...')
except(EOFError, KeyboardInterrupt):
self.err_msg.emit('User input cancelled. Aborting...')
def loop(self):
while self.running:
ba = self.sock.recv()
self.message.emit(ba.decode("utf-8"))
def __del__(self):
self.terminate()
self.quit()
self.wait()
| xaratustrah/pypiscope | zmq_listener.py | Python | gpl-3.0 | 1,215 | 0 |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import match_pb2 as match__pb2
class MatchServiceStub(object):
"""MatchService is a Google managed service for efficient vector similarity
search at scale.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Match = channel.unary_unary(
'/google.cloud.aiplatform.container.v1alpha1.MatchService/Match',
request_serializer=match__pb2.MatchRequest.SerializeToString,
response_deserializer=match__pb2.MatchResponse.FromString,
)
self.BatchMatch = channel.unary_unary(
'/google.cloud.aiplatform.container.v1alpha1.MatchService/BatchMatch',
request_serializer=match__pb2.BatchMatchRequest.SerializeToString,
response_deserializer=match__pb2.BatchMatchResponse.FromString,
)
class MatchServiceServicer(object):
"""MatchService is a Google managed service for efficient vector similarity
search at scale.
"""
def Match(self, request, context):
"""Returns the nearest neighbors for the query. If it is a sharded
deployment, calls the other shards and aggregates the responses.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def BatchMatch(self, request, context):
"""Returns the nearest neighbors for batch queries. If it is a sharded
deployment, calls the other shards and aggregates the responses.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_MatchServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'Match': grpc.unary_unary_rpc_method_handler(
servicer.Match,
request_deserializer=match__pb2.MatchRequest.FromString,
response_serializer=match__pb2.MatchResponse.SerializeToString,
),
'BatchMatch': grpc.unary_unary_rpc_method_handler(
servicer.BatchMatch,
request_deserializer=match__pb2.BatchMatchRequest.FromString,
response_serializer=match__pb2.BatchMatchResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'google.cloud.aiplatform.container.v1alpha1.MatchService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class MatchService(object):
"""MatchService is a Google managed service for efficient vector similarity
search at scale.
"""
@staticmethod
def Match(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/google.cloud.aiplatform.container.v1alpha1.MatchService/Match',
match__pb2.MatchRequest.SerializeToString,
match__pb2.MatchResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def BatchMatch(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/google.cloud.aiplatform.container.v1alpha1.MatchService/BatchMatch',
match__pb2.BatchMatchRequest.SerializeToString,
match__pb2.BatchMatchResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
| GoogleCloudPlatform/analytics-componentized-patterns | retail/recommendation-system/bqml-scann/ann_grpc/match_pb2_grpc.py | Python | apache-2.0 | 4,364 | 0.008937 |
import sys
import time
import uuid
import pandaserver.userinterface.Client as Client
from pandaserver.taskbuffer.JobSpec import JobSpec
from pandaserver.taskbuffer.FileSpec import FileSpec
aSrvID = None
prodUserNameDefault = 'unknown-user'
prodUserName = None
prodUserNameDP = None
prodUserNamePipeline = None
site = 'ANALY_BNL-LSST'
PIPELINE_TASK = None
PIPELINE_PROCESSINSTANCE = None
PIPELINE_EXECUTIONNUMBER = None
PIPELINE_STREAM = None
lsstJobParams = ""
for idx,argv in enumerate(sys.argv):
if argv == '--site':
try:
site = sys.argv[idx + 1]
except Exception:
site = 'ANALY_BNL-LSST'
if argv == '-DP_USER':
try:
prodUserNameDP = sys.argv[idx + 1]
if len(lsstJobParams):
lsstJobParams += "|"
lsstJobParams += "%(key)s=%(value)s" % \
{'key': 'DP_USER', \
'value': str(prodUserNameDP)}
except Exception:
prodUserNameDP = None
if argv == '-PIPELINE_USER':
try:
prodUserNamePipeline = sys.argv[idx + 1]
if len(lsstJobParams):
lsstJobParams += "|"
lsstJobParams += "%(key)s=%(value)s" % \
{'key': 'PIPELINE_USER', \
'value': str(prodUserNamePipeline)}
except Exception:
prodUserNamePipeline = None
if argv == '-PIPELINE_TASK':
try:
PIPELINE_TASK = sys.argv[idx + 1]
if len(lsstJobParams):
lsstJobParams += "|"
lsstJobParams += "%(key)s=%(value)s" % \
{'key': 'PIPELINE_TASK', \
'value': str(PIPELINE_TASK)}
except Exception:
PIPELINE_TASK = None
if argv == '-PIPELINE_PROCESSINSTANCE':
try:
PIPELINE_PROCESSINSTANCE = int(sys.argv[idx + 1])
if len(lsstJobParams):
lsstJobParams += "|"
lsstJobParams += "%(key)s=%(value)s" % \
{'key': 'PIPELINE_PROCESSINSTANCE', \
'value': str(PIPELINE_PROCESSINSTANCE)}
except Exception:
PIPELINE_PROCESSINSTANCE = None
if argv == '-PIPELINE_EXECUTIONNUMBER':
try:
PIPELINE_EXECUTIONNUMBER = int(sys.argv[idx + 1])
if len(lsstJobParams):
lsstJobParams += "|"
lsstJobParams += "%(key)s=%(value)s" % \
{'key': 'PIPELINE_EXECUTIONNUMBER', \
'value': str(PIPELINE_EXECUTIONNUMBER)}
except Exception:
PIPELINE_EXECUTIONNUMBER = None
if argv == '-PIPELINE_STREAM':
try:
PIPELINE_STREAM = int(sys.argv[idx + 1])
if len(lsstJobParams):
lsstJobParams += "|"
lsstJobParams += "%(key)s=%(value)s" % \
{'key': 'PIPELINE_STREAM', \
'value': str(PIPELINE_STREAM)}
except Exception:
PIPELINE_STREAM = None
if argv == '-s':
aSrvID = sys.argv[idx+1]
sys.argv = sys.argv[:idx]
break
### DP_USER and PIPELINE_USER preference
if prodUserNameDP is not None:
prodUserName = prodUserNameDP
elif prodUserNamePipeline is not None:
prodUserName = prodUserNamePipeline
#site = sys.argv[1]
#site = 'ANALY_BNL-LSST' #orig
#site = 'BNL-LSST'
#site = 'SWT2_CPB-LSST'
#site = 'UTA_SWT2-LSST'
#site = 'ANALY_SWT2_CPB-LSST'
destName = None
if prodUserName is not None \
and PIPELINE_TASK is not None \
and PIPELINE_PROCESSINSTANCE is not None:
datasetName = 'panda.lsst.user.%(PIPELINE_PROCESSINSTANCE)s.%(PIPELINE_TASK)s.%(prodUserName)s' % \
{'prodUserName': str(prodUserName), \
'PIPELINE_TASK': str(PIPELINE_TASK), \
'PIPELINE_PROCESSINSTANCE': str(PIPELINE_PROCESSINSTANCE) \
}
else:
datasetName = 'panda.lsst.user.jschovan.%s' % str(uuid.uuid4())
if prodUserName is not None \
and PIPELINE_TASK is not None \
and PIPELINE_EXECUTIONNUMBER is not None \
and PIPELINE_STREAM is not None:
jobName = 'job.%(PIPELINE_PROCESSINSTANCE)s.%(PIPELINE_TASK)s.%(PIPELINE_EXECUTIONNUMBER)s.%(prodUserName)s.%(PIPELINE_STREAM)s' % \
{'prodUserName': str(prodUserName), \
'PIPELINE_TASK': str(PIPELINE_TASK), \
'PIPELINE_EXECUTIONNUMBER': str(PIPELINE_EXECUTIONNUMBER), \
'PIPELINE_STREAM': str(PIPELINE_STREAM), \
'PIPELINE_PROCESSINSTANCE': str(PIPELINE_PROCESSINSTANCE) \
}
else:
jobName = "%s" % str(uuid.uuid4())
if PIPELINE_STREAM is not None:
jobDefinitionID = PIPELINE_STREAM
else:
jobDefinitionID = int(time.time()) % 10000
job = JobSpec()
job.jobDefinitionID = jobDefinitionID
job.jobName = jobName
job.transformation = 'http://pandawms.org/pandawms-jobcache/lsst-trf.sh'
job.destinationDBlock = datasetName
job.destinationSE = 'local'
job.currentPriority = 1000
job.prodSourceLabel = 'panda'
job.jobParameters = ' --lsstJobParams="%s" ' % lsstJobParams
if prodUserName is not None:
job.prodUserName = prodUserName
else:
job.prodUserName = prodUserNameDefault
if PIPELINE_PROCESSINSTANCE is not None:
job.taskID = PIPELINE_PROCESSINSTANCE
if PIPELINE_EXECUTIONNUMBER is not None:
job.attemptNr = PIPELINE_EXECUTIONNUMBER
if PIPELINE_TASK is not None:
job.processingType = PIPELINE_TASK
job.computingSite = site
job.VO = "lsst"
fileOL = FileSpec()
fileOL.lfn = "%s.job.log.tgz" % job.jobName
fileOL.destinationDBlock = job.destinationDBlock
fileOL.destinationSE = job.destinationSE
fileOL.dataset = job.destinationDBlock
fileOL.type = 'log'
job.addFile(fileOL)
s,o = Client.submitJobs([job],srvID=aSrvID)
print(s)
for x in o:
print("PandaID=%s" % x[0])
| PanDAWMS/panda-server | pandaserver/test/lsst/lsstSubmit.py | Python | apache-2.0 | 5,693 | 0.006499 |
#!/usr/bin/env python3
# Copyright (c) 2015-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test BIP 9 soft forks.
Connect to a single node.
regtest lock-in with 108/144 block signalling
activation after a further 144 blocks
mine 2 block and save coinbases for later use
mine 141 blocks to transition from DEFINED to STARTED
mine 100 blocks signalling readiness and 44 not in order to fail to change state this period
mine 108 blocks signalling readiness and 36 blocks not signalling readiness (STARTED->LOCKED_IN)
mine a further 143 blocks (LOCKED_IN)
test that enforcement has not triggered (which triggers ACTIVE)
test that enforcement has triggered
"""
from io import BytesIO
import shutil
import time
import itertools
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, network_thread_start
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_CHECKSEQUENCEVERIFY, OP_DROP
class BIP9SoftForksTest(ComparisonTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.extra_args = [['-whitelist=127.0.0.1']]
self.setup_clean_chain = True
def run_test(self):
self.test = TestManager(self, self.options.tmpdir)
self.test.add_all_connections(self.nodes)
network_thread_start()
self.test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(rawtx))
tx.deserialize(f)
tx.nVersion = 2
return tx
def sign_transaction(self, node, tx):
signresult = node.signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize()))
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(signresult['hex']))
tx.deserialize(f)
return tx
def generate_blocks(self, number, version, test_blocks = []):
for i in range(number):
block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
block.nVersion = version
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
self.height += 1
return test_blocks
def get_bip9_status(self, key):
info = self.nodes[0].getblockchaininfo()
return info['bip9_softforks'][key]
def test_BIP(self, bipName, activated_version, invalidate, invalidatePostSignature, bitno):
assert_equal(self.get_bip9_status(bipName)['status'], 'defined')
assert_equal(self.get_bip9_status(bipName)['since'], 0)
# generate some coins for later
self.coinbase_blocks = self.nodes[0].generate(2)
self.height = 3 # height of the next block to build
self.tip = int("0x" + self.nodes[0].getbestblockhash(), 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = int(time.time())
assert_equal(self.get_bip9_status(bipName)['status'], 'defined')
assert_equal(self.get_bip9_status(bipName)['since'], 0)
tmpl = self.nodes[0].getblocktemplate({})
assert(bipName not in tmpl['rules'])
assert(bipName not in tmpl['vbavailable'])
assert_equal(tmpl['vbrequired'], 0)
assert_equal(tmpl['version'], 0x20000000)
# Test 1
# Advance from DEFINED to STARTED
test_blocks = self.generate_blocks(141, 4)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['status'], 'started')
assert_equal(self.get_bip9_status(bipName)['since'], 144)
assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 0)
assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 0)
tmpl = self.nodes[0].getblocktemplate({})
assert(bipName not in tmpl['rules'])
assert_equal(tmpl['vbavailable'][bipName], bitno)
assert_equal(tmpl['vbrequired'], 0)
assert(tmpl['version'] & activated_version)
# Test 1-A
# check stats after max number of "signalling not" blocks such that LOCKED_IN still possible this period
test_blocks = self.generate_blocks(36, 4, test_blocks) # 0x00000004 (signalling not)
test_blocks = self.generate_blocks(10, activated_version) # 0x20000001 (signalling ready)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 46)
assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 10)
assert_equal(self.get_bip9_status(bipName)['statistics']['possible'], True)
# Test 1-B
# check stats after one additional "signalling not" block -- LOCKED_IN no longer possible this period
test_blocks = self.generate_blocks(1, 4, test_blocks) # 0x00000004 (signalling not)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 47)
assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 10)
assert_equal(self.get_bip9_status(bipName)['statistics']['possible'], False)
# Test 1-C
# finish period with "ready" blocks, but soft fork will still fail to advance to LOCKED_IN
test_blocks = self.generate_blocks(97, activated_version) # 0x20000001 (signalling ready)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 0)
assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 0)
assert_equal(self.get_bip9_status(bipName)['statistics']['possible'], True)
assert_equal(self.get_bip9_status(bipName)['status'], 'started')
# Test 2
# Fail to achieve LOCKED_IN 100 out of 144 signal bit 1
# using a variety of bits to simulate multiple parallel softforks
test_blocks = self.generate_blocks(50, activated_version) # 0x20000001 (signalling ready)
test_blocks = self.generate_blocks(20, 4, test_blocks) # 0x00000004 (signalling not)
test_blocks = self.generate_blocks(50, activated_version, test_blocks) # 0x20000101 (signalling ready)
test_blocks = self.generate_blocks(24, 4, test_blocks) # 0x20010000 (signalling not)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['status'], 'started')
assert_equal(self.get_bip9_status(bipName)['since'], 144)
assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 0)
assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 0)
tmpl = self.nodes[0].getblocktemplate({})
assert(bipName not in tmpl['rules'])
assert_equal(tmpl['vbavailable'][bipName], bitno)
assert_equal(tmpl['vbrequired'], 0)
assert(tmpl['version'] & activated_version)
# Test 3
# 108 out of 144 signal bit 1 to achieve LOCKED_IN
# using a variety of bits to simulate multiple parallel softforks
test_blocks = self.generate_blocks(57, activated_version) # 0x20000001 (signalling ready)
test_blocks = self.generate_blocks(26, 4, test_blocks) # 0x00000004 (signalling not)
test_blocks = self.generate_blocks(50, activated_version, test_blocks) # 0x20000101 (signalling ready)
test_blocks = self.generate_blocks(10, 4, test_blocks) # 0x20010000 (signalling not)
yield TestInstance(test_blocks, sync_every_block=False)
# check counting stats and "possible" flag before last block of this period achieves LOCKED_IN...
assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 143)
assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 107)
assert_equal(self.get_bip9_status(bipName)['statistics']['possible'], True)
assert_equal(self.get_bip9_status(bipName)['status'], 'started')
# ...continue with Test 3
test_blocks = self.generate_blocks(1, activated_version) # 0x20000001 (signalling ready)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['status'], 'locked_in')
assert_equal(self.get_bip9_status(bipName)['since'], 576)
tmpl = self.nodes[0].getblocktemplate({})
assert(bipName not in tmpl['rules'])
# Test 4
# 143 more version 536870913 blocks (waiting period-1)
test_blocks = self.generate_blocks(143, 4)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['status'], 'locked_in')
assert_equal(self.get_bip9_status(bipName)['since'], 576)
tmpl = self.nodes[0].getblocktemplate({})
assert(bipName not in tmpl['rules'])
# Test 5
# Check that the new rule is enforced
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
invalidate(spendtx)
spendtx = self.sign_transaction(self.nodes[0], spendtx)
spendtx.rehash()
invalidatePostSignature(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
block.nVersion = activated_version
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
self.height += 1
yield TestInstance([[block, True]])
assert_equal(self.get_bip9_status(bipName)['status'], 'active')
assert_equal(self.get_bip9_status(bipName)['since'], 720)
tmpl = self.nodes[0].getblocktemplate({})
assert(bipName in tmpl['rules'])
assert(bipName not in tmpl['vbavailable'])
assert_equal(tmpl['vbrequired'], 0)
assert(not (tmpl['version'] & (1 << bitno)))
# Test 6
# Check that the new sequence lock rules are enforced
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
invalidate(spendtx)
spendtx = self.sign_transaction(self.nodes[0], spendtx)
spendtx.rehash()
invalidatePostSignature(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
block.nVersion = 5
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
# Restart all
self.test.clear_all_connections()
self.stop_nodes()
self.nodes = []
shutil.rmtree(self.options.tmpdir + "/node0")
self.setup_chain()
self.setup_network()
self.test.add_all_connections(self.nodes)
network_thread_start()
self.test.p2p_connections[0].wait_for_verack()
def get_tests(self):
for test in itertools.chain(
self.test_BIP('csv', 0x20000001, self.sequence_lock_invalidate, self.donothing, 0),
self.test_BIP('csv', 0x20000001, self.mtp_invalidate, self.donothing, 0),
self.test_BIP('csv', 0x20000001, self.donothing, self.csv_invalidate, 0)
):
yield test
def donothing(self, tx):
return
def csv_invalidate(self, tx):
"""Modify the signature in vin 0 of the tx to fail CSV
Prepends -1 CSV DROP in the scriptSig itself.
"""
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_CHECKSEQUENCEVERIFY, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
def sequence_lock_invalidate(self, tx):
"""Modify the nSequence to make it fails once sequence lock rule is
activated (high timespan).
"""
tx.vin[0].nSequence = 0x00FFFFFF
tx.nLockTime = 0
def mtp_invalidate(self, tx):
"""Modify the nLockTime to make it fails once MTP rule is activated."""
# Disable Sequence lock, Activate nLockTime
tx.vin[0].nSequence = 0x90FFFFFF
tx.nLockTime = self.last_block_time
if __name__ == '__main__':
BIP9SoftForksTest().main()
| globaltoken/globaltoken | test/functional/feature_bip9_softforks.py | Python | mit | 12,919 | 0.004722 |
from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserLogin(ModelForm):
class Meta:
model = User
fields = ['username', 'password']
class UserRegister(UserCreationForm):
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
class Meta:
model = User
fields = ['username']
def save(self, commit=True):
user = super(UserRegister, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name'],
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
class UserProfile(ModelForm):
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name']
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self.fields["username"].disabled = True
self.fields["email"].disabled = True
| GAngelov5/Sportvendor | sportvendor/sportvendor/users/forms.py | Python | gpl-2.0 | 1,164 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.