repo_name stringlengths 5 100 | ref stringlengths 12 67 | path stringlengths 4 244 | copies stringlengths 1 8 | content stringlengths 0 1.05M ⌀ |
|---|---|---|---|---|
saleemjaveds/https-github.com-openstack-nova | refs/heads/master | nova/console/manager.py | 12 | # Copyright (c) 2010 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.
"""Console Proxy Service."""
import socket
from oslo.config import cfg
from oslo import messaging
from nova.compute import rpcapi as compute_rpcapi
from nova import exception
from nova import manager
from nova.openstack.common import importutils
from nova.openstack.common import log as logging
from nova import utils
console_manager_opts = [
cfg.StrOpt('console_driver',
default='nova.console.xvp.XVPConsoleProxy',
help='Driver to use for the console proxy'),
cfg.BoolOpt('stub_compute',
default=False,
help='Stub calls to compute worker for tests'),
cfg.StrOpt('console_public_hostname',
default=socket.gethostname(),
help='Publicly visible name for this console host'),
]
CONF = cfg.CONF
CONF.register_opts(console_manager_opts)
LOG = logging.getLogger(__name__)
class ConsoleProxyManager(manager.Manager):
"""Sets up and tears down any console proxy connections.
Needed for accessing instance consoles securely.
"""
target = messaging.Target(version='2.0')
def __init__(self, console_driver=None, *args, **kwargs):
if not console_driver:
console_driver = CONF.console_driver
self.driver = importutils.import_object(console_driver)
super(ConsoleProxyManager, self).__init__(service_name='console',
*args, **kwargs)
self.driver.host = self.host
self.compute_rpcapi = compute_rpcapi.ComputeAPI()
def init_host(self):
self.driver.init_host()
def add_console(self, context, instance_id):
instance = self.db.instance_get(context, instance_id)
host = instance['host']
name = instance['name']
pool = self._get_pool_for_instance_host(context, host)
try:
console = self.db.console_get_by_pool_instance(context,
pool['id'],
instance['uuid'])
except exception.NotFound:
LOG.debug('Adding console', instance=instance)
password = utils.generate_password(8)
port = self.driver.get_port(context)
console_data = {'instance_name': name,
'instance_uuid': instance['uuid'],
'password': password,
'pool_id': pool['id']}
if port:
console_data['port'] = port
console = self.db.console_create(context, console_data)
self.driver.setup_console(context, console)
return console['id']
def remove_console(self, context, console_id):
try:
console = self.db.console_get(context, console_id)
except exception.NotFound:
LOG.debug('Tried to remove non-existent console '
'%(console_id)s.',
{'console_id': console_id})
return
self.db.console_delete(context, console_id)
self.driver.teardown_console(context, console)
def _get_pool_for_instance_host(self, context, instance_host):
context = context.elevated()
console_type = self.driver.console_type
try:
pool = self.db.console_pool_get_by_host_type(context,
instance_host,
self.host,
console_type)
except exception.NotFound:
# NOTE(mdragon): Right now, the only place this info exists is the
# compute worker's flagfile, at least for
# xenserver. Thus we ned to ask.
if CONF.stub_compute:
pool_info = {'address': '127.0.0.1',
'username': 'test',
'password': '1234pass'}
else:
pool_info = self.compute_rpcapi.get_console_pool_info(context,
console_type, instance_host)
pool_info['password'] = self.driver.fix_pool_password(
pool_info['password'])
pool_info['host'] = self.host
pool_info['public_hostname'] = CONF.console_public_hostname
pool_info['console_type'] = self.driver.console_type
pool_info['compute_host'] = instance_host
pool = self.db.console_pool_create(context, pool_info)
return pool
|
dch312/scipy | refs/heads/master | scipy/weave/vtk_spec.py | 100 | """
VTK type converter.
This module handles conversion between VTK C++ and VTK Python objects
so that one can write inline C++ code to manipulate VTK Python
objects. It requires that you have VTK and the VTK-Python wrappers
installed. It has been tested with VTK 4.0 and above. You will need
to call inline with include_dirs, library_dirs and often even
libraries appropriately set for this to work without errors.
Sometimes you might need to include additional headers.
Distributed under the SciPy License.
Authors:
Prabhu Ramachandran <prabhu@aero.iitm.ernet.in>
Eric Jones <eric@enthought.com>
"""
from __future__ import absolute_import, print_function
from .c_spec import common_base_converter
vtk_py_to_c_template = \
"""
class %(type_name)s_handler
{
public:
%(c_type)s convert_to_%(type_name)s(PyObject* py_obj, const char* name)
{
%(c_type)s vtk_ptr = (%(c_type)s) vtkPythonGetPointerFromObject(py_obj, "%(type_name)s");
if (!vtk_ptr)
handle_conversion_error(py_obj,"%(type_name)s", name);
%(inc_ref_count)s
return vtk_ptr;
}
%(c_type)s py_to_%(type_name)s(PyObject* py_obj, const char* name)
{
%(c_type)s vtk_ptr = (%(c_type)s) vtkPythonGetPointerFromObject(py_obj, "%(type_name)s");
if (!vtk_ptr)
handle_bad_type(py_obj,"%(type_name)s", name);
%(inc_ref_count)s
return vtk_ptr;
}
};
%(type_name)s_handler x__%(type_name)s_handler = %(type_name)s_handler();
#define convert_to_%(type_name)s(py_obj,name) \\
x__%(type_name)s_handler.convert_to_%(type_name)s(py_obj,name)
#define py_to_%(type_name)s(py_obj,name) \\
x__%(type_name)s_handler.py_to_%(type_name)s(py_obj,name)
"""
vtk_c_to_py_template = \
"""
PyObject* %(type_name)s_to_py(vtkObjectBase* obj)
{
return vtkPythonGetObjectFromPointer(obj);
}
"""
class vtk_converter(common_base_converter):
def __init__(self,class_name="undefined"):
self.class_name = class_name
common_base_converter.__init__(self)
def init_info(self):
common_base_converter.init_info(self)
# These are generated on the fly instead of defined at
# the class level.
self.type_name = self.class_name
self.c_type = self.class_name + "*"
self.return_type = self.c_type
self.to_c_return = None # not used
self.check_func = None # not used
hdr = self.class_name + ".h"
# Remember that you need both the quotes!
self.headers.extend(['"vtkPythonUtil.h"', '"vtkObject.h"',
'"%s"' % hdr])
# self.include_dirs.extend(vtk_inc)
# self.define_macros.append(('SOME_VARIABLE', '1'))
# self.library_dirs.extend(vtk_lib)
self.libraries.extend(['vtkCommonPython', 'vtkCommon'])
# self.support_code.append(common_info.swig_support_code)
def type_match(self,value):
is_match = 0
try:
if value.IsA('vtkObject'):
is_match = 1
except AttributeError:
pass
return is_match
def generate_build_info(self):
if self.class_name != "undefined":
res = common_base_converter.generate_build_info(self)
else:
# if there isn't a class_name, we don't want the
# we don't want the support_code to be included
from . import base_info
res = base_info.base_info()
return res
def py_to_c_code(self):
return vtk_py_to_c_template % self.template_vars()
def c_to_py_code(self):
return vtk_c_to_py_template % self.template_vars()
def type_spec(self,name,value):
# factory
class_name = value.__class__.__name__
new_spec = self.__class__(class_name)
new_spec.name = name
return new_spec
def __cmp__(self,other):
# only works for equal
res = -1
try:
res = cmp(self.name,other.name) or \
cmp(self.__class__, other.__class__) or \
cmp(self.class_name, other.class_name) or \
cmp(self.type_name,other.type_name)
except:
pass
return res
|
Ballz0fSteel/Umeko | refs/heads/master | lib/youtube_dl/extractor/aljazeera.py | 47 | from __future__ import unicode_literals
from .common import InfoExtractor
class AlJazeeraIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?aljazeera\.com/(?:programmes|video)/.*?/(?P<id>[^/]+)\.html'
_TESTS = [{
'url': 'http://www.aljazeera.com/programmes/the-slum/2014/08/deliverance-201482883754237240.html',
'info_dict': {
'id': '3792260579001',
'ext': 'mp4',
'title': 'The Slum - Episode 1: Deliverance',
'description': 'As a birth attendant advocating for family planning, Remy is on the frontline of Tondo\'s battle with overcrowding.',
'uploader_id': '665003303001',
'timestamp': 1411116829,
'upload_date': '20140919',
},
'add_ie': ['BrightcoveNew'],
'skip': 'Not accessible from Travis CI server',
}, {
'url': 'http://www.aljazeera.com/video/news/2017/05/sierra-leone-709-carat-diamond-auctioned-170511100111930.html',
'only_matching': True,
}]
BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/665003303001/default_default/index.html?videoId=%s'
def _real_extract(self, url):
program_name = self._match_id(url)
webpage = self._download_webpage(url, program_name)
brightcove_id = self._search_regex(
r'RenderPagesVideo\(\'(.+?)\'', webpage, 'brightcove id')
return self.url_result(self.BRIGHTCOVE_URL_TEMPLATE % brightcove_id, 'BrightcoveNew', brightcove_id)
|
mapr/hue | refs/heads/hue-3.9.0-mapr | desktop/core/ext-py/pycrypto-2.6.1/lib/Crypto/Cipher/PKCS1_OAEP.py | 123 | # -*- coding: utf-8 -*-
#
# Cipher/PKCS1_OAEP.py : PKCS#1 OAEP
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""RSA encryption protocol according to PKCS#1 OAEP
See RFC3447__ or the `original RSA Labs specification`__ .
This scheme is more properly called ``RSAES-OAEP``.
As an example, a sender may encrypt a message in this way:
>>> from Crypto.Cipher import PKCS1_OAEP
>>> from Crypto.PublicKey import RSA
>>>
>>> message = 'To be encrypted'
>>> key = RSA.importKey(open('pubkey.der').read())
>>> cipher = PKCS1_OAEP.new(key)
>>> ciphertext = cipher.encrypt(message)
At the receiver side, decryption can be done using the private part of
the RSA key:
>>> key = RSA.importKey(open('privkey.der').read())
>>> cipher = PKCS1_OAP.new(key)
>>> message = cipher.decrypt(ciphertext)
:undocumented: __revision__, __package__
.. __: http://www.ietf.org/rfc/rfc3447.txt
.. __: http://www.rsa.com/rsalabs/node.asp?id=2125.
"""
from __future__ import nested_scopes
__revision__ = "$Id$"
__all__ = [ 'new', 'PKCS1OAEP_Cipher' ]
import Crypto.Signature.PKCS1_PSS
import Crypto.Hash.SHA
from Crypto.Util.py3compat import *
import Crypto.Util.number
from Crypto.Util.number import ceil_div
from Crypto.Util.strxor import strxor
class PKCS1OAEP_Cipher:
"""This cipher can perform PKCS#1 v1.5 OAEP encryption or decryption."""
def __init__(self, key, hashAlgo, mgfunc, label):
"""Initialize this PKCS#1 OAEP cipher object.
:Parameters:
key : an RSA key object
If a private half is given, both encryption and decryption are possible.
If a public half is given, only encryption is possible.
hashAlgo : hash object
The hash function to use. This can be a module under `Crypto.Hash`
or an existing hash object created from any of such modules. If not specified,
`Crypto.Hash.SHA` (that is, SHA-1) is used.
mgfunc : callable
A mask generation function that accepts two parameters: a string to
use as seed, and the lenth of the mask to generate, in bytes.
If not specified, the standard MGF1 is used (a safe choice).
label : string
A label to apply to this particular encryption. If not specified,
an empty string is used. Specifying a label does not improve
security.
:attention: Modify the mask generation function only if you know what you are doing.
Sender and receiver must use the same one.
"""
self._key = key
if hashAlgo:
self._hashObj = hashAlgo
else:
self._hashObj = Crypto.Hash.SHA
if mgfunc:
self._mgf = mgfunc
else:
self._mgf = lambda x,y: Crypto.Signature.PKCS1_PSS.MGF1(x,y,self._hashObj)
self._label = label
def can_encrypt(self):
"""Return True/1 if this cipher object can be used for encryption."""
return self._key.can_encrypt()
def can_decrypt(self):
"""Return True/1 if this cipher object can be used for decryption."""
return self._key.can_decrypt()
def encrypt(self, message):
"""Produce the PKCS#1 OAEP encryption of a message.
This function is named ``RSAES-OAEP-ENCRYPT``, and is specified in
section 7.1.1 of RFC3447.
:Parameters:
message : string
The message to encrypt, also known as plaintext. It can be of
variable length, but not longer than the RSA modulus (in bytes)
minus 2, minus twice the hash output size.
:Return: A string, the ciphertext in which the message is encrypted.
It is as long as the RSA modulus (in bytes).
:Raise ValueError:
If the RSA key length is not sufficiently long to deal with the given
message.
"""
# TODO: Verify the key is RSA
randFunc = self._key._randfunc
# See 7.1.1 in RFC3447
modBits = Crypto.Util.number.size(self._key.n)
k = ceil_div(modBits,8) # Convert from bits to bytes
hLen = self._hashObj.digest_size
mLen = len(message)
# Step 1b
ps_len = k-mLen-2*hLen-2
if ps_len<0:
raise ValueError("Plaintext is too long.")
# Step 2a
lHash = self._hashObj.new(self._label).digest()
# Step 2b
ps = bchr(0x00)*ps_len
# Step 2c
db = lHash + ps + bchr(0x01) + message
# Step 2d
ros = randFunc(hLen)
# Step 2e
dbMask = self._mgf(ros, k-hLen-1)
# Step 2f
maskedDB = strxor(db, dbMask)
# Step 2g
seedMask = self._mgf(maskedDB, hLen)
# Step 2h
maskedSeed = strxor(ros, seedMask)
# Step 2i
em = bchr(0x00) + maskedSeed + maskedDB
# Step 3a (OS2IP), step 3b (RSAEP), part of step 3c (I2OSP)
m = self._key.encrypt(em, 0)[0]
# Complete step 3c (I2OSP)
c = bchr(0x00)*(k-len(m)) + m
return c
def decrypt(self, ct):
"""Decrypt a PKCS#1 OAEP ciphertext.
This function is named ``RSAES-OAEP-DECRYPT``, and is specified in
section 7.1.2 of RFC3447.
:Parameters:
ct : string
The ciphertext that contains the message to recover.
:Return: A string, the original message.
:Raise ValueError:
If the ciphertext length is incorrect, or if the decryption does not
succeed.
:Raise TypeError:
If the RSA key has no private half.
"""
# TODO: Verify the key is RSA
# See 7.1.2 in RFC3447
modBits = Crypto.Util.number.size(self._key.n)
k = ceil_div(modBits,8) # Convert from bits to bytes
hLen = self._hashObj.digest_size
# Step 1b and 1c
if len(ct) != k or k<hLen+2:
raise ValueError("Ciphertext with incorrect length.")
# Step 2a (O2SIP), 2b (RSADP), and part of 2c (I2OSP)
m = self._key.decrypt(ct)
# Complete step 2c (I2OSP)
em = bchr(0x00)*(k-len(m)) + m
# Step 3a
lHash = self._hashObj.new(self._label).digest()
# Step 3b
y = em[0]
# y must be 0, but we MUST NOT check it here in order not to
# allow attacks like Manger's (http://dl.acm.org/citation.cfm?id=704143)
maskedSeed = em[1:hLen+1]
maskedDB = em[hLen+1:]
# Step 3c
seedMask = self._mgf(maskedDB, hLen)
# Step 3d
seed = strxor(maskedSeed, seedMask)
# Step 3e
dbMask = self._mgf(seed, k-hLen-1)
# Step 3f
db = strxor(maskedDB, dbMask)
# Step 3g
valid = 1
one = db[hLen:].find(bchr(0x01))
lHash1 = db[:hLen]
if lHash1!=lHash:
valid = 0
if one<0:
valid = 0
if bord(y)!=0:
valid = 0
if not valid:
raise ValueError("Incorrect decryption.")
# Step 4
return db[hLen+one+1:]
def new(key, hashAlgo=None, mgfunc=None, label=b('')):
"""Return a cipher object `PKCS1OAEP_Cipher` that can be used to perform PKCS#1 OAEP encryption or decryption.
:Parameters:
key : RSA key object
The key to use to encrypt or decrypt the message. This is a `Crypto.PublicKey.RSA` object.
Decryption is only possible if *key* is a private RSA key.
hashAlgo : hash object
The hash function to use. This can be a module under `Crypto.Hash`
or an existing hash object created from any of such modules. If not specified,
`Crypto.Hash.SHA` (that is, SHA-1) is used.
mgfunc : callable
A mask generation function that accepts two parameters: a string to
use as seed, and the lenth of the mask to generate, in bytes.
If not specified, the standard MGF1 is used (a safe choice).
label : string
A label to apply to this particular encryption. If not specified,
an empty string is used. Specifying a label does not improve
security.
:attention: Modify the mask generation function only if you know what you are doing.
Sender and receiver must use the same one.
"""
return PKCS1OAEP_Cipher(key, hashAlgo, mgfunc, label)
|
Lilykos/invenio | refs/heads/master | invenio/ext/principal/wrappers.py | 17 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Define action class and registry."""
import six
from werkzeug.local import LocalProxy
class ActionsRegistry(type):
"""Action registry."""
__actions_registry__ = []
def __init__(cls, name, bases, dct):
"""Register cls to actions registry."""
if not dct.get('__prototype__', False):
cls.__actions_registry__.append(cls)
super(ActionsRegistry, cls).__init__(name, bases, dct)
@property
def name(cls):
"""Return lowercased action class name."""
return cls.__name__.lower()
@property
def description(cls):
"""Return stripped class documentation string."""
return cls.__doc__.strip()
actions = LocalProxy(lambda: ActionsRegistry.__actions_registry__)
"""List of registered actions."""
@six.add_metaclass(ActionsRegistry)
class Action(object):
"""Default action description."""
__prototype__ = True # do not register this class
allowedkeywords = []
optional = False
|
apanju/odoo | refs/heads/8.0 | openerp/tools/win32.py | 457 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import locale
import time
import datetime
if not hasattr(locale, 'D_FMT'):
locale.D_FMT = 1
if not hasattr(locale, 'T_FMT'):
locale.T_FMT = 2
if not hasattr(locale, 'nl_langinfo'):
def nl_langinfo(param):
if param == locale.D_FMT:
val = time.strptime('30/12/2004', '%d/%m/%Y')
dt = datetime.datetime(*val[:-2])
format_date = dt.strftime('%x')
for x, y in [('30', '%d'),('12', '%m'),('2004','%Y'),('04', '%Y')]:
format_date = format_date.replace(x, y)
return format_date
if param == locale.T_FMT:
val = time.strptime('13:24:56', '%H:%M:%S')
dt = datetime.datetime(*val[:-2])
format_time = dt.strftime('%X')
for x, y in [('13', '%H'),('24', '%M'),('56','%S')]:
format_time = format_time.replace(x, y)
return format_time
locale.nl_langinfo = nl_langinfo
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
OSSHealth/ghdata | refs/heads/master | augur/housekeeper.py | 1 | #SPDX-License-Identifier: MIT
"""
Keeps data up to date
"""
import coloredlogs
from copy import deepcopy
import logging, os, time, requests
import logging.config
from multiprocessing import Process, get_start_method
from sqlalchemy.ext.automap import automap_base
import sqlalchemy as s
import pandas as pd
from sqlalchemy import MetaData
from augur.logging import AugurLogging
from urllib.parse import urlparse
import warnings
warnings.filterwarnings('ignore')
logger = logging.getLogger(__name__)
class Housekeeper:
def __init__(self, broker, augur_app):
logger.info("Booting housekeeper")
self._processes = []
self.augur_logging = augur_app.logging
self.jobs = deepcopy(augur_app.config.get_value("Housekeeper", "jobs"))
self.update_redirects = deepcopy(augur_app.config.get_value("Housekeeper", "update_redirects"))
self.broker_host = augur_app.config.get_value("Server", "host")
self.broker_port = augur_app.config.get_value("Server", "port")
self.broker = broker
self.db = augur_app.database
self.helper_db = augur_app.operations_database
helper_metadata = MetaData()
helper_metadata.reflect(self.helper_db, only=['worker_job'])
HelperBase = automap_base(metadata=helper_metadata)
HelperBase.prepare()
self.job_table = HelperBase.classes.worker_job.__table__
repoUrlSQL = s.sql.text("""
SELECT repo_git FROM repo
""")
rs = pd.read_sql(repoUrlSQL, self.db, params={})
all_repos = rs['repo_git'].values.tolist()
# If enabled, updates all redirects of repositories
# and organizations urls for configured repo_group_id
self.update_url_redirects()
# List of tasks that need periodic updates
self.schedule_updates()
def schedule_updates(self):
"""
Starts update processes
"""
self.prep_jobs()
self.augur_logging.initialize_housekeeper_logging_listener()
logger.info("Scheduling update processes")
for job in self.jobs:
process = Process(target=self.updater_process, name=job["model"], args=(self.broker_host, self.broker_port, self.broker, job, (self.augur_logging.housekeeper_job_config, self.augur_logging.get_config())))
self._processes.append(process)
process.start()
@staticmethod
def updater_process(broker_host, broker_port, broker, job, logging_config):
"""
Controls a given plugin's update process
"""
logging.config.dictConfig(logging_config[0])
logger = logging.getLogger(f"augur.jobs.{job['model']}")
coloredlogs.install(level=logging_config[1]["log_level"], logger=logger, fmt=logging_config[1]["format_string"])
if logging_config[1]["quiet"]:
logger.disabled
if 'repo_group_id' in job:
repo_group_id = job['repo_group_id']
logger.info('Housekeeper spawned {} model updater process for repo group id {}'.format(job['model'], repo_group_id))
else:
repo_group_id = None
logger.info('Housekeeper spawned {} model updater process for repo ids {}'.format(job['model'], job['repo_ids']))
try:
compatible_worker_found = False
# Waiting for compatible worker
while True:
if not compatible_worker_found:
for worker in list(broker._getvalue().keys()):
if job['model'] in broker[worker]['models'] and job['given'] in broker[worker]['given']:
compatible_worker_found = True
time.sleep(3)
continue
logger.info("Housekeeper recognized that the broker has a worker that " +
"can handle the {} model... beginning to distribute maintained tasks".format(job['model']))
while True:
logger.info('Housekeeper updating {} model with given {}...'.format(
job['model'], job['given'][0]))
if job['given'][0] == 'git_url' or job['given'][0] == 'github_url':
for repo in job['repos']:
if job['given'][0] == 'github_url' and 'github.com' not in repo['repo_git']:
continue
given_key = 'git_url' if job['given'][0] == 'git_url' else 'github_url'
task = {
"job_type": job['job_type'] if 'job_type' in job else 'MAINTAIN',
"models": [job['model']],
"display_name": "{} model for url: {}".format(job['model'], repo['repo_git']),
"given": {}
}
task['given'][given_key] = repo['repo_git']
if "focused_task" in repo:
task["focused_task"] = repo['focused_task']
try:
requests.post('http://{}:{}/api/unstable/task'.format(
broker_host,broker_port), json=task, timeout=10)
except Exception as e:
logger.error("Error encountered: {}".format(e))
logger.debug(task)
time.sleep(15)
elif job['given'][0] == 'repo_group':
task = {
"job_type": job['job_type'] if 'job_type' in job else 'MAINTAIN',
"models": [job['model']],
"display_name": "{} model for repo group id: {}".format(job['model'], repo_group_id),
"given": {
"repo_group": job['repos']
}
}
try:
requests.post('http://{}:{}/api/unstable/task'.format(
broker_host,broker_port), json=task, timeout=10)
except Exception as e:
logger.error("Error encountered: {}".format(e))
logger.info("Housekeeper finished sending {} tasks to the broker for it to distribute to your worker(s)".format(len(job['repos'])))
time.sleep(job['delay'])
except KeyboardInterrupt as e:
pass
def join_updates(self):
"""
Join to the update processes
"""
for process in self._processes:
logger.debug(f"Joining {process.name} update process")
process.join()
def shutdown_updates(self):
"""
Ends all running update processes
"""
for process in self._processes:
# logger.debug(f"Terminating {process.name} update process")
process.terminate()
def prep_jobs(self):
logger.info("Preparing housekeeper jobs")
for job in self.jobs:
if 'repo_group_id' in job or 'repo_ids' in job:
# If RG id is 0 then it just means to query all repos
where_and = 'AND' if job['model'] == 'issues' and 'repo_group_id' in job else 'WHERE'
where_condition = '{} repo_group_id = {}'.format(where_and, job['repo_group_id']
) if 'repo_group_id' in job and job['repo_group_id'] != 0 else '{} repo.repo_id IN ({})'.format(
where_and, ",".join(str(id) for id in job['repo_ids'])) if 'repo_ids' in job else ''
repo_url_sql = s.sql.text("""
SELECT repo.repo_id, repo.repo_git, pull_request_count, collected_pr_count,
(repo_info.pull_request_count - pr_count.collected_pr_count) AS pull_requests_missing
FROM augur_data.repo LEFT OUTER JOIN (
SELECT count(*) AS collected_pr_count, repo_id
FROM pull_requests GROUP BY repo_id ) pr_count
ON pr_count.repo_id = repo.repo_id LEFT OUTER JOIN (
SELECT repo_id, MAX ( data_collection_date ) AS last_collected
FROM augur_data.repo_info
GROUP BY repo_id) recent_info
ON recent_info.repo_id = pr_count.repo_id LEFT OUTER JOIN repo_info
ON recent_info.repo_id = repo_info.repo_id
AND repo_info.data_collection_date = recent_info.last_collected
{}
GROUP BY repo.repo_id, repo_info.pull_request_count, pr_count.collected_pr_count
ORDER BY pull_requests_missing DESC NULLS LAST
""".format(where_condition)) if job['model'] == 'pull_requests' else s.sql.text("""
SELECT
*
FROM
(
( SELECT repo_git, repo.repo_id, issues_enabled, COUNT ( * ) AS meta_count
FROM repo left outer join repo_info on repo.repo_id = repo_info.repo_id
--WHERE issues_enabled = 'true'
GROUP BY repo.repo_id, issues_enabled
ORDER BY repo.repo_id ) zz
LEFT OUTER JOIN (
SELECT repo.repo_id,
repo.repo_name,
b.issues_count,
d.repo_id AS issue_repo_id,
e.last_collected,
COUNT ( * ) AS issues_collected_count,
(
b.issues_count - COUNT ( * )) AS issues_missing,
ABS (
CAST (( COUNT ( * )) AS DOUBLE PRECISION ) / CAST ( b.issues_count + 1 AS DOUBLE PRECISION )) AS ratio_abs,
(
CAST (( COUNT ( * )) AS DOUBLE PRECISION ) / CAST ( b.issues_count + 1 AS DOUBLE PRECISION )) AS ratio_issues
FROM
augur_data.repo left outer join
augur_data.pull_requests d on d.repo_id = repo.repo_id left outer join
augur_data.repo_info b on d.repo_id = b.repo_id left outer join
( SELECT repo_id, MAX ( data_collection_date ) AS last_collected FROM augur_data.repo_info GROUP BY repo_id ORDER BY repo_id ) e
on e.repo_id = d.repo_id and b.data_collection_date = e.last_collected
WHERE d.pull_request_id IS NULL
{}
GROUP BY
repo.repo_id,
d.repo_id,
b.issues_count,
e.last_collected
ORDER BY ratio_abs
) yy ON zz.repo_id = yy.repo_id
) D
ORDER BY ratio_abs NULLS FIRST
""".format(where_condition)) if job['model'] == 'issues' and 'repo_group_id' in job else s.sql.text("""
SELECT repo_git, repo_id FROM repo {} ORDER BY repo_id ASC
""".format(where_condition)) if 'order' not in job else s.sql.text("""
SELECT repo_git, repo.repo_id, count(*) as commit_count
FROM augur_data.repo left outer join augur_data.commits
on repo.repo_id = commits.repo_id
{}
group by repo.repo_id ORDER BY commit_count {}
""".format(where_condition, job['order']))
reorganized_repos = pd.read_sql(repo_url_sql, self.db, params={})
if len(reorganized_repos) == 0:
logger.warning("Trying to send tasks for repo group, but the repo group does not contain any repos: {}".format(repo_url_sql))
job['repos'] = []
continue
if 'starting_repo_id' in job:
last_id = job['starting_repo_id']
else:
repoIdSQL = s.sql.text("""
SELECT since_id_str FROM worker_job
WHERE job_model = '{}'
""".format(job['model']))
job_df = pd.read_sql(repoIdSQL, self.helper_db, params={})
# If there is no job tuple found, insert one
if len(job_df) == 0:
job_tuple = {
'job_model': job['model'],
'oauth_id': 0
}
result = self.helper_db.execute(self.job_table.insert().values(job_tuple))
logger.debug("No job tuple for {} model was found, so one was inserted into the job table: {}".format(job['model'], job_tuple))
# If a last id is not recorded, start from beginning of repos
# (first id is not necessarily 0)
try:
last_id = int(job_df.iloc[0]['since_id_str'])
except:
last_id = 0
jobHistorySQL = s.sql.text("""
SELECT max(history_id) AS history_id, status FROM worker_history
GROUP BY status
LIMIT 1
""")
history_df = pd.read_sql(jobHistorySQL, self.helper_db, params={})
finishing_task = False
if len(history_df.index) != 0:
if history_df.iloc[0]['status'] == 'Stopped':
self.history_id = int(history_df.iloc[0]['history_id'])
finishing_task = True
# Rearrange repos so the one after the last one that
# was completed will be ran first (if prioritized ordering is not available/enabled)
if job['model'] not in ['issues', 'pull_requests']:
before_repos = reorganized_repos.loc[reorganized_repos['repo_id'].astype(int) < last_id]
after_repos = reorganized_repos.loc[reorganized_repos['repo_id'].astype(int) >= last_id]
reorganized_repos = after_repos.append(before_repos)
if 'all_focused' in job:
reorganized_repos['focused_task'] = job['all_focused']
reorganized_repos = reorganized_repos.to_dict('records')
if finishing_task:
reorganized_repos[0]['focused_task'] = 1
job['repos'] = reorganized_repos
elif 'repo_id' in job:
job['repo_group_id'] = None
repoUrlSQL = s.sql.text("""
SELECT repo_git, repo_id FROM repo WHERE repo_id = {}
""".format(job['repo_id']))
rs = pd.read_sql(repoUrlSQL, self.db, params={})
if 'all_focused' in job:
rs['focused_task'] = job['all_focused']
rs = rs.to_dict('records')
job['repos'] = rs
# time.sleep(120)
def update_url_redirects(self):
if 'switch' in self.update_redirects and self.update_redirects['switch'] == 1 and 'repo_group_id' in self.update_redirects:
repos_urls = self.get_repos_urls(self.update_redirects['repo_group_id'])
if self.update_redirects['repo_group_id'] == 0:
logger.info("Repo Group Set to Zero for URL Updates")
else:
logger.info("Repo Group ID Specified.")
for url in repos_urls:
url = self.trim_git_suffix(url)
if url:
r = requests.get(url)
check_for_update = url != r.url
if check_for_update:
self.update_repo_url(url, r.url, self.update_redirects['repo_group_id'])
def trim_git_suffix(self, url):
if url.endswith('.git'):
url = url.replace('.git', '')
elif url.endswith('.github.io'):
url = url.replace('.github.io', '')
elif url.endswith('/.github'):
url = ''
return url
def get_repos_urls(self, repo_group_id):
if self.update_redirects['repo_group_id'] == 0:
repos_sql = s.sql.text("""
SELECT repo_git FROM repo
""")
logger.info("repo_group_id is 0")
else:
repos_sql = s.sql.text("""
SELECT repo_git FROM repo
WHERE repo_group_id = ':repo_group_id'
""")
repos = pd.read_sql(repos_sql, self.db, params={'repo_group_id': repo_group_id})
if len(repos) == 0:
logger.info("Did not find any repositories stored in augur_database for repo_group_id {}\n".format(repo_group_id))
return repos['repo_git']
def update_repo_url(self, old_url, new_url, repo_group_id):
trimmed_new_url = self.trim_git_suffix(new_url)
if not trimmed_new_url:
logger.info("New repo is named .github : {} ... skipping \n".format(new_url))
return
else:
new_url = trimmed_new_url
old_repo_path = Housekeeper.parseRepoName(old_url)
old_repo_group_name = old_repo_path[0]
new_repo_path = Housekeeper.parseRepoName(new_url)
new_repo_group_name = new_repo_path[0]
if old_repo_group_name != new_repo_group_name:
# verifying the old repo group name is available in the database
old_rg_name_sql = s.sql.text("""
SELECT rg_name FROM repo_groups
WHERE repo_group_id = ':repo_group_id'
""")
old_rg_name_from_DB = pd.read_sql(old_rg_name_sql, self.db, params={'repo_group_id': repo_group_id})
if len(old_rg_name_from_DB['rg_name']) > 0 and old_repo_group_name != old_rg_name_from_DB['rg_name'][0]:
logger.info("Incoming old repo group name doesn't match the DB record for repo_group_id {} . Incoming name: {} DB record: {} \n".format(repo_group_id, old_repo_group_name, old_rg_name_from_DB['rg_name'][0]))
# checking if the new repo group name already exists and
# inserting it in repo_groups if it doesn't
rg_name_check_sql = s.sql.text("""
SELECT rg_name, repo_group_id FROM repo_groups
WHERE rg_name = :new_repo_group_name
""")
rg_name_check = pd.read_sql(rg_name_check_sql, self.db, params={'new_repo_group_name': new_repo_group_name})
new_rg_name_already_exists = len(rg_name_check['rg_name']) > 0
if new_rg_name_already_exists:
new_repo_group_id = rg_name_check['repo_group_id'][0]
else:
insert_sql = s.sql.text("""
INSERT INTO repo_groups("rg_name", "rg_description", "rg_website", "rg_recache", "rg_last_modified", "rg_type", "tool_source", "tool_version", "data_source", "data_collection_date")
VALUES (:new_repo_group_name, '', '', 0, CURRENT_TIMESTAMP, 'Unknown', 'Loaded by user', '1.0', 'Git', CURRENT_TIMESTAMP) RETURNING repo_group_id;
""")
new_repo_group_id = self.db.execute(insert_sql, new_repo_group_name=new_repo_group_name).fetchone()[0]
logger.info("Inserted repo group {} with id {}\n".format(new_repo_group_name, new_repo_group_id))
new_repo_group_id = '%s' % new_repo_group_id
update_sql = s.sql.text("""
UPDATE repo SET repo_git = :new_url, repo_path = NULL, repo_name = NULL, repo_status = 'New', repo_group_id = :new_repo_group_id
WHERE repo_git = :old_url
""")
self.db.execute(update_sql, new_url=new_url, new_repo_group_id=new_repo_group_id, old_url=old_url)
logger.info("Updated repo url from {} to {}\n".format(new_url, old_url))
else:
update_sql = s.sql.text("""
UPDATE repo SET repo_git = :new_url, repo_path = NULL, repo_name = NULL, repo_status = 'New'
WHERE repo_git = :old_url
""")
self.db.execute(update_sql, new_url=new_url, old_url=old_url)
logger.info("Updated repo url from {} to {}\n".format(new_url, old_url))
def parseRepoName(repo_url):
path = urlparse(repo_url).path
parts = path.split('/')
return parts[1:]
|
ProfessionalIT/professionalit-webiste | refs/heads/master | sdk/google_appengine/lib/django-1.2/django/conf/project_template/manage.py | 2072 | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
|
pozar87/apts | refs/heads/master | apts/constants/objecttablelabels.py | 1 | class ObjectTableLabels:
# Altitude
ALTITUDE = 'Altitude'
# Transit time
TRANSIT = 'Transit'
# Right ascension
RA = 'RA'
# Declination
DEC = 'Dec'
# Name
NAME = 'Name'
# Ephem obeject
EPHEM = 'Ephem'
# Magnitude
MAGNITUDE = 'Magnitude'
# Distance
DISTANCE = 'Distance'
# Phase
PHASE = 'Phase'
# Apparent size
SIZE = 'Size'
# Elongation
ELONGATION = 'Elongation'
# Rising
RISING = 'Rising'
# Setting
SETTING = 'Setting'
MESSIER = 'Messier'
WIDTH = 'Width' |
buqing2009/MissionPlanner | refs/heads/master | Lib/site-packages/numpy/testing/tests/test_decorators.py | 86 | import numpy as np
from numpy.testing import *
from numpy.testing.noseclasses import KnownFailureTest
import nose
def test_slow():
@dec.slow
def slow_func(x,y,z):
pass
assert(slow_func.slow)
def test_setastest():
@dec.setastest()
def f_default(a):
pass
@dec.setastest(True)
def f_istest(a):
pass
@dec.setastest(False)
def f_isnottest(a):
pass
assert(f_default.__test__)
assert(f_istest.__test__)
assert(not f_isnottest.__test__)
class DidntSkipException(Exception):
pass
def test_skip_functions_hardcoded():
@dec.skipif(True)
def f1(x):
raise DidntSkipException
try:
f1('a')
except DidntSkipException:
raise Exception('Failed to skip')
except nose.SkipTest:
pass
@dec.skipif(False)
def f2(x):
raise DidntSkipException
try:
f2('a')
except DidntSkipException:
pass
except nose.SkipTest:
raise Exception('Skipped when not expected to')
def test_skip_functions_callable():
def skip_tester():
return skip_flag == 'skip me!'
@dec.skipif(skip_tester)
def f1(x):
raise DidntSkipException
try:
skip_flag = 'skip me!'
f1('a')
except DidntSkipException:
raise Exception('Failed to skip')
except nose.SkipTest:
pass
@dec.skipif(skip_tester)
def f2(x):
raise DidntSkipException
try:
skip_flag = 'five is right out!'
f2('a')
except DidntSkipException:
pass
except nose.SkipTest:
raise Exception('Skipped when not expected to')
def test_skip_generators_hardcoded():
@dec.knownfailureif(True, "This test is known to fail")
def g1(x):
for i in xrange(x):
yield i
try:
for j in g1(10):
pass
except KnownFailureTest:
pass
else:
raise Exception('Failed to mark as known failure')
@dec.knownfailureif(False, "This test is NOT known to fail")
def g2(x):
for i in xrange(x):
yield i
raise DidntSkipException('FAIL')
try:
for j in g2(10):
pass
except KnownFailureTest:
raise Exception('Marked incorretly as known failure')
except DidntSkipException:
pass
def test_skip_generators_callable():
def skip_tester():
return skip_flag == 'skip me!'
@dec.knownfailureif(skip_tester, "This test is known to fail")
def g1(x):
for i in xrange(x):
yield i
try:
skip_flag = 'skip me!'
for j in g1(10):
pass
except KnownFailureTest:
pass
else:
raise Exception('Failed to mark as known failure')
@dec.knownfailureif(skip_tester, "This test is NOT known to fail")
def g2(x):
for i in xrange(x):
yield i
raise DidntSkipException('FAIL')
try:
skip_flag = 'do not skip'
for j in g2(10):
pass
except KnownFailureTest:
raise Exception('Marked incorretly as known failure')
except DidntSkipException:
pass
if __name__ == '__main__':
run_module_suite()
|
benspaulding/django | refs/heads/master | tests/regressiontests/null_fk/__init__.py | 12133432 | |
ignaci0/pyafipws.web2py-app | refs/heads/master | modules/__init__.py | 12133432 | |
cmbclh/vnpy1.7 | refs/heads/master | build/lib/vnpy/trader/language/chinese/__init__.py | 12133432 | |
Lujeni/ansible | refs/heads/devel | lib/ansible/module_utils/network/iosxr/argspec/facts/__init__.py | 12133432 | |
samithaj/headphones | refs/heads/master | lib/requests/packages/urllib3/contrib/__init__.py | 12133432 | |
CanalTP/navitia | refs/heads/dev | source/jormungandr/tests/klaxit_routing_tests.py | 1 | # -*- coding: utf-8 -*-
# Copyright (c) 2001-2017, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive locomotion way of traveling!
#
# LICENCE: This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, unicode_literals, division
import pytest
from jormungandr.tests.utils_test import MockResponse
from tests.check_utils import get_not_null, get_links_dict
from tests.tests_mechanism import dataset, NewDefaultScenarioAbstractTestFixture
DUMMY_KLAXIT_FEED_PUBLISHER = {'id': '42', 'name': '42', 'license': 'I dunno', 'url': 'http://w.tf'}
MOCKED_INSTANCE_CONF = {
'scenario': 'new_default',
'instance_config': {
'ridesharing': [
{
"args": {
"service_url": "http://wtf",
"api_key": "key",
"network": "Super Covoit",
"feed_publisher": DUMMY_KLAXIT_FEED_PUBLISHER,
"rating_scale_min": 0,
"rating_scale_max": 5,
},
"class": "jormungandr.scenarios.ridesharing.klaxit.Klaxit",
}
]
},
}
KLAXIT_RESPONSE = [
{
"departureToPickupWalkingDistance": 475,
"departureToPickupWalkingPolyline": "keliHiyoMqAxCjFvHIRdA~BjE`G",
"departureToPickupWalkingTime": 174,
"distance": 18869,
"driver": {"alias": "Mohamed M", "grade": 5, "picture": "https://driver.png"},
"driverArrivalLat": 0.00071865,
"driverArrivalLng": 0.00188646,
"driverDepartureDate": 1601988149,
"driverDepartureLat": 0.0000898312,
"driverDepartureLng": 0.0000898312,
"dropoffToArrivalWalkingDistance": 1237,
"dropoffToArrivalWalkingPolyline": "{deiHq~nMh@hBrNaK?u@jKdFrBnAvMw@fEjCXu@[]`CkG",
"dropoffToArrivalWalkingTime": 76,
"duration": 1301,
"id": "fe08fceb-03a2-4dc6-8ba4-b422c1256227",
"journeyPolyline": "svr_H}fyC{@g@[[o@u@Qc@[sBMm@Qe@[g@e@k@aBuAIKOI?AACCEEAIDAN@DMf@GZ@d@QbBOzAy@xFAJ]r@IPOQm@a@wDoB?C?ECIGAGD?@m@c@uCiCcCgBEKsB}AK?IGs@i@m@y@Wm@oAoDaB_EYk@y@kAyDmG_A}Ao@}AQeAIcAOiBUw@Yc@WWUKiAe@USSQKOACAIEQMOOGO@MHKPGd@CZK^INq@`A}@lAmEhGcIdLcPlUqGdJ[XE?K@KFK\AH?DQl@aFjH{IlMoCdEgBrCkG~JqDtFcLpPyb@pn@aHdKoHjKcAtAQLSLC?G@KFMZAVI`@eCvDoAnBs@rAe@~@{@pBg@tAk@fBcEpO{FpTeL~a@wBfIoAjEy@fBK?KDOPIXCd@F`@UxAY`AQn@o@zCwAxFiAbEMd@cCdJ_BxF[t@GAE?KDILAP@RHLBB]`Bw@fDYbAQn@gBrGqAnFq@rCyIj\qH|XMNe@vAq@dCcFpRaF|QuFbT}CdL{CbLgE`PiCjJcApDYWoB{@gBw@_EiBiAi@[KwBmAiF}CuAm@Q@}A{@sFeDkDqBsIwEkYmOyJ_FgEmBiEeB_EuAkCw@aCm@{AWaCa@aCYcF[yCG_D@iEPaDXeANmBZsCl@wDdA_DhAcEfBiHjDoLzF}h@fWoKbFcAh@]E_Cl@s@L_AJqA?}@IkAOcAUaA[y@e@{@i@SISA_@Fa@T]XYd@Gn@R|@X~@p@dAn@|@h@z@?B?D@HJNB?@?|@~ArE`IPl@t@tAt@hBdAvCzBxFj@tHn@|Iz@zL~@nMf@hGLb@F`@TzCJpB^@VERSN]@a@Ae@|By@bA[dCw@NKpDiAxAc@|@U",
"price": {"amount": 1.0, "type": "PAYING"},
"type": "PLANNED",
"webUrl": "https://klaxitlines.com",
}
]
def mock_klaxit(_, params):
return MockResponse(KLAXIT_RESPONSE, 200)
@pytest.fixture(scope="function", autouse=True)
def mock_http_klaxit(monkeypatch):
monkeypatch.setattr('jormungandr.scenarios.ridesharing.klaxit.Klaxit._call_service', mock_klaxit)
@dataset({'main_routing_test': MOCKED_INSTANCE_CONF})
class TestKlaxit(NewDefaultScenarioAbstractTestFixture):
"""
Integration test with Klaxit VIA API
Note: '&forbidden_uris[]=PM' used to avoid line 'PM' and it's vj=vjPB in /journeys
"""
def test_basic_ride_sharing(self):
"""
test ridesharing_jouneys details
"""
q = (
"journeys?from=0.0000898312;0.0000898312&to=0.00188646;0.00071865&datetime=20120614T075500&"
"first_section_mode[]={first}&last_section_mode[]={last}&forbidden_uris[]=PM".format(
first='ridesharing', last='walking'
)
)
response = self.query_region(q)
self.is_valid_journey_response(response, q, check_journey_links=False)
# Check links: ridesharing_journeys
links = get_links_dict(response)
link = links["ridesharing_journeys"]
assert link["rel"] == "ridesharing_journeys"
assert link["type"] == "ridesharing_journeys"
assert link["href"].startswith("http://localhost/v1/coverage/main_routing_test/")
journeys = get_not_null(response, 'journeys')
assert len(journeys) == 1
tickets = response.get('tickets')
assert len(tickets) == 1
assert tickets[0].get('cost').get('currency') == 'centime'
assert tickets[0].get('cost').get('value') == '100.0'
ticket = tickets[0]
ridesharing_kraken = journeys[0]
assert 'ridesharing' in ridesharing_kraken['tags']
assert 'non_pt' in ridesharing_kraken['tags']
assert ridesharing_kraken.get('type') == 'best'
assert ridesharing_kraken.get('durations').get('ridesharing') > 0
assert ridesharing_kraken.get('durations').get('total') == ridesharing_kraken['durations']['ridesharing']
assert ridesharing_kraken.get('distances').get('ridesharing') > 0
rs_sections = ridesharing_kraken.get('sections')
assert len(rs_sections) == 1
assert rs_sections[0].get('mode') == 'ridesharing'
assert rs_sections[0].get('type') == 'street_network'
sections = ridesharing_kraken.get('sections')
rs_journeys = sections[0].get('ridesharing_journeys')
assert len(rs_journeys) == 1
assert rs_journeys[0].get('distances').get('ridesharing') == 18869
assert rs_journeys[0].get('durations').get('walking') == 250
assert rs_journeys[0].get('durations').get('ridesharing') == 1301
assert 'ridesharing' in rs_journeys[0].get('tags')
rsj_sections = rs_journeys[0].get('sections')
assert len(rsj_sections) == 3
assert rsj_sections[0].get('type') == 'street_network'
assert rsj_sections[0].get('mode') == 'walking'
assert rsj_sections[0].get('duration') == 174
assert rsj_sections[0].get('departure_date_time') == '20201006T123935'
assert rsj_sections[0].get('arrival_date_time') == '20201006T124229'
assert rsj_sections[1].get('type') == 'ridesharing'
assert rsj_sections[1].get('duration') == 1301
assert rsj_sections[1].get('departure_date_time') == '20201006T124229'
assert rsj_sections[1].get('arrival_date_time') == '20201006T130410'
assert rsj_sections[1].get('geojson').get('coordinates')[0] == [0.0000898312, 0.0000898312]
assert rsj_sections[1].get('geojson').get('coordinates')[2] == [0.78995, 47.28728]
# ridesharing duration comes from the offer
rsj_info = rsj_sections[1].get('ridesharing_informations')
assert rsj_info.get('network') == 'Super Covoit'
assert rsj_info.get('operator') == 'klaxit'
# Driver and ratings
assert rsj_info.get('driver').get('alias') == "Mohamed M"
assert rsj_info.get('driver').get('image') == "https://driver.png"
assert rsj_info.get('driver').get('gender') is None
assert rsj_info.get('driver').get('rating').get('value') == 5.0
assert rsj_info.get('driver').get('rating').get('scale_min') == 0.0
assert rsj_info.get('driver').get('rating').get('scale_max') == 5.0
assert rsj_info.get('driver').get('rating').get('count') == 0.0
rsj_links = rsj_sections[1].get('links')
assert len(rsj_links) == 2
assert rsj_links[0].get('rel') == 'ridesharing_ad'
assert rsj_links[0].get('type') == 'ridesharing_ad'
assert rsj_links[1].get('rel') == 'tickets'
assert rsj_links[1].get('type') == 'ticket'
assert rsj_links[1].get('id') == ticket['id']
assert ticket['links'][0]['id'] == rsj_sections[1]['id']
assert rs_journeys[0].get('fare').get('total').get('value') == tickets[0].get('cost').get('value')
assert rsj_sections[2].get('type') == 'street_network'
assert rsj_sections[2].get('mode') == 'walking'
assert rsj_sections[2].get('duration') == 76
assert rsj_sections[2].get('departure_date_time') == '20201006T130410'
assert rsj_sections[2].get('arrival_date_time') == '20201006T130526'
fps = response['feed_publishers']
assert len(fps) == 2
def equals_to_dummy_fp(fp):
return fp == DUMMY_KLAXIT_FEED_PUBLISHER
assert any(equals_to_dummy_fp(fp) for fp in fps)
def test_filter_ridesharing_with_parameter(self):
"""
test ridesharing_jouneys details
"""
q = (
"journeys?from=0.0000898312;0.0000898312&to=0.00188646;0.00071865&datetime=20120614T075500&"
"first_section_mode[]={rs}&first_section_mode[]={walk}&last_section_mode[]={walk}&forbidden_uris[]=PM&"
"debug=true".format(rs='ridesharing', walk='walking')
)
response = self.query_region(q)
self.is_valid_journey_response(response, q, check_journey_links=False)
# Ridesharing journey is eliminated as the duration is inferior to default min_ridesharing(600)
# Note: ridesharing journey is eliminated only if walking option is added for that fallback
journeys = get_not_null(response, 'journeys')
assert len(journeys) == 3
ridesharing_journey = next((journey for journey in journeys if "ridesharing" in journey['tags']), None)
assert ridesharing_journey is not None
assert ridesharing_journey['durations']['ridesharing'] == 43
assert "deleted_because_too_short_heavy_mode_fallback" in ridesharing_journey['tags']
# Modify min_ridesharing value from 600 to 40 (< 43) not to eliminate ridesharing journey
q += "&_min_ridesharing=40"
response = self.query_region(q)
self.is_valid_journey_response(response, q, check_journey_links=False)
journeys = get_not_null(response, 'journeys')
assert len(journeys) == 3
ridesharing_journey = next((journey for journey in journeys if "ridesharing" in journey['tags']), None)
assert ridesharing_journey is not None
assert "deleted_because_too_short_heavy_mode_fallback" not in ridesharing_journey['tags']
|
yewang15215/django | refs/heads/master | tests/postgres_tests/models.py | 14 | from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from .fields import (
ArrayField, BigIntegerRangeField, CITextField, DateRangeField,
DateTimeRangeField, FloatRangeField, HStoreField, IntegerRangeField,
JSONField, SearchVectorField,
)
class Tag(object):
def __init__(self, tag_id):
self.tag_id = tag_id
def __eq__(self, other):
return isinstance(other, Tag) and self.tag_id == other.tag_id
class TagField(models.SmallIntegerField):
def from_db_value(self, value, expression, connection, context):
if value is None:
return value
return Tag(int(value))
def to_python(self, value):
if isinstance(value, Tag):
return value
if value is None:
return value
return Tag(int(value))
def get_prep_value(self, value):
return value.tag_id
class PostgreSQLModel(models.Model):
class Meta:
abstract = True
required_db_vendor = 'postgresql'
class IntegerArrayModel(PostgreSQLModel):
field = ArrayField(models.IntegerField(), default=[], blank=True)
class NullableIntegerArrayModel(PostgreSQLModel):
field = ArrayField(models.IntegerField(), blank=True, null=True)
class CharArrayModel(PostgreSQLModel):
field = ArrayField(models.CharField(max_length=10))
class DateTimeArrayModel(PostgreSQLModel):
datetimes = ArrayField(models.DateTimeField())
dates = ArrayField(models.DateField())
times = ArrayField(models.TimeField())
class NestedIntegerArrayModel(PostgreSQLModel):
field = ArrayField(ArrayField(models.IntegerField()))
class OtherTypesArrayModel(PostgreSQLModel):
ips = ArrayField(models.GenericIPAddressField())
uuids = ArrayField(models.UUIDField())
decimals = ArrayField(models.DecimalField(max_digits=5, decimal_places=2))
tags = ArrayField(TagField(), blank=True, null=True)
class HStoreModel(PostgreSQLModel):
field = HStoreField(blank=True, null=True)
class CharFieldModel(models.Model):
field = models.CharField(max_length=16)
class TextFieldModel(models.Model):
field = models.TextField()
def __str__(self):
return self.field
# Scene/Character/Line models are used to test full text search. They're
# populated with content from Monty Python and the Holy Grail.
class Scene(models.Model):
scene = models.CharField(max_length=255)
setting = models.CharField(max_length=255)
def __str__(self):
return self.scene
class Character(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class CITextTestModel(PostgreSQLModel):
name = CITextField(primary_key=True, max_length=255)
def __str__(self):
return self.name
class Line(PostgreSQLModel):
scene = models.ForeignKey('Scene', models.CASCADE)
character = models.ForeignKey('Character', models.CASCADE)
dialogue = models.TextField(blank=True, null=True)
dialogue_search_vector = SearchVectorField(blank=True, null=True)
dialogue_config = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.dialogue or ''
class RangesModel(PostgreSQLModel):
ints = IntegerRangeField(blank=True, null=True)
bigints = BigIntegerRangeField(blank=True, null=True)
floats = FloatRangeField(blank=True, null=True)
timestamps = DateTimeRangeField(blank=True, null=True)
dates = DateRangeField(blank=True, null=True)
class RangeLookupsModel(PostgreSQLModel):
parent = models.ForeignKey(RangesModel, models.SET_NULL, blank=True, null=True)
integer = models.IntegerField(blank=True, null=True)
big_integer = models.BigIntegerField(blank=True, null=True)
float = models.FloatField(blank=True, null=True)
timestamp = models.DateTimeField(blank=True, null=True)
date = models.DateField(blank=True, null=True)
class JSONModel(models.Model):
field = JSONField(blank=True, null=True)
field_custom = JSONField(blank=True, null=True, encoder=DjangoJSONEncoder)
class Meta:
required_db_features = ['has_jsonb_datatype']
class ArrayFieldSubclass(ArrayField):
def __init__(self, *args, **kwargs):
super(ArrayFieldSubclass, self).__init__(models.IntegerField())
class AggregateTestModel(models.Model):
"""
To test postgres-specific general aggregation functions
"""
char_field = models.CharField(max_length=30, blank=True)
integer_field = models.IntegerField(null=True)
boolean_field = models.NullBooleanField()
class StatTestModel(models.Model):
"""
To test postgres-specific aggregation functions for statistics
"""
int1 = models.IntegerField()
int2 = models.IntegerField()
related_field = models.ForeignKey(AggregateTestModel, models.SET_NULL, null=True)
class NowTestModel(models.Model):
when = models.DateTimeField(null=True, default=None)
|
devGregA/scrapy | refs/heads/master | scrapy/contrib/downloadermiddleware/httpauth.py | 89 | """
HTTP basic auth downloader middleware
See documentation in docs/topics/downloader-middleware.rst
"""
from w3lib.http import basic_auth_header
from scrapy import signals
class HttpAuthMiddleware(object):
"""Set Basic HTTP Authorization header
(http_user and http_pass spider class attributes)"""
@classmethod
def from_crawler(cls, crawler):
o = cls()
crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)
return o
def spider_opened(self, spider):
usr = getattr(spider, 'http_user', '')
pwd = getattr(spider, 'http_pass', '')
if usr or pwd:
self.auth = basic_auth_header(usr, pwd)
def process_request(self, request, spider):
auth = getattr(self, 'auth', None)
if auth and 'Authorization' not in request.headers:
request.headers['Authorization'] = auth
|
mne-tools/mne-tools.github.io | refs/heads/main | 0.14/_downloads/plot_artifacts_correction_ssp.py | 3 | """
.. _tut_artifacts_correct_ssp:
Artifact Correction with SSP
============================
"""
import numpy as np
import mne
from mne.datasets import sample
from mne.preprocessing import compute_proj_ecg, compute_proj_eog
# getting some data ready
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.set_eeg_reference()
raw.pick_types(meg=True, ecg=True, eog=True, stim=True)
##############################################################################
# Compute SSP projections
# -----------------------
projs, events = compute_proj_ecg(raw, n_grad=1, n_mag=1, average=True)
print(projs)
ecg_projs = projs[-2:]
mne.viz.plot_projs_topomap(ecg_projs)
# Now for EOG
projs, events = compute_proj_eog(raw, n_grad=1, n_mag=1, average=True)
print(projs)
eog_projs = projs[-2:]
mne.viz.plot_projs_topomap(eog_projs)
##############################################################################
# Apply SSP projections
# ---------------------
#
# MNE is handling projections at the level of the info,
# so to register them populate the list that you find in the 'proj' field
raw.info['projs'] += eog_projs + ecg_projs
#############################################################################
# Yes this was it. Now MNE will apply the projs on demand at any later stage,
# so watch out for proj parmeters in functions or to it explicitly
# with the ``.apply_proj`` method
#############################################################################
# Demonstrate SSP cleaning on some evoked data
# --------------------------------------------
events = mne.find_events(raw, stim_channel='STI 014')
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
# this can be highly data dependent
event_id = {'auditory/left': 1}
epochs_no_proj = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5,
proj=False, baseline=(None, 0), reject=reject)
epochs_no_proj.average().plot(spatial_colors=True)
epochs_proj = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5, proj=True,
baseline=(None, 0), reject=reject)
epochs_proj.average().plot(spatial_colors=True)
##############################################################################
# Looks cool right? It is however often not clear how many components you
# should take and unfortunately this can have bad consequences as can be seen
# interactively using the delayed SSP mode:
evoked = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5,
proj='delayed', baseline=(None, 0),
reject=reject).average()
# set time instants in seconds (from 50 to 150ms in a step of 10ms)
times = np.arange(0.05, 0.15, 0.01)
evoked.plot_topomap(times, proj='interactive')
##############################################################################
# now you should see checkboxes. Remove a few SSP and see how the auditory
# pattern suddenly drops off
|
mldbai/mldb | refs/heads/master | testing/MLDB-1328-join_empty_dataset_test.py | 1 | #
# MLDB-1328-join_empty_dataset_test.py
# Mich, 2016-01-28
# Copyright (c) 2016 mldb.ai inc. All rights reserved.
#
# Tools for the plugins and their tests.
import unittest
from mldb import mldb
def log(thing):
mldb.log(str(thing))
def perform(*args, **kwargs):
res = mldb.perform(*args, **kwargs)
assert res['statusCode'] in [200, 201], str(res)
return res
class JoinEmptyDatasetTest(unittest.TestCase):
def test_it(self):
perform('PUT', '/v1/datasets/ds', [], {
'type' : 'sparse.mutable'
})
perform('POST', '/v1/datasets/ds/commit', [], {})
qry = "SELECT uid, count(1) AS size FROM ds GROUP BY uid"
res = perform('GET', '/v1/query', [['q', qry]])
assert res['response'] == '[]'
if __name__ == '__main__':
if mldb.script.args:
assert type(mldb.script.args) is list
argv = ['python'] + mldb.script.args
else:
argv = None
res = unittest.main(exit=False, argv=argv).result
log(res)
got_err = False
for err in res.errors + res.failures:
got_err = True
log(str(err[0]) + "\n" + err[1])
if not got_err:
request.set_return("success")
|
phobson/bokeh | refs/heads/master | examples/plotting/file/graphs.py | 5 | from bokeh.plotting import figure, gridplot, GridSpec, output_file, show
import networkx as nx
from sympy import *
def graph_draw(g, layout=nx.circular_layout, node_color="white", text_color="black"):
pos = layout(g)
labels = [ str(v) for v in g.nodes() ]
vx, vy = zip(*[ pos[v] for v in g.nodes() ])
xs, ys = [], []
for (a, b) in g.edges():
x0, y0 = pos[a]
x1, y1 = pos[b]
xs.append([x0, x1])
ys.append([y0, y1])
f = figure(width=300, height=300,
x_axis_type=None, y_axis_type=None,
outline_line_color=None,
tools=[], toolbar_location=None)
f.multi_line(xs, ys, line_color="black")
f.circle(vx, vy, size=16, line_color="black", fill_color=node_color)
f.text(vx, vy, text=labels, text_color=text_color,
text_font_size="10px", text_align="center", text_baseline="middle")
return f
V = range(1, 12+1)
E = [(1,2),(2,3),(1,4),(1,6),(1,12),(2,5),(2,7),(3,8),(3,10),(4,11),(4,9),(5,6),
(6,7),(7,8),(8,9),(9,10),(10,11),(11,12),(5,12),(5,9),(6,10),(7,11),(8,12)]
g = nx.Graph()
g.add_nodes_from(V)
g.add_edges_from(E)
Vx = [ Symbol('x%d' % i) for i in V ]
Ex = [ (Vx[i-1], Vx[j-1]) for i, j in E ]
F3 = [ xi**3 - 1 for xi in Vx ]
Fg = [ xi**2 + xi*xj + xj**2 for xi, xj in Ex ]
Fx = F3 + Fg
colors = symbols('red,green,blue')
roots_of_unity = roots(Dummy()**3 - 1, multiple=True)
color_map = dict(zip(roots_of_unity, colors))
solutions = solve(Fx, *Vx)
colorings = [ [ color_map.get(zeta) for zeta in solution ] for solution in solutions ]
n, ncols = len(colorings), 2
gs = GridSpec((n + 1)//ncols, 1 + ncols)
gs[0, 0] = graph_draw(g)
for i, coloring in enumerate(colorings):
f = graph_draw(g, node_color=[ str(color) for color in coloring ], text_color="white")
gs[i//ncols, 1 + i%ncols] = f
plot = gridplot(gs, toolbar_location=None)
output_file("graphs.html", title="Graph k-coloring with computer algebra")
show(plot)
|
ryfeus/lambda-packs | refs/heads/master | Tensorflow_LightGBM_Scipy_nightly/source/scipy/interpolate/fitpack.py | 21 | from __future__ import print_function, division, absolute_import
__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde',
'bisplrep', 'bisplev', 'insert', 'splder', 'splantider']
import warnings
import numpy as np
from ._fitpack_impl import bisplrep, bisplev, dblint
from . import _fitpack_impl as _impl
from ._bsplines import BSpline
def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None,
full_output=0, nest=None, per=0, quiet=1):
"""
Find the B-spline representation of an N-dimensional curve.
Given a list of N rank-1 arrays, `x`, which represent a curve in
N-dimensional space parametrized by `u`, find a smooth approximating
spline curve g(`u`). Uses the FORTRAN routine parcur from FITPACK.
Parameters
----------
x : array_like
A list of sample vector arrays representing the curve.
w : array_like, optional
Strictly positive rank-1 array of weights the same length as `x[0]`.
The weights are used in computing the weighted least-squares spline
fit. If the errors in the `x` values have standard-deviation given by
the vector d, then `w` should be 1/d. Default is ``ones(len(x[0]))``.
u : array_like, optional
An array of parameter values. If not given, these values are
calculated automatically as ``M = len(x[0])``, where
v[0] = 0
v[i] = v[i-1] + distance(`x[i]`, `x[i-1]`)
u[i] = v[i] / v[M-1]
ub, ue : int, optional
The end-points of the parameters interval. Defaults to
u[0] and u[-1].
k : int, optional
Degree of the spline. Cubic splines are recommended.
Even values of `k` should be avoided especially with a small s-value.
``1 <= k <= 5``, default is 3.
task : int, optional
If task==0 (default), find t and c for a given smoothing factor, s.
If task==1, find t and c for another value of the smoothing factor, s.
There must have been a previous call with task=0 or task=1
for the same set of data.
If task=-1 find the weighted least square spline for a given set of
knots, t.
s : float, optional
A smoothing condition. The amount of smoothness is determined by
satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s``,
where g(x) is the smoothed interpolation of (x,y). The user can
use `s` to control the trade-off between closeness and smoothness
of fit. Larger `s` means more smoothing while smaller values of `s`
indicate less smoothing. Recommended values of `s` depend on the
weights, w. If the weights represent the inverse of the
standard-deviation of y, then a good `s` value should be found in
the range ``(m-sqrt(2*m),m+sqrt(2*m))``, where m is the number of
data points in x, y, and w.
t : int, optional
The knots needed for task=-1.
full_output : int, optional
If non-zero, then return optional outputs.
nest : int, optional
An over-estimate of the total number of knots of the spline to
help in determining the storage space. By default nest=m/2.
Always large enough is nest=m+k+1.
per : int, optional
If non-zero, data points are considered periodic with period
``x[m-1] - x[0]`` and a smooth periodic spline approximation is
returned. Values of ``y[m-1]`` and ``w[m-1]`` are not used.
quiet : int, optional
Non-zero to suppress messages.
This parameter is deprecated; use standard Python warning filters
instead.
Returns
-------
tck : tuple
(t,c,k) a tuple containing the vector of knots, the B-spline
coefficients, and the degree of the spline.
u : array
An array of the values of the parameter.
fp : float
The weighted sum of squared residuals of the spline approximation.
ier : int
An integer flag about splrep success. Success is indicated
if ier<=0. If ier in [1,2,3] an error occurred but was not raised.
Otherwise an error is raised.
msg : str
A message corresponding to the integer flag, ier.
See Also
--------
splrep, splev, sproot, spalde, splint,
bisplrep, bisplev
UnivariateSpline, BivariateSpline
BSpline
make_interp_spline
Notes
-----
See `splev` for evaluation of the spline and its derivatives.
The number of dimensions N must be smaller than 11.
The number of coefficients in the `c` array is ``k+1`` less then the number
of knots, ``len(t)``. This is in contrast with `splrep`, which zero-pads
the array of coefficients to have the same length as the array of knots.
These additional coefficients are ignored by evaluation routines, `splev`
and `BSpline`.
References
----------
.. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
parametric splines, Computer Graphics and Image Processing",
20 (1982) 171-184.
.. [2] P. Dierckx, "Algorithms for smoothing data with periodic and
parametric splines", report tw55, Dept. Computer Science,
K.U.Leuven, 1981.
.. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs on
Numerical Analysis, Oxford University Press, 1993.
Examples
--------
Generate a discretization of a limacon curve in the polar coordinates:
>>> phi = np.linspace(0, 2.*np.pi, 40)
>>> r = 0.5 + np.cos(phi) # polar coords
>>> x, y = r * np.cos(phi), r * np.sin(phi) # convert to cartesian
And interpolate:
>>> from scipy.interpolate import splprep, splev
>>> tck, u = splprep([x, y], s=0)
>>> new_points = splev(u, tck)
Notice that (i) we force interpolation by using `s=0`,
(ii) the parameterization, ``u``, is generated automatically.
Now plot the result:
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> ax.plot(x, y, 'ro')
>>> ax.plot(new_points[0], new_points[1], 'r-')
>>> plt.show()
"""
res = _impl.splprep(x, w, u, ub, ue, k, task, s, t, full_output, nest, per,
quiet)
return res
def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None,
full_output=0, per=0, quiet=1):
"""
Find the B-spline representation of 1-D curve.
Given the set of data points ``(x[i], y[i])`` determine a smooth spline
approximation of degree k on the interval ``xb <= x <= xe``.
Parameters
----------
x, y : array_like
The data points defining a curve y = f(x).
w : array_like, optional
Strictly positive rank-1 array of weights the same length as x and y.
The weights are used in computing the weighted least-squares spline
fit. If the errors in the y values have standard-deviation given by the
vector d, then w should be 1/d. Default is ones(len(x)).
xb, xe : float, optional
The interval to fit. If None, these default to x[0] and x[-1]
respectively.
k : int, optional
The degree of the spline fit. It is recommended to use cubic splines.
Even values of k should be avoided especially with small s values.
1 <= k <= 5
task : {1, 0, -1}, optional
If task==0 find t and c for a given smoothing factor, s.
If task==1 find t and c for another value of the smoothing factor, s.
There must have been a previous call with task=0 or task=1 for the same
set of data (t will be stored an used internally)
If task=-1 find the weighted least square spline for a given set of
knots, t. These should be interior knots as knots on the ends will be
added automatically.
s : float, optional
A smoothing condition. The amount of smoothness is determined by
satisfying the conditions: sum((w * (y - g))**2,axis=0) <= s where g(x)
is the smoothed interpolation of (x,y). The user can use s to control
the tradeoff between closeness and smoothness of fit. Larger s means
more smoothing while smaller values of s indicate less smoothing.
Recommended values of s depend on the weights, w. If the weights
represent the inverse of the standard-deviation of y, then a good s
value should be found in the range (m-sqrt(2*m),m+sqrt(2*m)) where m is
the number of datapoints in x, y, and w. default : s=m-sqrt(2*m) if
weights are supplied. s = 0.0 (interpolating) if no weights are
supplied.
t : array_like, optional
The knots needed for task=-1. If given then task is automatically set
to -1.
full_output : bool, optional
If non-zero, then return optional outputs.
per : bool, optional
If non-zero, data points are considered periodic with period x[m-1] -
x[0] and a smooth periodic spline approximation is returned. Values of
y[m-1] and w[m-1] are not used.
quiet : bool, optional
Non-zero to suppress messages.
This parameter is deprecated; use standard Python warning filters
instead.
Returns
-------
tck : tuple
A tuple (t,c,k) containing the vector of knots, the B-spline
coefficients, and the degree of the spline.
fp : array, optional
The weighted sum of squared residuals of the spline approximation.
ier : int, optional
An integer flag about splrep success. Success is indicated if ier<=0.
If ier in [1,2,3] an error occurred but was not raised. Otherwise an
error is raised.
msg : str, optional
A message corresponding to the integer flag, ier.
See Also
--------
UnivariateSpline, BivariateSpline
splprep, splev, sproot, spalde, splint
bisplrep, bisplev
BSpline
make_interp_spline
Notes
-----
See `splev` for evaluation of the spline and its derivatives. Uses the
FORTRAN routine ``curfit`` from FITPACK.
The user is responsible for assuring that the values of `x` are unique.
Otherwise, `splrep` will not return sensible results.
If provided, knots `t` must satisfy the Schoenberg-Whitney conditions,
i.e., there must be a subset of data points ``x[j]`` such that
``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
This routine zero-pads the coefficients array ``c`` to have the same length
as the array of knots ``t`` (the trailing ``k + 1`` coefficients are ignored
by the evaluation routines, `splev` and `BSpline`.) This is in contrast with
`splprep`, which does not zero-pad the coefficients.
References
----------
Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
.. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
integration of experimental data using spline functions",
J.Comp.Appl.Maths 1 (1975) 165-184.
.. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
1286-1304.
.. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
.. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
Numerical Analysis, Oxford University Press, 1993.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from scipy.interpolate import splev, splrep
>>> x = np.linspace(0, 10, 10)
>>> y = np.sin(x)
>>> spl = splrep(x, y)
>>> x2 = np.linspace(0, 10, 200)
>>> y2 = splev(x2, spl)
>>> plt.plot(x, y, 'o', x2, y2)
>>> plt.show()
"""
res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet)
return res
def splev(x, tck, der=0, ext=0):
"""
Evaluate a B-spline or its derivatives.
Given the knots and coefficients of a B-spline representation, evaluate
the value of the smoothing polynomial and its derivatives. This is a
wrapper around the FORTRAN routines splev and splder of FITPACK.
Parameters
----------
x : array_like
An array of points at which to return the value of the smoothed
spline or its derivatives. If `tck` was returned from `splprep`,
then the parameter values, u should be given.
tck : 3-tuple or a BSpline object
If a tuple, then it should be a sequence of length 3 returned by
`splrep` or `splprep` containing the knots, coefficients, and degree
of the spline. (Also see Notes.)
der : int, optional
The order of derivative of the spline to compute (must be less than
or equal to k).
ext : int, optional
Controls the value returned for elements of ``x`` not in the
interval defined by the knot sequence.
* if ext=0, return the extrapolated value.
* if ext=1, return 0
* if ext=2, raise a ValueError
* if ext=3, return the boundary value.
The default value is 0.
Returns
-------
y : ndarray or list of ndarrays
An array of values representing the spline function evaluated at
the points in `x`. If `tck` was returned from `splprep`, then this
is a list of arrays representing the curve in N-dimensional space.
Notes
-----
Manipulating the tck-tuples directly is not recommended. In new code,
prefer using `BSpline` objects.
See Also
--------
splprep, splrep, sproot, spalde, splint
bisplrep, bisplev
BSpline
References
----------
.. [1] C. de Boor, "On calculating with b-splines", J. Approximation
Theory, 6, p.50-62, 1972.
.. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
Applics, 10, p.134-149, 1972.
.. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
on Numerical Analysis, Oxford University Press, 1993.
"""
if isinstance(tck, BSpline):
if tck.c.ndim > 1:
mesg = ("Calling splev() with BSpline objects with c.ndim > 1 is "
"not recommended. Use BSpline.__call__(x) instead.")
warnings.warn(mesg, DeprecationWarning)
# remap the out-of-bounds behavior
try:
extrapolate = {0: True, }[ext]
except KeyError:
raise ValueError("Extrapolation mode %s is not supported "
"by BSpline." % ext)
return tck(x, der, extrapolate=extrapolate)
else:
return _impl.splev(x, tck, der, ext)
def splint(a, b, tck, full_output=0):
"""
Evaluate the definite integral of a B-spline between two given points.
Parameters
----------
a, b : float
The end-points of the integration interval.
tck : tuple or a BSpline instance
If a tuple, then it should be a sequence of length 3, containing the
vector of knots, the B-spline coefficients, and the degree of the
spline (see `splev`).
full_output : int, optional
Non-zero to return optional output.
Returns
-------
integral : float
The resulting integral.
wrk : ndarray
An array containing the integrals of the normalized B-splines
defined on the set of knots.
(Only returned if `full_output` is non-zero)
Notes
-----
`splint` silently assumes that the spline function is zero outside the data
interval (`a`, `b`).
Manipulating the tck-tuples directly is not recommended. In new code,
prefer using the `BSpline` objects.
See Also
--------
splprep, splrep, sproot, spalde, splev
bisplrep, bisplev
BSpline
References
----------
.. [1] P.W. Gaffney, The calculation of indefinite integrals of b-splines",
J. Inst. Maths Applics, 17, p.37-41, 1976.
.. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs
on Numerical Analysis, Oxford University Press, 1993.
"""
if isinstance(tck, BSpline):
if tck.c.ndim > 1:
mesg = ("Calling splint() with BSpline objects with c.ndim > 1 is "
"not recommended. Use BSpline.integrate() instead.")
warnings.warn(mesg, DeprecationWarning)
if full_output != 0:
mesg = ("full_output = %s is not supported. Proceeding as if "
"full_output = 0" % full_output)
return tck.integrate(a, b, extrapolate=False)
else:
return _impl.splint(a, b, tck, full_output)
def sproot(tck, mest=10):
"""
Find the roots of a cubic B-spline.
Given the knots (>=8) and coefficients of a cubic B-spline return the
roots of the spline.
Parameters
----------
tck : tuple or a BSpline object
If a tuple, then it should be a sequence of length 3, containing the
vector of knots, the B-spline coefficients, and the degree of the
spline.
The number of knots must be >= 8, and the degree must be 3.
The knots must be a montonically increasing sequence.
mest : int, optional
An estimate of the number of zeros (Default is 10).
Returns
-------
zeros : ndarray
An array giving the roots of the spline.
Notes
-----
Manipulating the tck-tuples directly is not recommended. In new code,
prefer using the `BSpline` objects.
See also
--------
splprep, splrep, splint, spalde, splev
bisplrep, bisplev
BSpline
References
----------
.. [1] C. de Boor, "On calculating with b-splines", J. Approximation
Theory, 6, p.50-62, 1972.
.. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
Applics, 10, p.134-149, 1972.
.. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
on Numerical Analysis, Oxford University Press, 1993.
"""
if isinstance(tck, BSpline):
if tck.c.ndim > 1:
mesg = ("Calling sproot() with BSpline objects with c.ndim > 1 is "
"not recommended.")
warnings.warn(mesg, DeprecationWarning)
t, c, k = tck.tck
# _impl.sproot expects the interpolation axis to be last, so roll it.
# NB: This transpose is a no-op if c is 1D.
sh = tuple(range(c.ndim))
c = c.transpose(sh[1:] + (0,))
return _impl.sproot((t, c, k), mest)
else:
return _impl.sproot(tck, mest)
def spalde(x, tck):
"""
Evaluate all derivatives of a B-spline.
Given the knots and coefficients of a cubic B-spline compute all
derivatives up to order k at a point (or set of points).
Parameters
----------
x : array_like
A point or a set of points at which to evaluate the derivatives.
Note that ``t(k) <= x <= t(n-k+1)`` must hold for each `x`.
tck : tuple
A tuple ``(t, c, k)``, containing the vector of knots, the B-spline
coefficients, and the degree of the spline (see `splev`).
Returns
-------
results : {ndarray, list of ndarrays}
An array (or a list of arrays) containing all derivatives
up to order k inclusive for each point `x`.
See Also
--------
splprep, splrep, splint, sproot, splev, bisplrep, bisplev,
BSpline
References
----------
.. [1] C. de Boor: On calculating with b-splines, J. Approximation Theory
6 (1972) 50-62.
.. [2] M. G. Cox : The numerical evaluation of b-splines, J. Inst. Maths
applics 10 (1972) 134-149.
.. [3] P. Dierckx : Curve and surface fitting with splines, Monographs on
Numerical Analysis, Oxford University Press, 1993.
"""
if isinstance(tck, BSpline):
raise TypeError("spalde does not accept BSpline instances.")
else:
return _impl.spalde(x, tck)
def insert(x, tck, m=1, per=0):
"""
Insert knots into a B-spline.
Given the knots and coefficients of a B-spline representation, create a
new B-spline with a knot inserted `m` times at point `x`.
This is a wrapper around the FORTRAN routine insert of FITPACK.
Parameters
----------
x (u) : array_like
A 1-D point at which to insert a new knot(s). If `tck` was returned
from ``splprep``, then the parameter values, u should be given.
tck : a `BSpline` instance or a tuple
If tuple, then it is expected to be a tuple (t,c,k) containing
the vector of knots, the B-spline coefficients, and the degree of
the spline.
m : int, optional
The number of times to insert the given knot (its multiplicity).
Default is 1.
per : int, optional
If non-zero, the input spline is considered periodic.
Returns
-------
BSpline instance or a tuple
A new B-spline with knots t, coefficients c, and degree k.
``t(k+1) <= x <= t(n-k)``, where k is the degree of the spline.
In case of a periodic spline (``per != 0``) there must be
either at least k interior knots t(j) satisfying ``t(k+1)<t(j)<=x``
or at least k interior knots t(j) satisfying ``x<=t(j)<t(n-k)``.
A tuple is returned iff the input argument `tck` is a tuple, otherwise
a BSpline object is constructed and returned.
Notes
-----
Based on algorithms from [1]_ and [2]_.
Manipulating the tck-tuples directly is not recommended. In new code,
prefer using the `BSpline` objects.
References
----------
.. [1] W. Boehm, "Inserting new knots into b-spline curves.",
Computer Aided Design, 12, p.199-201, 1980.
.. [2] P. Dierckx, "Curve and surface fitting with splines, Monographs on
Numerical Analysis", Oxford University Press, 1993.
"""
if isinstance(tck, BSpline):
t, c, k = tck.tck
# FITPACK expects the interpolation axis to be last, so roll it over
# NB: if c array is 1D, transposes are no-ops
sh = tuple(range(c.ndim))
c = c.transpose(sh[1:] + (0,))
t_, c_, k_ = _impl.insert(x, (t, c, k), m, per)
# and roll the last axis back
c_ = np.asarray(c_)
c_ = c_.transpose((sh[-1],) + sh[:-1])
return BSpline(t_, c_, k_)
else:
return _impl.insert(x, tck, m, per)
def splder(tck, n=1):
"""
Compute the spline representation of the derivative of a given spline
Parameters
----------
tck : BSpline instance or a tuple of (t, c, k)
Spline whose derivative to compute
n : int, optional
Order of derivative to evaluate. Default: 1
Returns
-------
`BSpline` instance or tuple
Spline of order k2=k-n representing the derivative
of the input spline.
A tuple is returned iff the input argument `tck` is a tuple, otherwise
a BSpline object is constructed and returned.
Notes
-----
.. versionadded:: 0.13.0
See Also
--------
splantider, splev, spalde
BSpline
Examples
--------
This can be used for finding maxima of a curve:
>>> from scipy.interpolate import splrep, splder, sproot
>>> x = np.linspace(0, 10, 70)
>>> y = np.sin(x)
>>> spl = splrep(x, y, k=4)
Now, differentiate the spline and find the zeros of the
derivative. (NB: `sproot` only works for order 3 splines, so we
fit an order 4 spline):
>>> dspl = splder(spl)
>>> sproot(dspl) / np.pi
array([ 0.50000001, 1.5 , 2.49999998])
This agrees well with roots :math:`\\pi/2 + n\\pi` of
:math:`\\cos(x) = \\sin'(x)`.
"""
if isinstance(tck, BSpline):
return tck.derivative(n)
else:
return _impl.splder(tck, n)
def splantider(tck, n=1):
"""
Compute the spline for the antiderivative (integral) of a given spline.
Parameters
----------
tck : BSpline instance or a tuple of (t, c, k)
Spline whose antiderivative to compute
n : int, optional
Order of antiderivative to evaluate. Default: 1
Returns
-------
BSpline instance or a tuple of (t2, c2, k2)
Spline of order k2=k+n representing the antiderivative of the input
spline.
A tuple is returned iff the input argument `tck` is a tuple, otherwise
a BSpline object is constructed and returned.
See Also
--------
splder, splev, spalde
BSpline
Notes
-----
The `splder` function is the inverse operation of this function.
Namely, ``splder(splantider(tck))`` is identical to `tck`, modulo
rounding error.
.. versionadded:: 0.13.0
Examples
--------
>>> from scipy.interpolate import splrep, splder, splantider, splev
>>> x = np.linspace(0, np.pi/2, 70)
>>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
>>> spl = splrep(x, y)
The derivative is the inverse operation of the antiderivative,
although some floating point error accumulates:
>>> splev(1.7, spl), splev(1.7, splder(splantider(spl)))
(array(2.1565429877197317), array(2.1565429877201865))
Antiderivative can be used to evaluate definite integrals:
>>> ispl = splantider(spl)
>>> splev(np.pi/2, ispl) - splev(0, ispl)
2.2572053588768486
This is indeed an approximation to the complete elliptic integral
:math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
>>> from scipy.special import ellipk
>>> ellipk(0.8)
2.2572053268208538
"""
if isinstance(tck, BSpline):
return tck.antiderivative(n)
else:
return _impl.splantider(tck, n)
|
Azulinho/ansible | refs/heads/devel | test/units/modules/system/interfaces_file/test_interfaces_file.py | 39 | # (c) 2017, Roman Belyakovsky <ihryamzik () gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from ansible.compat.tests import unittest
import ansible.module_utils.basic
from ansible.modules.system import interfaces_file
import os
import json
import sys
import io
import inspect
import json
class AnsibleFailJson(Exception):
pass
class ModuleMocked():
def fail_json(self, msg):
raise AnsibleFailJson(msg)
module = ModuleMocked()
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'input')
golden_output_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'golden_output')
class TestInterfacesFileModule(unittest.TestCase):
def getTestFiles(self):
return next(os.walk(fixture_path))[2]
def compareInterfacesLinesToFile(self, interfaces_lines, path, testname=None):
if not testname:
testname = "%s.%s" % (path, inspect.stack()[1][3])
self.compareStringWithFile("".join([d['line'] for d in interfaces_lines if 'line' in d]), testname)
def compareInterfacesToFile(self, ifaces, path, testname=None):
if not testname:
testname = "%s.%s.json" % (path, inspect.stack()[1][3])
self.compareStringWithFile(json.dumps(ifaces, sort_keys=True, indent=4, separators=(',', ': ')), testname)
def compareStringWithFile(self, string, path):
# self.assertEqual("","_",msg=path)
testfilepath = os.path.join(golden_output_path, path)
goldenstring = string
if not os.path.isfile(testfilepath):
f = io.open(testfilepath, 'wb')
f.write(string)
f.close()
else:
with open(testfilepath, 'r') as goldenfile:
goldenstring = goldenfile.read()
goldenfile.close()
self.assertEqual(string, goldenstring)
def test_no_changes(self):
for testfile in self.getTestFiles():
path = os.path.join(fixture_path, testfile)
lines, ifaces = interfaces_file.read_interfaces_file(module, path)
self.compareInterfacesLinesToFile(lines, testfile)
self.compareInterfacesToFile(ifaces, testfile)
def test_add_up_aoption_to_aggi(self):
testcases = {
"add_aggi_up": [
{
'iface': 'aggi',
'option': 'up',
'value': 'route add -net 224.0.0.0 netmask 240.0.0.0 dev aggi',
'state': 'present',
}
],
"add_and_delete_aggi_up": [
{
'iface': 'aggi',
'option': 'up',
'value': 'route add -net 224.0.0.0 netmask 240.0.0.0 dev aggi',
'state': 'present',
},
{
'iface': 'aggi',
'option': 'up',
'value': None,
'state': 'absent',
},
],
"set_aggi_slaves": [
{
'iface': 'aggi',
'option': 'slaves',
'value': 'int1 int3',
'state': 'present',
},
],
"set_aggi_and_eth0_mtu": [
{
'iface': 'aggi',
'option': 'mtu',
'value': '1350',
'state': 'present',
},
{
'iface': 'eth0',
'option': 'mtu',
'value': '1350',
'state': 'present',
},
],
}
for testname, options_list in testcases.items():
for testfile in self.getTestFiles():
path = os.path.join(fixture_path, testfile)
lines, ifaces = interfaces_file.read_interfaces_file(module, path)
fail_json_iterations = []
for i, options in enumerate(options_list):
try:
_, lines = interfaces_file.setInterfaceOption(module, lines, options['iface'], options['option'], options['value'], options['state'])
except AnsibleFailJson as e:
fail_json_iterations.append("[%d] fail_json message: %s\noptions:\n%s" %
(i, str(e), json.dumps(options, sort_keys=True, indent=4, separators=(',', ': '))))
self.compareStringWithFile("\n=====\n".join(fail_json_iterations), "%s_%s.exceptions.txt" % (testfile, testname))
self.compareInterfacesLinesToFile(lines, testfile, "%s_%s" % (testfile, testname))
self.compareInterfacesToFile(ifaces, testfile, "%s_%s.json" % (testfile, testname))
|
cdubz/babybuddy | refs/heads/master | core/templatetags/__init__.py | 12133432 | |
gabrielfalcao/lettuce | refs/heads/master | tests/integration/lib/Django-1.3/django/contrib/localflavor/be/__init__.py | 12133432 | |
uiri/pxqz | refs/heads/master | venv/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/__init__.py | 12133432 | |
kingvuplus/gui_test5 | refs/heads/master | lib/python/Plugins/SystemPlugins/DiseqcTester/__init__.py | 12133432 | |
asrie/phantomjs | refs/heads/master | src/breakpad/src/tools/gyp/test/library/gyptest-shared.py | 430 | #!/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 simple build of a "Hello, world!" program with shared libraries,
including verifying that libraries are rebuilt correctly when functions
move between libraries.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('library.gyp',
'-Dlibrary=shared_library',
'-Dmoveable_function=lib1',
chdir='src')
test.relocate('src', 'relocate/src')
test.build('library.gyp', test.ALL, chdir='relocate/src')
expect = """\
Hello from program.c
Hello from lib1.c
Hello from lib2.c
Hello from lib1_moveable.c
"""
test.run_built_executable('program', chdir='relocate/src', stdout=expect)
test.run_gyp('library.gyp',
'-Dlibrary=shared_library',
'-Dmoveable_function=lib2',
chdir='relocate/src')
# Update program.c to force a rebuild.
test.sleep()
contents = test.read('relocate/src/program.c')
contents = contents.replace('Hello', 'Hello again')
test.write('relocate/src/program.c', contents)
test.build('library.gyp', test.ALL, chdir='relocate/src')
expect = """\
Hello again from program.c
Hello from lib1.c
Hello from lib2.c
Hello from lib2_moveable.c
"""
test.run_built_executable('program', chdir='relocate/src', stdout=expect)
test.run_gyp('library.gyp',
'-Dlibrary=shared_library',
'-Dmoveable_function=lib1',
chdir='relocate/src')
# Update program.c to force a rebuild.
test.sleep()
contents = test.read('relocate/src/program.c')
contents = contents.replace('again', 'again again')
test.write('relocate/src/program.c', contents)
# TODO(sgk): we have to force a rebuild of lib2 so that it weeds out
# the "moved" module. This should be done in gyp by adding a dependency
# on the generated .vcproj file itself.
test.touch('relocate/src/lib2.c')
test.build('library.gyp', test.ALL, chdir='relocate/src')
expect = """\
Hello again again from program.c
Hello from lib1.c
Hello from lib2.c
Hello from lib1_moveable.c
"""
test.run_built_executable('program', chdir='relocate/src', stdout=expect)
test.pass_test()
|
aidanlister/django | refs/heads/master | django/db/backends/postgresql/utils.py | 682 | from django.utils.timezone import utc
def utc_tzinfo_factory(offset):
if offset != 0:
raise AssertionError("database connection isn't set to UTC")
return utc
|
lisa-lab/pylearn2 | refs/heads/master | pylearn2/devtools/tests/test_shebangs.py | 44 | from __future__ import print_function
__author__ = "Ian Goodfellow"
from pylearn2.devtools.list_files import list_files
def test_shebangs():
# Make sure all scripts that use shebangs use /usr/bin/env
# (instead of the non-standard /bin/env or hardcoding the path to
# the interpreter). This test allows any shebang lines that start
# with /usr/bin/env. Examples:
# "#!/usr/bin/env python"
# "#! /usr/bin/env python"
# "#!/usr/bin/env ipython"
# "#!/usr/bin/env ipython --pylab --"
# etc.
files = list_files('.py')
for f in files:
fd = open(f, 'r')
l = fd.readline()
fd.close()
if l.startswith("#!"):
if not l[2:].strip().startswith("/usr/bin/env"):
print(l)
print(f)
raise AssertionError("Bad shebang")
|
raymondgom/pmip6ns3.13new | refs/heads/master | src/uan/bindings/modulegen__gcc_ILP32.py | 28 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
return True
pybindgen.settings.error_handler = ErrorHandler()
import sys
def module_init():
root_module = Module('ns.uan', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## address.h (module 'network'): ns3::Address [class]
module.add_class('Address', import_from_module='ns.network')
## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration]
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class]
module.add_class('AttributeConstructionList', import_from_module='ns.core')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct]
module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList'])
## buffer.h (module 'network'): ns3::Buffer [class]
module.add_class('Buffer', import_from_module='ns.network')
## buffer.h (module 'network'): ns3::Buffer::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer'])
## packet.h (module 'network'): ns3::ByteTagIterator [class]
module.add_class('ByteTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::ByteTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList', import_from_module='ns.network')
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator'])
## callback.h (module 'core'): ns3::CallbackBase [class]
module.add_class('CallbackBase', import_from_module='ns.core')
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer [class]
module.add_class('DeviceEnergyModelContainer', import_from_module='ns.energy')
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper [class]
module.add_class('DeviceEnergyModelHelper', allow_subclassing=True, import_from_module='ns.energy')
## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper [class]
module.add_class('EnergySourceHelper', allow_subclassing=True, import_from_module='ns.energy')
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId', import_from_module='ns.core')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address', import_from_module='ns.network')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class]
module.add_class('Ipv6Prefix', import_from_module='ns.network')
## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class]
module.add_class('NetDeviceContainer', import_from_module='ns.network')
## node-container.h (module 'network'): ns3::NodeContainer [class]
module.add_class('NodeContainer', import_from_module='ns.network')
## object-base.h (module 'core'): ns3::ObjectBase [class]
module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core')
## object.h (module 'core'): ns3::ObjectDeleter [struct]
module.add_class('ObjectDeleter', import_from_module='ns.core')
## object-factory.h (module 'core'): ns3::ObjectFactory [class]
module.add_class('ObjectFactory', import_from_module='ns.core')
## packet-metadata.h (module 'network'): ns3::PacketMetadata [class]
module.add_class('PacketMetadata', import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration]
module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class]
module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet.h (module 'network'): ns3::PacketTagIterator [class]
module.add_class('PacketTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::PacketTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList [class]
module.add_class('PacketTagList', import_from_module='ns.network')
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct]
module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList'])
## uan-mac-rc.h (module 'uan'): ns3::Reservation [class]
module.add_class('Reservation')
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simulator.h (module 'core'): ns3::Simulator [class]
module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core')
## tag.h (module 'network'): ns3::Tag [class]
module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## tag-buffer.h (module 'network'): ns3::TagBuffer [class]
module.add_class('TagBuffer', import_from_module='ns.network')
## uan-prop-model.h (module 'uan'): ns3::Tap [class]
module.add_class('Tap')
## traced-value.h (module 'core'): ns3::TracedValue<double> [class]
module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['double'])
## type-id.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId', import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration]
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct]
module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## uan-address.h (module 'uan'): ns3::UanAddress [class]
module.add_class('UanAddress')
## uan-address.h (module 'uan'): ns3::UanAddress [class]
root_module['ns3::UanAddress'].implicitly_converts_to(root_module['ns3::Address'])
## uan-helper.h (module 'uan'): ns3::UanHelper [class]
module.add_class('UanHelper')
## uan-tx-mode.h (module 'uan'): ns3::UanModesList [class]
module.add_class('UanModesList')
## uan-transducer.h (module 'uan'): ns3::UanPacketArrival [class]
module.add_class('UanPacketArrival')
## uan-prop-model.h (module 'uan'): ns3::UanPdp [class]
module.add_class('UanPdp')
## uan-phy.h (module 'uan'): ns3::UanPhyListener [class]
module.add_class('UanPhyListener', allow_subclassing=True)
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode [class]
module.add_class('UanTxMode')
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::ModulationType [enumeration]
module.add_enum('ModulationType', ['PSK', 'QAM', 'FSK', 'OTHER'], outer_class=root_module['ns3::UanTxMode'])
## uan-tx-mode.h (module 'uan'): ns3::UanTxModeFactory [class]
module.add_class('UanTxModeFactory')
## vector.h (module 'core'): ns3::Vector2D [class]
module.add_class('Vector2D', import_from_module='ns.core')
## vector.h (module 'core'): ns3::Vector3D [class]
module.add_class('Vector3D', import_from_module='ns.core')
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::AcousticModemEnergyModelHelper [class]
module.add_class('AcousticModemEnergyModelHelper', parent=root_module['ns3::DeviceEnergyModelHelper'])
## chunk.h (module 'network'): ns3::Chunk [class]
module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## header.h (module 'network'): ns3::Header [class]
module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## object.h (module 'core'): ns3::Object [class]
module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
## object.h (module 'core'): ns3::Object::AggregateIterator [class]
module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object'])
## 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::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time', import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time::Unit [enumeration]
module.add_enum('Unit', ['S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time [class]
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class]
module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## trailer.h (module 'network'): ns3::Trailer [class]
module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon [class]
module.add_class('UanHeaderCommon', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcAck [class]
module.add_class('UanHeaderRcAck', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts [class]
module.add_class('UanHeaderRcCts', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal [class]
module.add_class('UanHeaderRcCtsGlobal', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData [class]
module.add_class('UanHeaderRcData', parent=root_module['ns3::Header'])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts [class]
module.add_class('UanHeaderRcRts', parent=root_module['ns3::Header'])
## uan-mac.h (module 'uan'): ns3::UanMac [class]
module.add_class('UanMac', parent=root_module['ns3::Object'])
## uan-mac-aloha.h (module 'uan'): ns3::UanMacAloha [class]
module.add_class('UanMacAloha', parent=root_module['ns3::UanMac'])
## uan-mac-cw.h (module 'uan'): ns3::UanMacCw [class]
module.add_class('UanMacCw', parent=[root_module['ns3::UanMac'], root_module['ns3::UanPhyListener']])
## uan-mac-rc.h (module 'uan'): ns3::UanMacRc [class]
module.add_class('UanMacRc', parent=root_module['ns3::UanMac'])
## uan-mac-rc.h (module 'uan'): ns3::UanMacRc [enumeration]
module.add_enum('', ['TYPE_DATA', 'TYPE_GWPING', 'TYPE_RTS', 'TYPE_CTS', 'TYPE_ACK'], outer_class=root_module['ns3::UanMacRc'])
## uan-mac-rc-gw.h (module 'uan'): ns3::UanMacRcGw [class]
module.add_class('UanMacRcGw', parent=root_module['ns3::UanMac'])
## uan-noise-model.h (module 'uan'): ns3::UanNoiseModel [class]
module.add_class('UanNoiseModel', parent=root_module['ns3::Object'])
## uan-noise-model-default.h (module 'uan'): ns3::UanNoiseModelDefault [class]
module.add_class('UanNoiseModelDefault', parent=root_module['ns3::UanNoiseModel'])
## uan-phy.h (module 'uan'): ns3::UanPhy [class]
module.add_class('UanPhy', parent=root_module['ns3::Object'])
## uan-phy.h (module 'uan'): ns3::UanPhy::State [enumeration]
module.add_enum('State', ['IDLE', 'CCABUSY', 'RX', 'TX', 'SLEEP'], outer_class=root_module['ns3::UanPhy'])
## uan-phy.h (module 'uan'): ns3::UanPhyCalcSinr [class]
module.add_class('UanPhyCalcSinr', parent=root_module['ns3::Object'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrDefault [class]
module.add_class('UanPhyCalcSinrDefault', parent=root_module['ns3::UanPhyCalcSinr'])
## uan-phy-dual.h (module 'uan'): ns3::UanPhyCalcSinrDual [class]
module.add_class('UanPhyCalcSinrDual', parent=root_module['ns3::UanPhyCalcSinr'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrFhFsk [class]
module.add_class('UanPhyCalcSinrFhFsk', parent=root_module['ns3::UanPhyCalcSinr'])
## uan-phy-dual.h (module 'uan'): ns3::UanPhyDual [class]
module.add_class('UanPhyDual', parent=root_module['ns3::UanPhy'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyGen [class]
module.add_class('UanPhyGen', parent=root_module['ns3::UanPhy'])
## uan-phy.h (module 'uan'): ns3::UanPhyPer [class]
module.add_class('UanPhyPer', parent=root_module['ns3::Object'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerGenDefault [class]
module.add_class('UanPhyPerGenDefault', parent=root_module['ns3::UanPhyPer'])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerUmodem [class]
module.add_class('UanPhyPerUmodem', parent=root_module['ns3::UanPhyPer'])
## uan-prop-model.h (module 'uan'): ns3::UanPropModel [class]
module.add_class('UanPropModel', parent=root_module['ns3::Object'])
## uan-prop-model-ideal.h (module 'uan'): ns3::UanPropModelIdeal [class]
module.add_class('UanPropModelIdeal', parent=root_module['ns3::UanPropModel'])
## uan-prop-model-thorp.h (module 'uan'): ns3::UanPropModelThorp [class]
module.add_class('UanPropModelThorp', parent=root_module['ns3::UanPropModel'])
## uan-transducer.h (module 'uan'): ns3::UanTransducer [class]
module.add_class('UanTransducer', parent=root_module['ns3::Object'])
## uan-transducer.h (module 'uan'): ns3::UanTransducer::State [enumeration]
module.add_enum('State', ['TX', 'RX'], outer_class=root_module['ns3::UanTransducer'])
## uan-transducer-hd.h (module 'uan'): ns3::UanTransducerHd [class]
module.add_class('UanTransducerHd', parent=root_module['ns3::UanTransducer'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## boolean.h (module 'core'): ns3::BooleanChecker [class]
module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## boolean.h (module 'core'): ns3::BooleanValue [class]
module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## channel.h (module 'network'): ns3::Channel [class]
module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel [class]
module.add_class('DeviceEnergyModel', import_from_module='ns.energy', parent=root_module['ns3::Object'])
## double.h (module 'core'): ns3::DoubleValue [class]
module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## energy-source.h (module 'energy'): ns3::EnergySource [class]
module.add_class('EnergySource', import_from_module='ns.energy', parent=root_module['ns3::Object'])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer [class]
module.add_class('EnergySourceContainer', import_from_module='ns.energy', parent=root_module['ns3::Object'])
## enum.h (module 'core'): ns3::EnumChecker [class]
module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## enum.h (module 'core'): ns3::EnumValue [class]
module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## 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> >'])
## integer.h (module 'core'): ns3::IntegerValue [class]
module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class]
module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class]
module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class]
module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class]
module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class]
module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class]
module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class]
module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class]
module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## mobility-model.h (module 'mobility'): ns3::MobilityModel [class]
module.add_class('MobilityModel', import_from_module='ns.mobility', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration]
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
## 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'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## pointer.h (module 'core'): ns3::PointerChecker [class]
module.add_class('PointerChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## pointer.h (module 'core'): ns3::PointerValue [class]
module.add_class('PointerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## nstime.h (module 'core'): ns3::TimeChecker [class]
module.add_class('TimeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## nstime.h (module 'core'): ns3::TimeValue [class]
module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## type-id.h (module 'core'): ns3::TypeIdChecker [class]
module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## type-id.h (module 'core'): ns3::TypeIdValue [class]
module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## uan-channel.h (module 'uan'): ns3::UanChannel [class]
module.add_class('UanChannel', parent=root_module['ns3::Channel'])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker [class]
module.add_class('UanModesListChecker', parent=root_module['ns3::AttributeChecker'])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue [class]
module.add_class('UanModesListValue', parent=root_module['ns3::AttributeValue'])
## uan-net-device.h (module 'uan'): ns3::UanNetDevice [class]
module.add_class('UanNetDevice', parent=root_module['ns3::NetDevice'])
## uinteger.h (module 'core'): ns3::UintegerValue [class]
module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## vector.h (module 'core'): ns3::Vector2DChecker [class]
module.add_class('Vector2DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## vector.h (module 'core'): ns3::Vector2DValue [class]
module.add_class('Vector2DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## vector.h (module 'core'): ns3::Vector3DChecker [class]
module.add_class('Vector3DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## vector.h (module 'core'): ns3::Vector3DValue [class]
module.add_class('Vector3DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel [class]
module.add_class('AcousticModemEnergyModel', parent=root_module['ns3::DeviceEnergyModel'])
## address.h (module 'network'): ns3::AddressChecker [class]
module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## address.h (module 'network'): ns3::AddressValue [class]
module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_container('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress > >', 'std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress >', container_type='list')
module.add_container('std::vector< ns3::Tap >', 'ns3::Tap', container_type='vector')
module.add_container('std::vector< std::complex< double > >', 'std::complex< double >', container_type='vector')
module.add_container('std::vector< double >', 'double', container_type='vector')
module.add_container('std::set< unsigned char >', 'unsigned char', container_type='set')
module.add_container('std::list< ns3::UanPacketArrival >', 'ns3::UanPacketArrival', container_type='list')
module.add_container('std::list< ns3::Ptr< ns3::UanPhy > >', 'ns3::Ptr< ns3::UanPhy >', container_type='list')
module.add_container('std::vector< std::pair< ns3::Ptr< ns3::UanNetDevice >, ns3::Ptr< ns3::UanTransducer > > >', 'std::pair< ns3::Ptr< ns3::UanNetDevice >, ns3::Ptr< ns3::UanTransducer > >', container_type='vector')
module.add_container('std::list< ns3::Ptr< ns3::UanTransducer > >', 'ns3::Ptr< ns3::UanTransducer >', container_type='list')
typehandlers.add_type_alias('ns3::Vector3DValue', 'ns3::VectorValue')
typehandlers.add_type_alias('ns3::Vector3DValue*', 'ns3::VectorValue*')
typehandlers.add_type_alias('ns3::Vector3DValue&', 'ns3::VectorValue&')
module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue')
typehandlers.add_type_alias('ns3::Vector3D', 'ns3::Vector')
typehandlers.add_type_alias('ns3::Vector3D*', 'ns3::Vector*')
typehandlers.add_type_alias('ns3::Vector3D&', 'ns3::Vector&')
module.add_typedef(root_module['ns3::Vector3D'], 'Vector')
typehandlers.add_type_alias('ns3::Vector3DChecker', 'ns3::VectorChecker')
typehandlers.add_type_alias('ns3::Vector3DChecker*', 'ns3::VectorChecker*')
typehandlers.add_type_alias('ns3::Vector3DChecker&', 'ns3::VectorChecker&')
module.add_typedef(root_module['ns3::Vector3DChecker'], 'VectorChecker')
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace internal
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(nested_module)
def register_types_ns3_FatalImpl(module):
root_module = module.get_root()
def register_types_ns3_internal(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer'])
register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator'])
register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator'])
register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item'])
register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList'])
register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator'])
register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item'])
register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase'])
register_Ns3DeviceEnergyModelContainer_methods(root_module, root_module['ns3::DeviceEnergyModelContainer'])
register_Ns3DeviceEnergyModelHelper_methods(root_module, root_module['ns3::DeviceEnergyModelHelper'])
register_Ns3EnergySourceHelper_methods(root_module, root_module['ns3::EnergySourceHelper'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address'])
register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix'])
register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata'])
register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item'])
register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3Reservation_methods(root_module, root_module['ns3::Reservation'])
register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3Tap_methods(root_module, root_module['ns3::Tap'])
register_Ns3TracedValue__Double_methods(root_module, root_module['ns3::TracedValue< double >'])
register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId'])
register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation'])
register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation'])
register_Ns3UanAddress_methods(root_module, root_module['ns3::UanAddress'])
register_Ns3UanHelper_methods(root_module, root_module['ns3::UanHelper'])
register_Ns3UanModesList_methods(root_module, root_module['ns3::UanModesList'])
register_Ns3UanPacketArrival_methods(root_module, root_module['ns3::UanPacketArrival'])
register_Ns3UanPdp_methods(root_module, root_module['ns3::UanPdp'])
register_Ns3UanPhyListener_methods(root_module, root_module['ns3::UanPhyListener'])
register_Ns3UanTxMode_methods(root_module, root_module['ns3::UanTxMode'])
register_Ns3UanTxModeFactory_methods(root_module, root_module['ns3::UanTxModeFactory'])
register_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D'])
register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3AcousticModemEnergyModelHelper_methods(root_module, root_module['ns3::AcousticModemEnergyModelHelper'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_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__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
register_Ns3UanHeaderCommon_methods(root_module, root_module['ns3::UanHeaderCommon'])
register_Ns3UanHeaderRcAck_methods(root_module, root_module['ns3::UanHeaderRcAck'])
register_Ns3UanHeaderRcCts_methods(root_module, root_module['ns3::UanHeaderRcCts'])
register_Ns3UanHeaderRcCtsGlobal_methods(root_module, root_module['ns3::UanHeaderRcCtsGlobal'])
register_Ns3UanHeaderRcData_methods(root_module, root_module['ns3::UanHeaderRcData'])
register_Ns3UanHeaderRcRts_methods(root_module, root_module['ns3::UanHeaderRcRts'])
register_Ns3UanMac_methods(root_module, root_module['ns3::UanMac'])
register_Ns3UanMacAloha_methods(root_module, root_module['ns3::UanMacAloha'])
register_Ns3UanMacCw_methods(root_module, root_module['ns3::UanMacCw'])
register_Ns3UanMacRc_methods(root_module, root_module['ns3::UanMacRc'])
register_Ns3UanMacRcGw_methods(root_module, root_module['ns3::UanMacRcGw'])
register_Ns3UanNoiseModel_methods(root_module, root_module['ns3::UanNoiseModel'])
register_Ns3UanNoiseModelDefault_methods(root_module, root_module['ns3::UanNoiseModelDefault'])
register_Ns3UanPhy_methods(root_module, root_module['ns3::UanPhy'])
register_Ns3UanPhyCalcSinr_methods(root_module, root_module['ns3::UanPhyCalcSinr'])
register_Ns3UanPhyCalcSinrDefault_methods(root_module, root_module['ns3::UanPhyCalcSinrDefault'])
register_Ns3UanPhyCalcSinrDual_methods(root_module, root_module['ns3::UanPhyCalcSinrDual'])
register_Ns3UanPhyCalcSinrFhFsk_methods(root_module, root_module['ns3::UanPhyCalcSinrFhFsk'])
register_Ns3UanPhyDual_methods(root_module, root_module['ns3::UanPhyDual'])
register_Ns3UanPhyGen_methods(root_module, root_module['ns3::UanPhyGen'])
register_Ns3UanPhyPer_methods(root_module, root_module['ns3::UanPhyPer'])
register_Ns3UanPhyPerGenDefault_methods(root_module, root_module['ns3::UanPhyPerGenDefault'])
register_Ns3UanPhyPerUmodem_methods(root_module, root_module['ns3::UanPhyPerUmodem'])
register_Ns3UanPropModel_methods(root_module, root_module['ns3::UanPropModel'])
register_Ns3UanPropModelIdeal_methods(root_module, root_module['ns3::UanPropModelIdeal'])
register_Ns3UanPropModelThorp_methods(root_module, root_module['ns3::UanPropModelThorp'])
register_Ns3UanTransducer_methods(root_module, root_module['ns3::UanTransducer'])
register_Ns3UanTransducerHd_methods(root_module, root_module['ns3::UanTransducerHd'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker'])
register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3DeviceEnergyModel_methods(root_module, root_module['ns3::DeviceEnergyModel'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EnergySource_methods(root_module, root_module['ns3::EnergySource'])
register_Ns3EnergySourceContainer_methods(root_module, root_module['ns3::EnergySourceContainer'])
register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker'])
register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue'])
register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker'])
register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue'])
register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker'])
register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue'])
register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker'])
register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue'])
register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker'])
register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue'])
register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel'])
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_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3PointerChecker_methods(root_module, root_module['ns3::PointerChecker'])
register_Ns3PointerValue_methods(root_module, root_module['ns3::PointerValue'])
register_Ns3TimeChecker_methods(root_module, root_module['ns3::TimeChecker'])
register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue'])
register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker'])
register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue'])
register_Ns3UanChannel_methods(root_module, root_module['ns3::UanChannel'])
register_Ns3UanModesListChecker_methods(root_module, root_module['ns3::UanModesListChecker'])
register_Ns3UanModesListValue_methods(root_module, root_module['ns3::UanModesListValue'])
register_Ns3UanNetDevice_methods(root_module, root_module['ns3::UanNetDevice'])
register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue'])
register_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker'])
register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue'])
register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker'])
register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue'])
register_Ns3AcousticModemEnergyModel_methods(root_module, root_module['ns3::AcousticModemEnergyModel'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
return
def register_Ns3Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## address.h (module 'network'): ns3::Address::Address() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor]
cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor]
cls.add_constructor([param('ns3::Address const &', 'address')])
## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function]
cls.add_method('CheckCompatible',
'bool',
[param('uint8_t', 'type'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyAllFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function]
cls.add_method('CopyAllTo',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'uint32_t',
[param('uint8_t *', 'buffer')],
is_const=True)
## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'buffer')])
## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function]
cls.add_method('GetLength',
'uint8_t',
[],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function]
cls.add_method('IsInvalid',
'bool',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function]
cls.add_method('IsMatchingType',
'bool',
[param('uint8_t', 'type')],
is_const=True)
## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function]
cls.add_method('Register',
'uint8_t',
[],
is_static=True)
## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'buffer')],
is_const=True)
return
def register_Ns3AttributeConstructionList_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')])
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('Find',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True)
return
def register_Ns3AttributeConstructionListItem_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable]
cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False)
return
def register_Ns3Buffer_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor]
cls.add_constructor([param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'bool',
[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'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'bool',
[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'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function]
cls.add_method('CreateFullCopy',
'ns3::Buffer',
[],
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'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function]
cls.add_method('GetCurrentEndOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function]
cls.add_method('GetCurrentStartOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3BufferIterator_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')])
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function]
cls.add_method('GetDistanceFrom',
'uint32_t',
[param('ns3::Buffer::Iterator const &', 'o')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function]
cls.add_method('IsEnd',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function]
cls.add_method('IsStart',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function]
cls.add_method('Next',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function]
cls.add_method('Next',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): 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'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function]
cls.add_method('ReadLsbtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function]
cls.add_method('ReadLsbtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function]
cls.add_method('ReadLsbtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function]
cls.add_method('ReadNtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function]
cls.add_method('ReadNtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function]
cls.add_method('ReadNtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Write',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function]
cls.add_method('WriteHtolsbU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function]
cls.add_method('WriteHtolsbU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function]
cls.add_method('WriteHtolsbU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function]
cls.add_method('WriteHtonU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function]
cls.add_method('WriteHtonU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function]
cls.add_method('WriteHtonU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data'), param('uint32_t', 'len')])
return
def register_Ns3ByteTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagIterator::Item',
[])
return
def register_Ns3ByteTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function]
cls.add_method('GetEnd',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function]
cls.add_method('GetStart',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3ByteTagList_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor]
cls.add_constructor([])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function]
cls.add_method('Add',
'ns3::TagBuffer',
[param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function]
cls.add_method('Add',
'void',
[param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function]
cls.add_method('AddAtEnd',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function]
cls.add_method('AddAtStart',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function]
cls.add_method('Begin',
'ns3::ByteTagList::Iterator',
[param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')],
is_const=True)
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3ByteTagListIterator_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')])
## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function]
cls.add_method('GetOffsetStart',
'uint32_t',
[],
is_const=True)
## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagList::Iterator::Item',
[])
return
def register_Ns3ByteTagListIteratorItem_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor]
cls.add_constructor([param('ns3::TagBuffer', 'buf')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable]
cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable]
cls.add_instance_attribute('end', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable]
cls.add_instance_attribute('size', 'uint32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable]
cls.add_instance_attribute('start', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3CallbackBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function]
cls.add_method('GetImpl',
'ns3::Ptr< ns3::CallbackImplBase >',
[],
is_const=True)
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')],
visibility='protected')
## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3DeviceEnergyModelContainer_methods(root_module, cls):
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'arg0')])
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer() [constructor]
cls.add_constructor([])
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::Ptr<ns3::DeviceEnergyModel> model) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')])
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(std::string modelName) [constructor]
cls.add_constructor([param('std::string', 'modelName')])
## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & a, ns3::DeviceEnergyModelContainer const & b) [constructor]
cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'a'), param('ns3::DeviceEnergyModelContainer const &', 'b')])
## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::DeviceEnergyModelContainer container) [member function]
cls.add_method('Add',
'void',
[param('ns3::DeviceEnergyModelContainer', 'container')])
## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::Ptr<ns3::DeviceEnergyModel> model) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')])
## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(std::string modelName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'modelName')])
## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >',
[],
is_const=True)
## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >',
[],
is_const=True)
## device-energy-model-container.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::DeviceEnergyModel >',
[param('uint32_t', 'i')],
is_const=True)
## device-energy-model-container.h (module 'energy'): uint32_t ns3::DeviceEnergyModelContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3DeviceEnergyModelHelper_methods(root_module, cls):
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper() [constructor]
cls.add_constructor([])
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper(ns3::DeviceEnergyModelHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeviceEnergyModelHelper const &', 'arg0')])
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function]
cls.add_method('Install',
'ns3::DeviceEnergyModelContainer',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_const=True)
## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::NetDeviceContainer deviceContainer, ns3::EnergySourceContainer sourceContainer) const [member function]
cls.add_method('Install',
'ns3::DeviceEnergyModelContainer',
[param('ns3::NetDeviceContainer', 'deviceContainer'), param('ns3::EnergySourceContainer', 'sourceContainer')],
is_const=True)
## energy-model-helper.h (module 'energy'): void ns3::DeviceEnergyModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')],
is_pure_virtual=True, is_virtual=True)
## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelHelper::DoInstall(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function]
cls.add_method('DoInstall',
'ns3::Ptr< ns3::DeviceEnergyModel >',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EnergySourceHelper_methods(root_module, cls):
## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper() [constructor]
cls.add_constructor([])
## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper(ns3::EnergySourceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnergySourceHelper const &', 'arg0')])
## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::EnergySourceContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::EnergySourceContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::EnergySourceContainer',
[param('std::string', 'nodeName')],
is_const=True)
## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::InstallAll() const [member function]
cls.add_method('InstallAll',
'ns3::EnergySourceContainer',
[],
is_const=True)
## energy-model-helper.h (module 'energy'): void ns3::EnergySourceHelper::Set(std::string name, ns3::AttributeValue const & v) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')],
is_pure_virtual=True, is_virtual=True)
## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergySourceHelper::DoInstall(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('DoInstall',
'ns3::Ptr< ns3::EnergySource >',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('==')
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventId const &', 'arg0')])
## event-id.h (module 'core'): ns3::EventId::EventId() [constructor]
cls.add_constructor([])
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')])
## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function]
cls.add_method('GetTs',
'uint64_t',
[],
is_const=True)
## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function]
cls.add_method('PeekEventImpl',
'ns3::EventImpl *',
[],
is_const=True)
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor]
cls.add_constructor([param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('CombineMask',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv4Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv4Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('GetSubnetDirectedBroadcast',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::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'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('IsSubnetDirectedBroadcast',
'bool',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
return
def register_Ns3Ipv4Mask_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor]
cls.add_constructor([param('uint32_t', 'mask')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor]
cls.add_constructor([param('char const *', 'mask')])
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function]
cls.add_method('GetInverse',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint16_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Mask', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'mask')])
return
def register_Ns3Ipv6Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor]
cls.add_constructor([param('uint8_t *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function]
cls.add_method('CombinePrefix',
'ns3::Ipv6Address',
[param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv6Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv6Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function]
cls.add_method('GetAllHostsMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function]
cls.add_method('GetAllNodesMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function]
cls.add_method('GetAllRoutersMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): 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',
[],
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::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::IsLinkLocal() const [member function]
cls.add_method('IsLinkLocal',
'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::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::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::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function]
cls.add_method('MakeSolicitedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv6Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function]
cls.add_method('Set',
'void',
[param('uint8_t *', 'address')])
return
def register_Ns3Ipv6Prefix_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor]
cls.add_constructor([param('uint8_t *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor]
cls.add_constructor([param('char const *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor]
cls.add_constructor([param('uint8_t', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint8_t',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Prefix const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
return
def register_Ns3NetDeviceContainer_methods(root_module, cls):
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor]
cls.add_constructor([])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor]
cls.add_constructor([param('std::string', 'devName')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NetDeviceContainer', 'other')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'deviceName')])
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True)
## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeContainer_methods(root_module, cls):
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor]
cls.add_constructor([])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor]
cls.add_constructor([param('std::string', 'nodeName')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NodeContainer', 'other')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'nodeName')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n')])
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n'), param('uint32_t', 'systemId')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'i')],
is_const=True)
## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function]
cls.add_method('GetGlobal',
'ns3::NodeContainer',
[],
is_static=True)
## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3ObjectBase_methods(root_module, cls):
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor]
cls.add_constructor([])
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')])
## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')],
is_const=True)
## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function]
cls.add_method('ConstructSelf',
'void',
[param('ns3::AttributeConstructionList const &', 'attributes')],
visibility='protected')
## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function]
cls.add_method('NotifyConstructionCompleted',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectDeleter_methods(root_module, cls):
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor]
cls.add_constructor([])
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')])
## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Object *', 'object')],
is_static=True)
return
def register_Ns3ObjectFactory_methods(root_module, cls):
cls.add_output_stream_operator()
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor]
cls.add_constructor([param('std::string', 'typeId')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('ns3::TypeId', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('char const *', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('std::string', 'tid')])
return
def register_Ns3PacketMetadata_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor]
cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[param('ns3::Buffer', 'buffer')],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function]
cls.add_method('CreateFragment',
'ns3::PacketMetadata',
[param('uint32_t', 'start'), param('uint32_t', 'end')],
is_const=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function]
cls.add_method('Enable',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('RemoveTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3PacketMetadataItem_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor]
cls.add_constructor([])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable]
cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable]
cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable]
cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable]
cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable]
cls.add_instance_attribute('isFragment', 'bool', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor]
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketMetadata::Item',
[])
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3PacketTagListTagData_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable]
cls.add_instance_attribute('count', 'uint32_t', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable]
cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable]
cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3Reservation_methods(root_module, cls):
## uan-mac-rc.h (module 'uan'): ns3::Reservation::Reservation(ns3::Reservation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Reservation const &', 'arg0')])
## uan-mac-rc.h (module 'uan'): ns3::Reservation::Reservation() [constructor]
cls.add_constructor([])
## uan-mac-rc.h (module 'uan'): ns3::Reservation::Reservation(std::list<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress>, std::allocator<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress> > > & list, uint8_t frameNo, uint32_t maxPkts=0) [constructor]
cls.add_constructor([param('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress > > &', 'list'), param('uint8_t', 'frameNo'), param('uint32_t', 'maxPkts', default_value='0')])
## uan-mac-rc.h (module 'uan'): void ns3::Reservation::AddTimestamp(ns3::Time t) [member function]
cls.add_method('AddTimestamp',
'void',
[param('ns3::Time', 't')])
## uan-mac-rc.h (module 'uan'): uint8_t ns3::Reservation::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): uint32_t ns3::Reservation::GetLength() const [member function]
cls.add_method('GetLength',
'uint32_t',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): uint32_t ns3::Reservation::GetNoFrames() const [member function]
cls.add_method('GetNoFrames',
'uint32_t',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): std::list<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress>, std::allocator<std::pair<ns3::Ptr<ns3::Packet>, ns3::UanAddress> > > const & ns3::Reservation::GetPktList() const [member function]
cls.add_method('GetPktList',
'std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::UanAddress > > const &',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): uint8_t ns3::Reservation::GetRetryNo() const [member function]
cls.add_method('GetRetryNo',
'uint8_t',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): ns3::Time ns3::Reservation::GetTimestamp(uint8_t n) const [member function]
cls.add_method('GetTimestamp',
'ns3::Time',
[param('uint8_t', 'n')],
is_const=True)
## uan-mac-rc.h (module 'uan'): void ns3::Reservation::IncrementRetry() [member function]
cls.add_method('IncrementRetry',
'void',
[])
## uan-mac-rc.h (module 'uan'): bool ns3::Reservation::IsTransmitted() const [member function]
cls.add_method('IsTransmitted',
'bool',
[],
is_const=True)
## uan-mac-rc.h (module 'uan'): void ns3::Reservation::SetFrameNo(uint8_t fn) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'fn')])
## uan-mac-rc.h (module 'uan'): void ns3::Reservation::SetTransmitted(bool t=true) [member function]
cls.add_method('SetTransmitted',
'void',
[param('bool', 't', default_value='true')])
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Next() [member function]
cls.add_method('Next',
'ns3::Time',
[],
is_static=True, deprecated=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::RunOneEvent() [member function]
cls.add_method('RunOneEvent',
'void',
[],
is_static=True, deprecated=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 & time) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'time')],
is_static=True)
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_Ns3Tap_methods(root_module, cls):
## uan-prop-model.h (module 'uan'): ns3::Tap::Tap(ns3::Tap const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tap const &', 'arg0')])
## uan-prop-model.h (module 'uan'): ns3::Tap::Tap() [constructor]
cls.add_constructor([])
## uan-prop-model.h (module 'uan'): ns3::Tap::Tap(ns3::Time delay, std::complex<double> amp) [constructor]
cls.add_constructor([param('ns3::Time', 'delay'), param('std::complex< double >', 'amp')])
## uan-prop-model.h (module 'uan'): std::complex<double> ns3::Tap::GetAmp() const [member function]
cls.add_method('GetAmp',
'std::complex< double >',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): ns3::Time ns3::Tap::GetDelay() const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[],
is_const=True)
return
def register_Ns3TracedValue__Double_methods(root_module, cls):
## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue() [constructor]
cls.add_constructor([])
## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue(ns3::TracedValue<double> const & o) [copy constructor]
cls.add_constructor([param('ns3::TracedValue< double > const &', 'o')])
## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue(double const & v) [constructor]
cls.add_constructor([param('double const &', 'v')])
## traced-value.h (module 'core'): void ns3::TracedValue<double>::Connect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function]
cls.add_method('Connect',
'void',
[param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')])
## traced-value.h (module 'core'): void ns3::TracedValue<double>::ConnectWithoutContext(ns3::CallbackBase const & cb) [member function]
cls.add_method('ConnectWithoutContext',
'void',
[param('ns3::CallbackBase const &', 'cb')])
## traced-value.h (module 'core'): void ns3::TracedValue<double>::Disconnect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function]
cls.add_method('Disconnect',
'void',
[param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')])
## traced-value.h (module 'core'): void ns3::TracedValue<double>::DisconnectWithoutContext(ns3::CallbackBase const & cb) [member function]
cls.add_method('DisconnectWithoutContext',
'void',
[param('ns3::CallbackBase const &', 'cb')])
## traced-value.h (module 'core'): double ns3::TracedValue<double>::Get() const [member function]
cls.add_method('Get',
'double',
[],
is_const=True)
## traced-value.h (module 'core'): void ns3::TracedValue<double>::Set(double const & v) [member function]
cls.add_method('Set',
'void',
[param('double const &', 'v')])
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function]
cls.add_method('GetParent',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint32_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint32_t',
[],
is_static=True)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function]
cls.add_method('GetUid',
'uint16_t',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function]
cls.add_method('HasConstructor',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function]
cls.add_method('HasParent',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function]
cls.add_method('HideFromDocumentation',
'ns3::TypeId',
[])
## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function]
cls.add_method('IsChildOf',
'bool',
[param('ns3::TypeId', 'other')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function]
cls.add_method('LookupAttributeByName',
'bool',
[param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info')],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function]
cls.add_method('MustHideFromDocumentation',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function]
cls.add_method('SetGroupName',
'ns3::TypeId',
[param('std::string', 'groupName')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[param('ns3::TypeId', 'tid')])
## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'tid')])
return
def register_Ns3TypeIdAttributeInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable]
cls.add_instance_attribute('flags', 'uint32_t', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable]
cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable]
cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
return
def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
return
def register_Ns3UanAddress_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## uan-address.h (module 'uan'): ns3::UanAddress::UanAddress(ns3::UanAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanAddress const &', 'arg0')])
## uan-address.h (module 'uan'): ns3::UanAddress::UanAddress() [constructor]
cls.add_constructor([])
## uan-address.h (module 'uan'): ns3::UanAddress::UanAddress(uint8_t addr) [constructor]
cls.add_constructor([param('uint8_t', 'addr')])
## uan-address.h (module 'uan'): static ns3::UanAddress ns3::UanAddress::Allocate() [member function]
cls.add_method('Allocate',
'ns3::UanAddress',
[],
is_static=True)
## uan-address.h (module 'uan'): static ns3::UanAddress ns3::UanAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::UanAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## uan-address.h (module 'uan'): void ns3::UanAddress::CopyFrom(uint8_t const * pBuffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'pBuffer')])
## uan-address.h (module 'uan'): void ns3::UanAddress::CopyTo(uint8_t * pBuffer) [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'pBuffer')])
## uan-address.h (module 'uan'): uint8_t ns3::UanAddress::GetAsInt() const [member function]
cls.add_method('GetAsInt',
'uint8_t',
[],
is_const=True)
## uan-address.h (module 'uan'): static ns3::UanAddress ns3::UanAddress::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::UanAddress',
[],
is_static=True)
## uan-address.h (module 'uan'): static bool ns3::UanAddress::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3UanHelper_methods(root_module, cls):
## uan-helper.h (module 'uan'): ns3::UanHelper::UanHelper(ns3::UanHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHelper const &', 'arg0')])
## uan-helper.h (module 'uan'): ns3::UanHelper::UanHelper() [constructor]
cls.add_constructor([])
## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAscii(std::ostream & os, uint32_t nodeid, uint32_t deviceid) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::ostream &', 'os'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')],
is_static=True)
## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAscii(std::ostream & os, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::ostream &', 'os'), param('ns3::NetDeviceContainer', 'd')],
is_static=True)
## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAscii(std::ostream & os, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::ostream &', 'os'), param('ns3::NodeContainer', 'n')],
is_static=True)
## uan-helper.h (module 'uan'): static void ns3::UanHelper::EnableAsciiAll(std::ostream & os) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('std::ostream &', 'os')],
is_static=True)
## uan-helper.h (module 'uan'): ns3::NetDeviceContainer ns3::UanHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## uan-helper.h (module 'uan'): ns3::NetDeviceContainer ns3::UanHelper::Install(ns3::NodeContainer c, ns3::Ptr<ns3::UanChannel> channel) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer', 'c'), param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_const=True)
## uan-helper.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::UanChannel> channel) const [member function]
cls.add_method('Install',
'ns3::Ptr< ns3::UanNetDevice >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_const=True)
## uan-helper.h (module 'uan'): void ns3::UanHelper::SetMac(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function]
cls.add_method('SetMac',
'void',
[param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')])
## uan-helper.h (module 'uan'): void ns3::UanHelper::SetPhy(std::string phyType, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function]
cls.add_method('SetPhy',
'void',
[param('std::string', 'phyType'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')])
## uan-helper.h (module 'uan'): void ns3::UanHelper::SetTransducer(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function]
cls.add_method('SetTransducer',
'void',
[param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')])
return
def register_Ns3UanModesList_methods(root_module, cls):
cls.add_output_stream_operator()
## uan-tx-mode.h (module 'uan'): ns3::UanModesList::UanModesList(ns3::UanModesList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanModesList const &', 'arg0')])
## uan-tx-mode.h (module 'uan'): ns3::UanModesList::UanModesList() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): void ns3::UanModesList::AppendMode(ns3::UanTxMode mode) [member function]
cls.add_method('AppendMode',
'void',
[param('ns3::UanTxMode', 'mode')])
## uan-tx-mode.h (module 'uan'): void ns3::UanModesList::DeleteMode(uint32_t num) [member function]
cls.add_method('DeleteMode',
'void',
[param('uint32_t', 'num')])
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanModesList::GetNModes() const [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_const=True)
return
def register_Ns3UanPacketArrival_methods(root_module, cls):
## uan-transducer.h (module 'uan'): ns3::UanPacketArrival::UanPacketArrival(ns3::UanPacketArrival const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPacketArrival const &', 'arg0')])
## uan-transducer.h (module 'uan'): ns3::UanPacketArrival::UanPacketArrival() [constructor]
cls.add_constructor([])
## uan-transducer.h (module 'uan'): ns3::UanPacketArrival::UanPacketArrival(ns3::Ptr<ns3::Packet> packet, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp, ns3::Time arrTime) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp'), param('ns3::Time', 'arrTime')])
## uan-transducer.h (module 'uan'): ns3::Time ns3::UanPacketArrival::GetArrivalTime() const [member function]
cls.add_method('GetArrivalTime',
'ns3::Time',
[],
is_const=True)
## uan-transducer.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPacketArrival::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## uan-transducer.h (module 'uan'): ns3::UanPdp ns3::UanPacketArrival::GetPdp() const [member function]
cls.add_method('GetPdp',
'ns3::UanPdp',
[],
is_const=True)
## uan-transducer.h (module 'uan'): double ns3::UanPacketArrival::GetRxPowerDb() const [member function]
cls.add_method('GetRxPowerDb',
'double',
[],
is_const=True)
## uan-transducer.h (module 'uan'): ns3::UanTxMode const & ns3::UanPacketArrival::GetTxMode() const [member function]
cls.add_method('GetTxMode',
'ns3::UanTxMode const &',
[],
is_const=True)
return
def register_Ns3UanPdp_methods(root_module, cls):
cls.add_output_stream_operator()
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(ns3::UanPdp const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPdp const &', 'arg0')])
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp() [constructor]
cls.add_constructor([])
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(std::vector<ns3::Tap, std::allocator<ns3::Tap> > taps, ns3::Time resolution) [constructor]
cls.add_constructor([param('std::vector< ns3::Tap >', 'taps'), param('ns3::Time', 'resolution')])
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(std::vector<std::complex<double>,std::allocator<std::complex<double> > > arrivals, ns3::Time resolution) [constructor]
cls.add_constructor([param('std::vector< std::complex< double > >', 'arrivals'), param('ns3::Time', 'resolution')])
## uan-prop-model.h (module 'uan'): ns3::UanPdp::UanPdp(std::vector<double,std::allocator<double> > arrivals, ns3::Time resolution) [constructor]
cls.add_constructor([param('std::vector< double >', 'arrivals'), param('ns3::Time', 'resolution')])
## uan-prop-model.h (module 'uan'): static ns3::UanPdp ns3::UanPdp::CreateImpulsePdp() [member function]
cls.add_method('CreateImpulsePdp',
'ns3::UanPdp',
[],
is_static=True)
## uan-prop-model.h (module 'uan'): __gnu_cxx::__normal_iterator<const ns3::Tap*,std::vector<ns3::Tap, std::allocator<ns3::Tap> > > ns3::UanPdp::GetBegin() const [member function]
cls.add_method('GetBegin',
'__gnu_cxx::__normal_iterator< ns3::Tap const *, std::vector< ns3::Tap > >',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): __gnu_cxx::__normal_iterator<const ns3::Tap*,std::vector<ns3::Tap, std::allocator<ns3::Tap> > > ns3::UanPdp::GetEnd() const [member function]
cls.add_method('GetEnd',
'__gnu_cxx::__normal_iterator< ns3::Tap const *, std::vector< ns3::Tap > >',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): uint32_t ns3::UanPdp::GetNTaps() const [member function]
cls.add_method('GetNTaps',
'uint32_t',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): ns3::Time ns3::UanPdp::GetResolution() const [member function]
cls.add_method('GetResolution',
'ns3::Time',
[],
is_const=True)
## uan-prop-model.h (module 'uan'): ns3::Tap const & ns3::UanPdp::GetTap(uint32_t i) const [member function]
cls.add_method('GetTap',
'ns3::Tap const &',
[param('uint32_t', 'i')],
is_const=True)
## uan-prop-model.h (module 'uan'): void ns3::UanPdp::SetNTaps(uint32_t nTaps) [member function]
cls.add_method('SetNTaps',
'void',
[param('uint32_t', 'nTaps')])
## uan-prop-model.h (module 'uan'): void ns3::UanPdp::SetResolution(ns3::Time resolution) [member function]
cls.add_method('SetResolution',
'void',
[param('ns3::Time', 'resolution')])
## uan-prop-model.h (module 'uan'): void ns3::UanPdp::SetTap(std::complex<double> arrival, uint32_t index) [member function]
cls.add_method('SetTap',
'void',
[param('std::complex< double >', 'arrival'), param('uint32_t', 'index')])
## uan-prop-model.h (module 'uan'): std::complex<double> ns3::UanPdp::SumTapsC(ns3::Time begin, ns3::Time end) const [member function]
cls.add_method('SumTapsC',
'std::complex< double >',
[param('ns3::Time', 'begin'), param('ns3::Time', 'end')],
is_const=True)
## uan-prop-model.h (module 'uan'): std::complex<double> ns3::UanPdp::SumTapsFromMaxC(ns3::Time delay, ns3::Time duration) const [member function]
cls.add_method('SumTapsFromMaxC',
'std::complex< double >',
[param('ns3::Time', 'delay'), param('ns3::Time', 'duration')],
is_const=True)
## uan-prop-model.h (module 'uan'): double ns3::UanPdp::SumTapsFromMaxNc(ns3::Time delay, ns3::Time duration) const [member function]
cls.add_method('SumTapsFromMaxNc',
'double',
[param('ns3::Time', 'delay'), param('ns3::Time', 'duration')],
is_const=True)
## uan-prop-model.h (module 'uan'): double ns3::UanPdp::SumTapsNc(ns3::Time begin, ns3::Time end) const [member function]
cls.add_method('SumTapsNc',
'double',
[param('ns3::Time', 'begin'), param('ns3::Time', 'end')],
is_const=True)
return
def register_Ns3UanPhyListener_methods(root_module, cls):
## uan-phy.h (module 'uan'): ns3::UanPhyListener::UanPhyListener() [constructor]
cls.add_constructor([])
## uan-phy.h (module 'uan'): ns3::UanPhyListener::UanPhyListener(ns3::UanPhyListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyListener const &', 'arg0')])
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyCcaEnd() [member function]
cls.add_method('NotifyCcaEnd',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyCcaStart() [member function]
cls.add_method('NotifyCcaStart',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyRxEndError() [member function]
cls.add_method('NotifyRxEndError',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyRxEndOk() [member function]
cls.add_method('NotifyRxEndOk',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyRxStart() [member function]
cls.add_method('NotifyRxStart',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyListener::NotifyTxStart(ns3::Time duration) [member function]
cls.add_method('NotifyTxStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3UanTxMode_methods(root_module, cls):
cls.add_output_stream_operator()
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::UanTxMode(ns3::UanTxMode const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanTxMode const &', 'arg0')])
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::UanTxMode() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetBandwidthHz() const [member function]
cls.add_method('GetBandwidthHz',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetCenterFreqHz() const [member function]
cls.add_method('GetCenterFreqHz',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetConstellationSize() const [member function]
cls.add_method('GetConstellationSize',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetDataRateBps() const [member function]
cls.add_method('GetDataRateBps',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): ns3::UanTxMode::ModulationType ns3::UanTxMode::GetModType() const [member function]
cls.add_method('GetModType',
'ns3::UanTxMode::ModulationType',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): std::string ns3::UanTxMode::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetPhyRateSps() const [member function]
cls.add_method('GetPhyRateSps',
'uint32_t',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): uint32_t ns3::UanTxMode::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
return
def register_Ns3UanTxModeFactory_methods(root_module, cls):
## uan-tx-mode.h (module 'uan'): ns3::UanTxModeFactory::UanTxModeFactory(ns3::UanTxModeFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanTxModeFactory const &', 'arg0')])
## uan-tx-mode.h (module 'uan'): ns3::UanTxModeFactory::UanTxModeFactory() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): static ns3::UanTxMode ns3::UanTxModeFactory::CreateMode(ns3::UanTxMode::ModulationType type, uint32_t dataRateBps, uint32_t phyRateSps, uint32_t cfHz, uint32_t bwHz, uint32_t constSize, std::string name) [member function]
cls.add_method('CreateMode',
'ns3::UanTxMode',
[param('ns3::UanTxMode::ModulationType', 'type'), param('uint32_t', 'dataRateBps'), param('uint32_t', 'phyRateSps'), param('uint32_t', 'cfHz'), param('uint32_t', 'bwHz'), param('uint32_t', 'constSize'), param('std::string', 'name')],
is_static=True)
## uan-tx-mode.h (module 'uan'): static ns3::UanTxMode ns3::UanTxModeFactory::GetMode(std::string name) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('std::string', 'name')],
is_static=True)
## uan-tx-mode.h (module 'uan'): static ns3::UanTxMode ns3::UanTxModeFactory::GetMode(uint32_t uid) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('uint32_t', 'uid')],
is_static=True)
return
def register_Ns3Vector2D_methods(root_module, cls):
cls.add_output_stream_operator()
## vector.h (module 'core'): ns3::Vector2D::Vector2D(ns3::Vector2D const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector2D const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector2D::Vector2D(double _x, double _y) [constructor]
cls.add_constructor([param('double', '_x'), param('double', '_y')])
## vector.h (module 'core'): ns3::Vector2D::Vector2D() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector2D::x [variable]
cls.add_instance_attribute('x', 'double', is_const=False)
## vector.h (module 'core'): ns3::Vector2D::y [variable]
cls.add_instance_attribute('y', 'double', is_const=False)
return
def register_Ns3Vector3D_methods(root_module, cls):
cls.add_output_stream_operator()
## vector.h (module 'core'): ns3::Vector3D::Vector3D(ns3::Vector3D const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector3D const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector3D::Vector3D(double _x, double _y, double _z) [constructor]
cls.add_constructor([param('double', '_x'), param('double', '_y'), param('double', '_z')])
## vector.h (module 'core'): ns3::Vector3D::Vector3D() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector3D::x [variable]
cls.add_instance_attribute('x', 'double', is_const=False)
## vector.h (module 'core'): ns3::Vector3D::y [variable]
cls.add_instance_attribute('y', 'double', is_const=False)
## vector.h (module 'core'): ns3::Vector3D::z [variable]
cls.add_instance_attribute('z', 'double', is_const=False)
return
def register_Ns3Empty_methods(root_module, cls):
## empty.h (module 'core'): ns3::empty::empty() [constructor]
cls.add_constructor([])
## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor]
cls.add_constructor([param('ns3::empty const &', 'arg0')])
return
def register_Ns3Int64x64_t_methods(root_module, cls):
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor]
cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t', 'v')],
is_static=True)
## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function]
cls.add_method('MulByInvert',
'void',
[param('ns3::int64x64_t const &', 'o')])
return
def register_Ns3AcousticModemEnergyModelHelper_methods(root_module, cls):
## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::AcousticModemEnergyModelHelper::AcousticModemEnergyModelHelper(ns3::AcousticModemEnergyModelHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AcousticModemEnergyModelHelper const &', 'arg0')])
## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::AcousticModemEnergyModelHelper::AcousticModemEnergyModelHelper() [constructor]
cls.add_constructor([])
## acoustic-modem-energy-model-helper.h (module 'uan'): void ns3::AcousticModemEnergyModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')],
is_virtual=True)
## acoustic-modem-energy-model-helper.h (module 'uan'): void ns3::AcousticModemEnergyModelHelper::SetDepletionCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetDepletionCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## acoustic-modem-energy-model-helper.h (module 'uan'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::AcousticModemEnergyModelHelper::DoInstall(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function]
cls.add_method('DoInstall',
'ns3::Ptr< ns3::DeviceEnergyModel >',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Chunk_methods(root_module, cls):
## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor]
cls.add_constructor([])
## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Chunk const &', 'arg0')])
## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Header_methods(root_module, cls):
cls.add_output_stream_operator()
## header.h (module 'network'): ns3::Header::Header() [constructor]
cls.add_constructor([])
## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Header const &', 'arg0')])
## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Object_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::Object() [constructor]
cls.add_constructor([])
## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function]
cls.add_method('AggregateObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'other')])
## object.h (module 'core'): void ns3::Object::Dispose() [member function]
cls.add_method('Dispose',
'void',
[])
## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function]
cls.add_method('GetAggregateIterator',
'ns3::Object::AggregateIterator',
[],
is_const=True)
## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object.h (module 'core'): void ns3::Object::Start() [member function]
cls.add_method('Start',
'void',
[])
## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor]
cls.add_constructor([param('ns3::Object const &', 'o')],
visibility='protected')
## object.h (module 'core'): void ns3::Object::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectAggregateIterator_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')])
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor]
cls.add_constructor([])
## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function]
cls.add_method('Next',
'ns3::Ptr< ns3::Object const >',
[])
return
def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Time_methods(root_module, cls):
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor]
cls.add_constructor([param('ns3::Time const &', 'o')])
## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'value')])
## 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 & from, ns3::Time::Unit timeUnit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')],
is_static=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::FromDouble(double value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=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'): 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'): 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'): 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 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'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
return
def register_Ns3TraceSourceAccessor_methods(root_module, cls):
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor]
cls.add_constructor([])
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Connect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('ConnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Disconnect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('DisconnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Trailer_methods(root_module, cls):
cls.add_output_stream_operator()
## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor]
cls.add_constructor([])
## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Trailer const &', 'arg0')])
## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'end')],
is_pure_virtual=True, is_virtual=True)
## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3UanHeaderCommon_methods(root_module, cls):
## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon::UanHeaderCommon(ns3::UanHeaderCommon const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderCommon const &', 'arg0')])
## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon::UanHeaderCommon() [constructor]
cls.add_constructor([])
## uan-header-common.h (module 'uan'): ns3::UanHeaderCommon::UanHeaderCommon(ns3::UanAddress const src, ns3::UanAddress const dest, uint8_t type) [constructor]
cls.add_constructor([param('ns3::UanAddress const', 'src'), param('ns3::UanAddress const', 'dest'), param('uint8_t', 'type')])
## uan-header-common.h (module 'uan'): uint32_t ns3::UanHeaderCommon::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-common.h (module 'uan'): ns3::UanAddress ns3::UanHeaderCommon::GetDest() const [member function]
cls.add_method('GetDest',
'ns3::UanAddress',
[],
is_const=True)
## uan-header-common.h (module 'uan'): ns3::TypeId ns3::UanHeaderCommon::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-common.h (module 'uan'): uint32_t ns3::UanHeaderCommon::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-common.h (module 'uan'): ns3::UanAddress ns3::UanHeaderCommon::GetSrc() const [member function]
cls.add_method('GetSrc',
'ns3::UanAddress',
[],
is_const=True)
## uan-header-common.h (module 'uan'): uint8_t ns3::UanHeaderCommon::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## uan-header-common.h (module 'uan'): static ns3::TypeId ns3::UanHeaderCommon::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::SetDest(ns3::UanAddress dest) [member function]
cls.add_method('SetDest',
'void',
[param('ns3::UanAddress', 'dest')])
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::SetSrc(ns3::UanAddress src) [member function]
cls.add_method('SetSrc',
'void',
[param('ns3::UanAddress', 'src')])
## uan-header-common.h (module 'uan'): void ns3::UanHeaderCommon::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
return
def register_Ns3UanHeaderRcAck_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcAck::UanHeaderRcAck(ns3::UanHeaderRcAck const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcAck const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcAck::UanHeaderRcAck() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::AddNackedFrame(uint8_t frame) [member function]
cls.add_method('AddNackedFrame',
'void',
[param('uint8_t', 'frame')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcAck::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcAck::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcAck::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): std::set<unsigned char, std::less<unsigned char>, std::allocator<unsigned char> > const & ns3::UanHeaderRcAck::GetNackedFrames() const [member function]
cls.add_method('GetNackedFrames',
'std::set< unsigned char > const &',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcAck::GetNoNacks() const [member function]
cls.add_method('GetNoNacks',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcAck::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcAck::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcAck::SetFrameNo(uint8_t frameNo) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'frameNo')])
return
def register_Ns3UanHeaderRcCts_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts::UanHeaderRcCts(ns3::UanHeaderRcCts const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcCts const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts::UanHeaderRcCts() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCts::UanHeaderRcCts(uint8_t frameNo, uint8_t retryNo, ns3::Time rtsTs, ns3::Time delay, ns3::UanAddress addr) [constructor]
cls.add_constructor([param('uint8_t', 'frameNo'), param('uint8_t', 'retryNo'), param('ns3::Time', 'rtsTs'), param('ns3::Time', 'delay'), param('ns3::UanAddress', 'addr')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCts::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::UanAddress ns3::UanHeaderRcCts::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::UanAddress',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCts::GetDelayToTx() const [member function]
cls.add_method('GetDelayToTx',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcCts::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcCts::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcCts::GetRetryNo() const [member function]
cls.add_method('GetRetryNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCts::GetRtsTimeStamp() const [member function]
cls.add_method('GetRtsTimeStamp',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCts::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcCts::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetDelayToTx(ns3::Time delay) [member function]
cls.add_method('SetDelayToTx',
'void',
[param('ns3::Time', 'delay')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetFrameNo(uint8_t frameNo) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'frameNo')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetRetryNo(uint8_t no) [member function]
cls.add_method('SetRetryNo',
'void',
[param('uint8_t', 'no')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCts::SetRtsTimeStamp(ns3::Time timeStamp) [member function]
cls.add_method('SetRtsTimeStamp',
'void',
[param('ns3::Time', 'timeStamp')])
return
def register_Ns3UanHeaderRcCtsGlobal_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal(ns3::UanHeaderRcCtsGlobal const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcCtsGlobal const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal(ns3::Time wt, ns3::Time ts, uint16_t rate, uint16_t retryRate) [constructor]
cls.add_constructor([param('ns3::Time', 'wt'), param('ns3::Time', 'ts'), param('uint16_t', 'rate'), param('uint16_t', 'retryRate')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCtsGlobal::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcCtsGlobal::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): uint16_t ns3::UanHeaderRcCtsGlobal::GetRateNum() const [member function]
cls.add_method('GetRateNum',
'uint16_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint16_t ns3::UanHeaderRcCtsGlobal::GetRetryRate() const [member function]
cls.add_method('GetRetryRate',
'uint16_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcCtsGlobal::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCtsGlobal::GetTxTimeStamp() const [member function]
cls.add_method('GetTxTimeStamp',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcCtsGlobal::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcCtsGlobal::GetWindowTime() const [member function]
cls.add_method('GetWindowTime',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetRateNum(uint16_t rate) [member function]
cls.add_method('SetRateNum',
'void',
[param('uint16_t', 'rate')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetRetryRate(uint16_t rate) [member function]
cls.add_method('SetRetryRate',
'void',
[param('uint16_t', 'rate')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetTxTimeStamp(ns3::Time timeStamp) [member function]
cls.add_method('SetTxTimeStamp',
'void',
[param('ns3::Time', 'timeStamp')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcCtsGlobal::SetWindowTime(ns3::Time t) [member function]
cls.add_method('SetWindowTime',
'void',
[param('ns3::Time', 't')])
return
def register_Ns3UanHeaderRcData_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData::UanHeaderRcData(ns3::UanHeaderRcData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcData const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData::UanHeaderRcData() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcData::UanHeaderRcData(uint8_t frameNum, ns3::Time propDelay) [constructor]
cls.add_constructor([param('uint8_t', 'frameNum'), param('ns3::Time', 'propDelay')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcData::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcData::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcData::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcData::GetPropDelay() const [member function]
cls.add_method('GetPropDelay',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcData::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcData::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::SetFrameNo(uint8_t frameNum) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'frameNum')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcData::SetPropDelay(ns3::Time propDelay) [member function]
cls.add_method('SetPropDelay',
'void',
[param('ns3::Time', 'propDelay')])
return
def register_Ns3UanHeaderRcRts_methods(root_module, cls):
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts::UanHeaderRcRts(ns3::UanHeaderRcRts const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanHeaderRcRts const &', 'arg0')])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts::UanHeaderRcRts() [constructor]
cls.add_constructor([])
## uan-header-rc.h (module 'uan'): ns3::UanHeaderRcRts::UanHeaderRcRts(uint8_t frameNo, uint8_t retryNo, uint8_t noFrames, uint16_t length, ns3::Time ts) [constructor]
cls.add_constructor([param('uint8_t', 'frameNo'), param('uint8_t', 'retryNo'), param('uint8_t', 'noFrames'), param('uint16_t', 'length'), param('ns3::Time', 'ts')])
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcRts::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcRts::GetFrameNo() const [member function]
cls.add_method('GetFrameNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): ns3::TypeId ns3::UanHeaderRcRts::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): uint16_t ns3::UanHeaderRcRts::GetLength() const [member function]
cls.add_method('GetLength',
'uint16_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcRts::GetNoFrames() const [member function]
cls.add_method('GetNoFrames',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint8_t ns3::UanHeaderRcRts::GetRetryNo() const [member function]
cls.add_method('GetRetryNo',
'uint8_t',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): uint32_t ns3::UanHeaderRcRts::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): ns3::Time ns3::UanHeaderRcRts::GetTimeStamp() const [member function]
cls.add_method('GetTimeStamp',
'ns3::Time',
[],
is_const=True)
## uan-header-rc.h (module 'uan'): static ns3::TypeId ns3::UanHeaderRcRts::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetFrameNo(uint8_t fno) [member function]
cls.add_method('SetFrameNo',
'void',
[param('uint8_t', 'fno')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetLength(uint16_t length) [member function]
cls.add_method('SetLength',
'void',
[param('uint16_t', 'length')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetNoFrames(uint8_t no) [member function]
cls.add_method('SetNoFrames',
'void',
[param('uint8_t', 'no')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetRetryNo(uint8_t no) [member function]
cls.add_method('SetRetryNo',
'void',
[param('uint8_t', 'no')])
## uan-header-rc.h (module 'uan'): void ns3::UanHeaderRcRts::SetTimeStamp(ns3::Time timeStamp) [member function]
cls.add_method('SetTimeStamp',
'void',
[param('ns3::Time', 'timeStamp')])
return
def register_Ns3UanMac_methods(root_module, cls):
## uan-mac.h (module 'uan'): ns3::UanMac::UanMac() [constructor]
cls.add_constructor([])
## uan-mac.h (module 'uan'): ns3::UanMac::UanMac(ns3::UanMac const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMac const &', 'arg0')])
## uan-mac.h (module 'uan'): void ns3::UanMac::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): void ns3::UanMac::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): bool ns3::UanMac::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): ns3::Address ns3::UanMac::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): ns3::Address ns3::UanMac::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-mac.h (module 'uan'): static ns3::TypeId ns3::UanMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac.h (module 'uan'): void ns3::UanMac::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_pure_virtual=True, is_virtual=True)
## uan-mac.h (module 'uan'): void ns3::UanMac::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3UanMacAloha_methods(root_module, cls):
## uan-mac-aloha.h (module 'uan'): ns3::UanMacAloha::UanMacAloha(ns3::UanMacAloha const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMacAloha const &', 'arg0')])
## uan-mac-aloha.h (module 'uan'): ns3::UanMacAloha::UanMacAloha() [constructor]
cls.add_constructor([])
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): bool ns3::UanMacAloha::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): ns3::Address ns3::UanMacAloha::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): ns3::Address ns3::UanMacAloha::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-mac-aloha.h (module 'uan'): static ns3::TypeId ns3::UanMacAloha::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-mac-aloha.h (module 'uan'): void ns3::UanMacAloha::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanMacCw_methods(root_module, cls):
## uan-mac-cw.h (module 'uan'): ns3::UanMacCw::UanMacCw(ns3::UanMacCw const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMacCw const &', 'arg0')])
## uan-mac-cw.h (module 'uan'): ns3::UanMacCw::UanMacCw() [constructor]
cls.add_constructor([])
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): bool ns3::UanMacCw::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): ns3::Address ns3::UanMacCw::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): ns3::Address ns3::UanMacCw::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-mac-cw.h (module 'uan'): uint32_t ns3::UanMacCw::GetCw() [member function]
cls.add_method('GetCw',
'uint32_t',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): ns3::Time ns3::UanMacCw::GetSlotTime() [member function]
cls.add_method('GetSlotTime',
'ns3::Time',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): static ns3::TypeId ns3::UanMacCw::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyCcaEnd() [member function]
cls.add_method('NotifyCcaEnd',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyCcaStart() [member function]
cls.add_method('NotifyCcaStart',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyRxEndError() [member function]
cls.add_method('NotifyRxEndError',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyRxEndOk() [member function]
cls.add_method('NotifyRxEndOk',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyRxStart() [member function]
cls.add_method('NotifyRxStart',
'void',
[],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::NotifyTxStart(ns3::Time duration) [member function]
cls.add_method('NotifyTxStart',
'void',
[param('ns3::Time', 'duration')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetCw(uint32_t cw) [member function]
cls.add_method('SetCw',
'void',
[param('uint32_t', 'cw')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::SetSlotTime(ns3::Time duration) [member function]
cls.add_method('SetSlotTime',
'void',
[param('ns3::Time', 'duration')],
is_virtual=True)
## uan-mac-cw.h (module 'uan'): void ns3::UanMacCw::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanMacRc_methods(root_module, cls):
## uan-mac-rc.h (module 'uan'): ns3::UanMacRc::UanMacRc(ns3::UanMacRc const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMacRc const &', 'arg0')])
## uan-mac-rc.h (module 'uan'): ns3::UanMacRc::UanMacRc() [constructor]
cls.add_constructor([])
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): bool ns3::UanMacRc::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): ns3::Address ns3::UanMacRc::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): ns3::Address ns3::UanMacRc::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-mac-rc.h (module 'uan'): static ns3::TypeId ns3::UanMacRc::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-mac-rc.h (module 'uan'): void ns3::UanMacRc::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanMacRcGw_methods(root_module, cls):
## uan-mac-rc-gw.h (module 'uan'): ns3::UanMacRcGw::UanMacRcGw(ns3::UanMacRcGw const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanMacRcGw const &', 'arg0')])
## uan-mac-rc-gw.h (module 'uan'): ns3::UanMacRcGw::UanMacRcGw() [constructor]
cls.add_constructor([])
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::AttachPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AttachPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): bool ns3::UanMacRcGw::Enqueue(ns3::Ptr<ns3::Packet> pkt, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): ns3::Address ns3::UanMacRcGw::GetAddress() [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): ns3::Address ns3::UanMacRcGw::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): static ns3::TypeId ns3::UanMacRcGw::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::SetAddress(ns3::UanAddress addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::UanAddress', 'addr')],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::SetForwardUpCb(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCb',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::UanAddress const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-mac-rc-gw.h (module 'uan'): void ns3::UanMacRcGw::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanNoiseModel_methods(root_module, cls):
## uan-noise-model.h (module 'uan'): ns3::UanNoiseModel::UanNoiseModel() [constructor]
cls.add_constructor([])
## uan-noise-model.h (module 'uan'): ns3::UanNoiseModel::UanNoiseModel(ns3::UanNoiseModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanNoiseModel const &', 'arg0')])
## uan-noise-model.h (module 'uan'): void ns3::UanNoiseModel::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-noise-model.h (module 'uan'): void ns3::UanNoiseModel::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## uan-noise-model.h (module 'uan'): double ns3::UanNoiseModel::GetNoiseDbHz(double fKhz) const [member function]
cls.add_method('GetNoiseDbHz',
'double',
[param('double', 'fKhz')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-noise-model.h (module 'uan'): static ns3::TypeId ns3::UanNoiseModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanNoiseModelDefault_methods(root_module, cls):
## uan-noise-model-default.h (module 'uan'): ns3::UanNoiseModelDefault::UanNoiseModelDefault(ns3::UanNoiseModelDefault const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanNoiseModelDefault const &', 'arg0')])
## uan-noise-model-default.h (module 'uan'): ns3::UanNoiseModelDefault::UanNoiseModelDefault() [constructor]
cls.add_constructor([])
## uan-noise-model-default.h (module 'uan'): double ns3::UanNoiseModelDefault::GetNoiseDbHz(double fKhz) const [member function]
cls.add_method('GetNoiseDbHz',
'double',
[param('double', 'fKhz')],
is_const=True, is_virtual=True)
## uan-noise-model-default.h (module 'uan'): static ns3::TypeId ns3::UanNoiseModelDefault::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhy_methods(root_module, cls):
## uan-phy.h (module 'uan'): ns3::UanPhy::UanPhy() [constructor]
cls.add_constructor([])
## uan-phy.h (module 'uan'): ns3::UanPhy::UanPhy(ns3::UanPhy const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhy const &', 'arg0')])
## uan-phy.h (module 'uan'): void ns3::UanPhy::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::EnergyDepletionHandler() [member function]
cls.add_method('EnergyDepletionHandler',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhy::GetCcaThresholdDb() [member function]
cls.add_method('GetCcaThresholdDb',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanPhy::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanPhy::GetDevice() [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::UanNetDevice >',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::UanTxMode ns3::UanPhy::GetMode(uint32_t n) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('uint32_t', 'n')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): uint32_t ns3::UanPhy::GetNModes() [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhy::GetPacketRx() const [member function]
cls.add_method('GetPacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhy::GetRxGainDb() [member function]
cls.add_method('GetRxGainDb',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhy::GetRxThresholdDb() [member function]
cls.add_method('GetRxThresholdDb',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanPhy::GetTransducer() [member function]
cls.add_method('GetTransducer',
'ns3::Ptr< ns3::UanTransducer >',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhy::GetTxPowerDb() [member function]
cls.add_method('GetTxPowerDb',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): static ns3::TypeId ns3::UanPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateSleep() [member function]
cls.add_method('IsStateSleep',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): bool ns3::UanPhy::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyIntChange() [member function]
cls.add_method('NotifyIntChange',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::NotifyTransStartTx(ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('NotifyTransStartTx',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::RegisterListener(ns3::UanPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::UanPhyListener *', 'listener')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SendPacket(ns3::Ptr<ns3::Packet> pkt, uint32_t modeNum) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('uint32_t', 'modeNum')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetCcaThresholdDb(double thresh) [member function]
cls.add_method('SetCcaThresholdDb',
'void',
[param('double', 'thresh')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetDevice(ns3::Ptr<ns3::UanNetDevice> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::UanNetDevice >', 'device')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetEnergyModelCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetEnergyModelCallback',
'void',
[param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::UanMac >', 'mac')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetReceiveErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetReceiveOkCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetRxGainDb(double gain) [member function]
cls.add_method('SetRxGainDb',
'void',
[param('double', 'gain')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetRxThresholdDb(double thresh) [member function]
cls.add_method('SetRxThresholdDb',
'void',
[param('double', 'thresh')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetSleepMode(bool sleep) [member function]
cls.add_method('SetSleepMode',
'void',
[param('bool', 'sleep')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('SetTransducer',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'trans')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::SetTxPowerDb(double txpwr) [member function]
cls.add_method('SetTxPowerDb',
'void',
[param('double', 'txpwr')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhy::StartRxPacket(ns3::Ptr<ns3::Packet> pkt, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('StartRxPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3UanPhyCalcSinr_methods(root_module, cls):
## uan-phy.h (module 'uan'): ns3::UanPhyCalcSinr::UanPhyCalcSinr() [constructor]
cls.add_constructor([])
## uan-phy.h (module 'uan'): ns3::UanPhyCalcSinr::UanPhyCalcSinr(ns3::UanPhyCalcSinr const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyCalcSinr const &', 'arg0')])
## uan-phy.h (module 'uan'): double ns3::UanPhyCalcSinr::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function]
cls.add_method('CalcSinrDb',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyCalcSinr::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-phy.h (module 'uan'): double ns3::UanPhyCalcSinr::DbToKp(double db) const [member function]
cls.add_method('DbToKp',
'double',
[param('double', 'db')],
is_const=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyCalcSinr::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## uan-phy.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinr::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-phy.h (module 'uan'): double ns3::UanPhyCalcSinr::KpToDb(double kp) const [member function]
cls.add_method('KpToDb',
'double',
[param('double', 'kp')],
is_const=True)
return
def register_Ns3UanPhyCalcSinrDefault_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrDefault::UanPhyCalcSinrDefault(ns3::UanPhyCalcSinrDefault const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyCalcSinrDefault const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrDefault::UanPhyCalcSinrDefault() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyCalcSinrDefault::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function]
cls.add_method('CalcSinrDb',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')],
is_const=True, is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinrDefault::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhyCalcSinrDual_methods(root_module, cls):
## uan-phy-dual.h (module 'uan'): ns3::UanPhyCalcSinrDual::UanPhyCalcSinrDual(ns3::UanPhyCalcSinrDual const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyCalcSinrDual const &', 'arg0')])
## uan-phy-dual.h (module 'uan'): ns3::UanPhyCalcSinrDual::UanPhyCalcSinrDual() [constructor]
cls.add_constructor([])
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyCalcSinrDual::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function]
cls.add_method('CalcSinrDb',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')],
is_const=True, is_virtual=True)
## uan-phy-dual.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinrDual::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhyCalcSinrFhFsk_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrFhFsk::UanPhyCalcSinrFhFsk(ns3::UanPhyCalcSinrFhFsk const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyCalcSinrFhFsk const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyCalcSinrFhFsk::UanPhyCalcSinrFhFsk() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyCalcSinrFhFsk::CalcSinrDb(ns3::Ptr<ns3::Packet> pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & arrivalList) const [member function]
cls.add_method('CalcSinrDb',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::Time', 'arrTime'), param('double', 'rxPowerDb'), param('double', 'ambNoiseDb'), param('ns3::UanTxMode', 'mode'), param('ns3::UanPdp', 'pdp'), param('std::list< ns3::UanPacketArrival > const &', 'arrivalList')],
is_const=True, is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyCalcSinrFhFsk::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhyDual_methods(root_module, cls):
## uan-phy-dual.h (module 'uan'): ns3::UanPhyDual::UanPhyDual(ns3::UanPhyDual const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyDual const &', 'arg0')])
## uan-phy-dual.h (module 'uan'): ns3::UanPhyDual::UanPhyDual() [constructor]
cls.add_constructor([])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::EnergyDepletionHandler() [member function]
cls.add_method('EnergyDepletionHandler',
'void',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetCcaThresholdDb() [member function]
cls.add_method('GetCcaThresholdDb',
'double',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetCcaThresholdPhy1() const [member function]
cls.add_method('GetCcaThresholdPhy1',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetCcaThresholdPhy2() const [member function]
cls.add_method('GetCcaThresholdPhy2',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanPhyDual::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_const=True, is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanPhyDual::GetDevice() [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::UanNetDevice >',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::UanTxMode ns3::UanPhyDual::GetMode(uint32_t n) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('uint32_t', 'n')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::UanModesList ns3::UanPhyDual::GetModesPhy1() const [member function]
cls.add_method('GetModesPhy1',
'ns3::UanModesList',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::UanModesList ns3::UanPhyDual::GetModesPhy2() const [member function]
cls.add_method('GetModesPhy2',
'ns3::UanModesList',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): uint32_t ns3::UanPhyDual::GetNModes() [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyDual::GetPacketRx() const [member function]
cls.add_method('GetPacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True, is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyPer> ns3::UanPhyDual::GetPerModelPhy1() const [member function]
cls.add_method('GetPerModelPhy1',
'ns3::Ptr< ns3::UanPhyPer >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyPer> ns3::UanPhyDual::GetPerModelPhy2() const [member function]
cls.add_method('GetPerModelPhy2',
'ns3::Ptr< ns3::UanPhyPer >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyDual::GetPhy1PacketRx() const [member function]
cls.add_method('GetPhy1PacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyDual::GetPhy2PacketRx() const [member function]
cls.add_method('GetPhy2PacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxGainDb() [member function]
cls.add_method('GetRxGainDb',
'double',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxGainDbPhy1() const [member function]
cls.add_method('GetRxGainDbPhy1',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxGainDbPhy2() const [member function]
cls.add_method('GetRxGainDbPhy2',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetRxThresholdDb() [member function]
cls.add_method('GetRxThresholdDb',
'double',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyCalcSinr> ns3::UanPhyDual::GetSinrModelPhy1() const [member function]
cls.add_method('GetSinrModelPhy1',
'ns3::Ptr< ns3::UanPhyCalcSinr >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanPhyCalcSinr> ns3::UanPhyDual::GetSinrModelPhy2() const [member function]
cls.add_method('GetSinrModelPhy2',
'ns3::Ptr< ns3::UanPhyCalcSinr >',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanPhyDual::GetTransducer() [member function]
cls.add_method('GetTransducer',
'ns3::Ptr< ns3::UanTransducer >',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetTxPowerDb() [member function]
cls.add_method('GetTxPowerDb',
'double',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetTxPowerDbPhy1() const [member function]
cls.add_method('GetTxPowerDbPhy1',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): double ns3::UanPhyDual::GetTxPowerDbPhy2() const [member function]
cls.add_method('GetTxPowerDbPhy2',
'double',
[],
is_const=True)
## uan-phy-dual.h (module 'uan'): static ns3::TypeId ns3::UanPhyDual::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy1Idle() [member function]
cls.add_method('IsPhy1Idle',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy1Rx() [member function]
cls.add_method('IsPhy1Rx',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy1Tx() [member function]
cls.add_method('IsPhy1Tx',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy2Idle() [member function]
cls.add_method('IsPhy2Idle',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy2Rx() [member function]
cls.add_method('IsPhy2Rx',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsPhy2Tx() [member function]
cls.add_method('IsPhy2Tx',
'bool',
[])
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateSleep() [member function]
cls.add_method('IsStateSleep',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): bool ns3::UanPhyDual::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::NotifyIntChange() [member function]
cls.add_method('NotifyIntChange',
'void',
[],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::NotifyTransStartTx(ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('NotifyTransStartTx',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::RegisterListener(ns3::UanPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::UanPhyListener *', 'listener')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SendPacket(ns3::Ptr<ns3::Packet> pkt, uint32_t modeNum) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('uint32_t', 'modeNum')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetCcaThresholdDb(double thresh) [member function]
cls.add_method('SetCcaThresholdDb',
'void',
[param('double', 'thresh')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetCcaThresholdPhy1(double thresh) [member function]
cls.add_method('SetCcaThresholdPhy1',
'void',
[param('double', 'thresh')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetCcaThresholdPhy2(double thresh) [member function]
cls.add_method('SetCcaThresholdPhy2',
'void',
[param('double', 'thresh')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetDevice(ns3::Ptr<ns3::UanNetDevice> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::UanNetDevice >', 'device')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetEnergyModelCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetEnergyModelCallback',
'void',
[param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::UanMac >', 'mac')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetModesPhy1(ns3::UanModesList modes) [member function]
cls.add_method('SetModesPhy1',
'void',
[param('ns3::UanModesList', 'modes')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetModesPhy2(ns3::UanModesList modes) [member function]
cls.add_method('SetModesPhy2',
'void',
[param('ns3::UanModesList', 'modes')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetPerModelPhy1(ns3::Ptr<ns3::UanPhyPer> per) [member function]
cls.add_method('SetPerModelPhy1',
'void',
[param('ns3::Ptr< ns3::UanPhyPer >', 'per')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetPerModelPhy2(ns3::Ptr<ns3::UanPhyPer> per) [member function]
cls.add_method('SetPerModelPhy2',
'void',
[param('ns3::Ptr< ns3::UanPhyPer >', 'per')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetReceiveErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetReceiveOkCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxGainDb(double gain) [member function]
cls.add_method('SetRxGainDb',
'void',
[param('double', 'gain')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxGainDbPhy1(double gain) [member function]
cls.add_method('SetRxGainDbPhy1',
'void',
[param('double', 'gain')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxGainDbPhy2(double gain) [member function]
cls.add_method('SetRxGainDbPhy2',
'void',
[param('double', 'gain')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetRxThresholdDb(double thresh) [member function]
cls.add_method('SetRxThresholdDb',
'void',
[param('double', 'thresh')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetSinrModelPhy1(ns3::Ptr<ns3::UanPhyCalcSinr> calcSinr) [member function]
cls.add_method('SetSinrModelPhy1',
'void',
[param('ns3::Ptr< ns3::UanPhyCalcSinr >', 'calcSinr')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetSinrModelPhy2(ns3::Ptr<ns3::UanPhyCalcSinr> calcSinr) [member function]
cls.add_method('SetSinrModelPhy2',
'void',
[param('ns3::Ptr< ns3::UanPhyCalcSinr >', 'calcSinr')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetSleepMode(bool sleep) [member function]
cls.add_method('SetSleepMode',
'void',
[param('bool', 'sleep')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('SetTransducer',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'trans')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTxPowerDb(double txpwr) [member function]
cls.add_method('SetTxPowerDb',
'void',
[param('double', 'txpwr')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTxPowerDbPhy1(double arg0) [member function]
cls.add_method('SetTxPowerDbPhy1',
'void',
[param('double', 'arg0')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::SetTxPowerDbPhy2(double arg0) [member function]
cls.add_method('SetTxPowerDbPhy2',
'void',
[param('double', 'arg0')])
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::StartRxPacket(ns3::Ptr<ns3::Packet> pkt, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('StartRxPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_virtual=True)
## uan-phy-dual.h (module 'uan'): void ns3::UanPhyDual::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanPhyGen_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyGen::UanPhyGen(ns3::UanPhyGen const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyGen const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyGen::UanPhyGen() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::EnergyDepletionHandler() [member function]
cls.add_method('EnergyDepletionHandler',
'void',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetCcaThresholdDb() [member function]
cls.add_method('GetCcaThresholdDb',
'double',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanPhyGen::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_const=True, is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::UanModesList ns3::UanPhyGen::GetDefaultModes() [member function]
cls.add_method('GetDefaultModes',
'ns3::UanModesList',
[],
is_static=True)
## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::UanNetDevice> ns3::UanPhyGen::GetDevice() [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::UanNetDevice >',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): ns3::UanTxMode ns3::UanPhyGen::GetMode(uint32_t n) [member function]
cls.add_method('GetMode',
'ns3::UanTxMode',
[param('uint32_t', 'n')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): uint32_t ns3::UanPhyGen::GetNModes() [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::Packet> ns3::UanPhyGen::GetPacketRx() const [member function]
cls.add_method('GetPacketRx',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True, is_virtual=True)
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetRxGainDb() [member function]
cls.add_method('GetRxGainDb',
'double',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetRxThresholdDb() [member function]
cls.add_method('GetRxThresholdDb',
'double',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanPhyGen::GetTransducer() [member function]
cls.add_method('GetTransducer',
'ns3::Ptr< ns3::UanTransducer >',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyGen::GetTxPowerDb() [member function]
cls.add_method('GetTxPowerDb',
'double',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyGen::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateSleep() [member function]
cls.add_method('IsStateSleep',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): bool ns3::UanPhyGen::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::NotifyIntChange() [member function]
cls.add_method('NotifyIntChange',
'void',
[],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::NotifyTransStartTx(ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('NotifyTransStartTx',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::RegisterListener(ns3::UanPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::UanPhyListener *', 'listener')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SendPacket(ns3::Ptr<ns3::Packet> pkt, uint32_t modeNum) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('uint32_t', 'modeNum')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetCcaThresholdDb(double thresh) [member function]
cls.add_method('SetCcaThresholdDb',
'void',
[param('double', 'thresh')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'channel')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetDevice(ns3::Ptr<ns3::UanNetDevice> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::UanNetDevice >', 'device')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetEnergyModelCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetEnergyModelCallback',
'void',
[param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::UanMac >', 'mac')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetReceiveErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetReceiveOkCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetRxGainDb(double gain) [member function]
cls.add_method('SetRxGainDb',
'void',
[param('double', 'gain')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetRxThresholdDb(double thresh) [member function]
cls.add_method('SetRxThresholdDb',
'void',
[param('double', 'thresh')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetSleepMode(bool sleep) [member function]
cls.add_method('SetSleepMode',
'void',
[param('bool', 'sleep')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('SetTransducer',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'trans')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::SetTxPowerDb(double txpwr) [member function]
cls.add_method('SetTxPowerDb',
'void',
[param('double', 'txpwr')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::StartRxPacket(ns3::Ptr<ns3::Packet> pkt, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('StartRxPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): void ns3::UanPhyGen::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanPhyPer_methods(root_module, cls):
## uan-phy.h (module 'uan'): ns3::UanPhyPer::UanPhyPer() [constructor]
cls.add_constructor([])
## uan-phy.h (module 'uan'): ns3::UanPhyPer::UanPhyPer(ns3::UanPhyPer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyPer const &', 'arg0')])
## uan-phy.h (module 'uan'): double ns3::UanPhyPer::CalcPer(ns3::Ptr<ns3::Packet> pkt, double sinrDb, ns3::UanTxMode mode) [member function]
cls.add_method('CalcPer',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')],
is_pure_virtual=True, is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyPer::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-phy.h (module 'uan'): void ns3::UanPhyPer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## uan-phy.h (module 'uan'): static ns3::TypeId ns3::UanPhyPer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhyPerGenDefault_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerGenDefault::UanPhyPerGenDefault(ns3::UanPhyPerGenDefault const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyPerGenDefault const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerGenDefault::UanPhyPerGenDefault() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyPerGenDefault::CalcPer(ns3::Ptr<ns3::Packet> pkt, double sinrDb, ns3::UanTxMode mode) [member function]
cls.add_method('CalcPer',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyPerGenDefault::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPhyPerUmodem_methods(root_module, cls):
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerUmodem::UanPhyPerUmodem(ns3::UanPhyPerUmodem const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPhyPerUmodem const &', 'arg0')])
## uan-phy-gen.h (module 'uan'): ns3::UanPhyPerUmodem::UanPhyPerUmodem() [constructor]
cls.add_constructor([])
## uan-phy-gen.h (module 'uan'): double ns3::UanPhyPerUmodem::CalcPer(ns3::Ptr<ns3::Packet> pkt, double sinrDb, ns3::UanTxMode mode) [member function]
cls.add_method('CalcPer',
'double',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-phy-gen.h (module 'uan'): static ns3::TypeId ns3::UanPhyPerUmodem::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPropModel_methods(root_module, cls):
## uan-prop-model.h (module 'uan'): ns3::UanPropModel::UanPropModel() [constructor]
cls.add_constructor([])
## uan-prop-model.h (module 'uan'): ns3::UanPropModel::UanPropModel(ns3::UanPropModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPropModel const &', 'arg0')])
## uan-prop-model.h (module 'uan'): void ns3::UanPropModel::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-prop-model.h (module 'uan'): void ns3::UanPropModel::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## uan-prop-model.h (module 'uan'): ns3::Time ns3::UanPropModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_pure_virtual=True, is_virtual=True)
## uan-prop-model.h (module 'uan'): double ns3::UanPropModel::GetPathLossDb(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode txMode) [member function]
cls.add_method('GetPathLossDb',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
## uan-prop-model.h (module 'uan'): ns3::UanPdp ns3::UanPropModel::GetPdp(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPdp',
'ns3::UanPdp',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_pure_virtual=True, is_virtual=True)
## uan-prop-model.h (module 'uan'): static ns3::TypeId ns3::UanPropModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPropModelIdeal_methods(root_module, cls):
## uan-prop-model-ideal.h (module 'uan'): ns3::UanPropModelIdeal::UanPropModelIdeal(ns3::UanPropModelIdeal const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPropModelIdeal const &', 'arg0')])
## uan-prop-model-ideal.h (module 'uan'): ns3::UanPropModelIdeal::UanPropModelIdeal() [constructor]
cls.add_constructor([])
## uan-prop-model-ideal.h (module 'uan'): ns3::Time ns3::UanPropModelIdeal::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-ideal.h (module 'uan'): double ns3::UanPropModelIdeal::GetPathLossDb(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPathLossDb',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-ideal.h (module 'uan'): ns3::UanPdp ns3::UanPropModelIdeal::GetPdp(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPdp',
'ns3::UanPdp',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-ideal.h (module 'uan'): static ns3::TypeId ns3::UanPropModelIdeal::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanPropModelThorp_methods(root_module, cls):
## uan-prop-model-thorp.h (module 'uan'): ns3::UanPropModelThorp::UanPropModelThorp(ns3::UanPropModelThorp const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanPropModelThorp const &', 'arg0')])
## uan-prop-model-thorp.h (module 'uan'): ns3::UanPropModelThorp::UanPropModelThorp() [constructor]
cls.add_constructor([])
## uan-prop-model-thorp.h (module 'uan'): ns3::Time ns3::UanPropModelThorp::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-thorp.h (module 'uan'): double ns3::UanPropModelThorp::GetPathLossDb(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPathLossDb',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-thorp.h (module 'uan'): ns3::UanPdp ns3::UanPropModelThorp::GetPdp(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, ns3::UanTxMode mode) [member function]
cls.add_method('GetPdp',
'ns3::UanPdp',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('ns3::UanTxMode', 'mode')],
is_virtual=True)
## uan-prop-model-thorp.h (module 'uan'): static ns3::TypeId ns3::UanPropModelThorp::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3UanTransducer_methods(root_module, cls):
## uan-transducer.h (module 'uan'): ns3::UanTransducer::UanTransducer() [constructor]
cls.add_constructor([])
## uan-transducer.h (module 'uan'): ns3::UanTransducer::UanTransducer(ns3::UanTransducer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanTransducer const &', 'arg0')])
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::AddPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('AddPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')],
is_pure_virtual=True, is_virtual=True)
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## uan-transducer.h (module 'uan'): std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & ns3::UanTransducer::GetArrivalList() const [member function]
cls.add_method('GetArrivalList',
'std::list< ns3::UanPacketArrival > const &',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanTransducer::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): std::list<ns3::Ptr<ns3::UanPhy>, std::allocator<ns3::Ptr<ns3::UanPhy> > > const & ns3::UanTransducer::GetPhyList() const [member function]
cls.add_method('GetPhyList',
'std::list< ns3::Ptr< ns3::UanPhy > > const &',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): ns3::UanTransducer::State ns3::UanTransducer::GetState() const [member function]
cls.add_method('GetState',
'ns3::UanTransducer::State',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): static ns3::TypeId ns3::UanTransducer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-transducer.h (module 'uan'): bool ns3::UanTransducer::IsRx() const [member function]
cls.add_method('IsRx',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): bool ns3::UanTransducer::IsTx() const [member function]
cls.add_method('IsTx',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::Receive(ns3::Ptr<ns3::Packet> packet, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_pure_virtual=True, is_virtual=True)
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::SetChannel(ns3::Ptr<ns3::UanChannel> chan) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'chan')],
is_pure_virtual=True, is_virtual=True)
## uan-transducer.h (module 'uan'): void ns3::UanTransducer::Transmit(ns3::Ptr<ns3::UanPhy> src, ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('Transmit',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3UanTransducerHd_methods(root_module, cls):
## uan-transducer-hd.h (module 'uan'): ns3::UanTransducerHd::UanTransducerHd(ns3::UanTransducerHd const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanTransducerHd const &', 'arg0')])
## uan-transducer-hd.h (module 'uan'): ns3::UanTransducerHd::UanTransducerHd() [constructor]
cls.add_constructor([])
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::AddPhy(ns3::Ptr<ns3::UanPhy> arg0) [member function]
cls.add_method('AddPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'arg0')],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): std::list<ns3::UanPacketArrival, std::allocator<ns3::UanPacketArrival> > const & ns3::UanTransducerHd::GetArrivalList() const [member function]
cls.add_method('GetArrivalList',
'std::list< ns3::UanPacketArrival > const &',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): ns3::Ptr<ns3::UanChannel> ns3::UanTransducerHd::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::UanChannel >',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): std::list<ns3::Ptr<ns3::UanPhy>, std::allocator<ns3::Ptr<ns3::UanPhy> > > const & ns3::UanTransducerHd::GetPhyList() const [member function]
cls.add_method('GetPhyList',
'std::list< ns3::Ptr< ns3::UanPhy > > const &',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): ns3::UanTransducer::State ns3::UanTransducerHd::GetState() const [member function]
cls.add_method('GetState',
'ns3::UanTransducer::State',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): static ns3::TypeId ns3::UanTransducerHd::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-transducer-hd.h (module 'uan'): bool ns3::UanTransducerHd::IsRx() const [member function]
cls.add_method('IsRx',
'bool',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): bool ns3::UanTransducerHd::IsTx() const [member function]
cls.add_method('IsTx',
'bool',
[],
is_const=True, is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::Receive(ns3::Ptr<ns3::Packet> packet, double rxPowerDb, ns3::UanTxMode txMode, ns3::UanPdp pdp) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDb'), param('ns3::UanTxMode', 'txMode'), param('ns3::UanPdp', 'pdp')],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::SetChannel(ns3::Ptr<ns3::UanChannel> chan) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'chan')],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::Transmit(ns3::Ptr<ns3::UanPhy> src, ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txMode) [member function]
cls.add_method('Transmit',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txMode')],
is_virtual=True)
## uan-transducer-hd.h (module 'uan'): void ns3::UanTransducerHd::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3BooleanChecker_methods(root_module, cls):
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')])
return
def register_Ns3BooleanValue_methods(root_module, cls):
cls.add_output_stream_operator()
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor]
cls.add_constructor([param('bool', 'value')])
## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function]
cls.add_method('Get',
'bool',
[],
is_const=True)
## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function]
cls.add_method('Set',
'void',
[param('bool', 'value')])
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_Ns3Channel_methods(root_module, cls):
## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Channel const &', 'arg0')])
## channel.h (module 'network'): ns3::Channel::Channel() [constructor]
cls.add_constructor([])
## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3DeviceEnergyModel_methods(root_module, cls):
## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel::DeviceEnergyModel(ns3::DeviceEnergyModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeviceEnergyModel const &', 'arg0')])
## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel::DeviceEnergyModel() [constructor]
cls.add_constructor([])
## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::ChangeState(int newState) [member function]
cls.add_method('ChangeState',
'void',
[param('int', 'newState')],
is_pure_virtual=True, is_virtual=True)
## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::GetCurrentA() const [member function]
cls.add_method('GetCurrentA',
'double',
[],
is_const=True)
## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::GetTotalEnergyConsumption() const [member function]
cls.add_method('GetTotalEnergyConsumption',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## device-energy-model.h (module 'energy'): static ns3::TypeId ns3::DeviceEnergyModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::HandleEnergyDepletion() [member function]
cls.add_method('HandleEnergyDepletion',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function]
cls.add_method('SetEnergySource',
'void',
[param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_pure_virtual=True, is_virtual=True)
## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::DoGetCurrentA() const [member function]
cls.add_method('DoGetCurrentA',
'double',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3DoubleValue_methods(root_module, cls):
## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor]
cls.add_constructor([])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor]
cls.add_constructor([param('double const &', 'value')])
## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## double.h (module 'core'): bool ns3::DoubleValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function]
cls.add_method('Get',
'double',
[],
is_const=True)
## double.h (module 'core'): std::string ns3::DoubleValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function]
cls.add_method('Set',
'void',
[param('double const &', 'value')])
return
def register_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, visibility='private', is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
visibility='private', is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EnergySource_methods(root_module, cls):
## energy-source.h (module 'energy'): ns3::EnergySource::EnergySource(ns3::EnergySource const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnergySource const &', 'arg0')])
## energy-source.h (module 'energy'): ns3::EnergySource::EnergySource() [constructor]
cls.add_constructor([])
## energy-source.h (module 'energy'): void ns3::EnergySource::AppendDeviceEnergyModel(ns3::Ptr<ns3::DeviceEnergyModel> deviceEnergyModelPtr) [member function]
cls.add_method('AppendDeviceEnergyModel',
'void',
[param('ns3::Ptr< ns3::DeviceEnergyModel >', 'deviceEnergyModelPtr')])
## energy-source.h (module 'energy'): void ns3::EnergySource::DisposeDeviceModels() [member function]
cls.add_method('DisposeDeviceModels',
'void',
[])
## energy-source.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::EnergySource::FindDeviceEnergyModels(ns3::TypeId tid) [member function]
cls.add_method('FindDeviceEnergyModels',
'ns3::DeviceEnergyModelContainer',
[param('ns3::TypeId', 'tid')])
## energy-source.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::EnergySource::FindDeviceEnergyModels(std::string name) [member function]
cls.add_method('FindDeviceEnergyModels',
'ns3::DeviceEnergyModelContainer',
[param('std::string', 'name')])
## energy-source.h (module 'energy'): double ns3::EnergySource::GetEnergyFraction() [member function]
cls.add_method('GetEnergyFraction',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## energy-source.h (module 'energy'): double ns3::EnergySource::GetInitialEnergy() const [member function]
cls.add_method('GetInitialEnergy',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## energy-source.h (module 'energy'): ns3::Ptr<ns3::Node> ns3::EnergySource::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True)
## energy-source.h (module 'energy'): double ns3::EnergySource::GetRemainingEnergy() [member function]
cls.add_method('GetRemainingEnergy',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## energy-source.h (module 'energy'): double ns3::EnergySource::GetSupplyVoltage() const [member function]
cls.add_method('GetSupplyVoltage',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## energy-source.h (module 'energy'): static ns3::TypeId ns3::EnergySource::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## energy-source.h (module 'energy'): void ns3::EnergySource::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## energy-source.h (module 'energy'): void ns3::EnergySource::StartDeviceModels() [member function]
cls.add_method('StartDeviceModels',
'void',
[])
## energy-source.h (module 'energy'): void ns3::EnergySource::UpdateEnergySource() [member function]
cls.add_method('UpdateEnergySource',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## energy-source.h (module 'energy'): void ns3::EnergySource::BreakDeviceEnergyModelRefCycle() [member function]
cls.add_method('BreakDeviceEnergyModelRefCycle',
'void',
[],
visibility='protected')
## energy-source.h (module 'energy'): double ns3::EnergySource::CalculateTotalCurrent() [member function]
cls.add_method('CalculateTotalCurrent',
'double',
[],
visibility='protected')
## energy-source.h (module 'energy'): void ns3::EnergySource::NotifyEnergyDrained() [member function]
cls.add_method('NotifyEnergyDrained',
'void',
[],
visibility='protected')
## energy-source.h (module 'energy'): void ns3::EnergySource::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EnergySourceContainer_methods(root_module, cls):
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::EnergySourceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnergySourceContainer const &', 'arg0')])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer() [constructor]
cls.add_constructor([])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::Ptr<ns3::EnergySource> source) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EnergySource >', 'source')])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(std::string sourceName) [constructor]
cls.add_constructor([param('std::string', 'sourceName')])
## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::EnergySourceContainer const & a, ns3::EnergySourceContainer const & b) [constructor]
cls.add_constructor([param('ns3::EnergySourceContainer const &', 'a'), param('ns3::EnergySourceContainer const &', 'b')])
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(ns3::EnergySourceContainer container) [member function]
cls.add_method('Add',
'void',
[param('ns3::EnergySourceContainer', 'container')])
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(ns3::Ptr<ns3::EnergySource> source) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::EnergySource >', 'source')])
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(std::string sourceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'sourceName')])
## energy-source-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::EnergySource>*,std::vector<ns3::Ptr<ns3::EnergySource>, std::allocator<ns3::Ptr<ns3::EnergySource> > > > ns3::EnergySourceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::EnergySource > const, std::vector< ns3::Ptr< ns3::EnergySource > > >',
[],
is_const=True)
## energy-source-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::EnergySource>*,std::vector<ns3::Ptr<ns3::EnergySource>, std::allocator<ns3::Ptr<ns3::EnergySource> > > > ns3::EnergySourceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::EnergySource > const, std::vector< ns3::Ptr< ns3::EnergySource > > >',
[],
is_const=True)
## energy-source-container.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergySourceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::EnergySource >',
[param('uint32_t', 'i')],
is_const=True)
## energy-source-container.h (module 'energy'): uint32_t ns3::EnergySourceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## energy-source-container.h (module 'energy'): static ns3::TypeId ns3::EnergySourceContainer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EnumChecker_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): void ns3::EnumChecker::Add(int v, std::string name) [member function]
cls.add_method('Add',
'void',
[param('int', 'v'), param('std::string', 'name')])
## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int v, std::string name) [member function]
cls.add_method('AddDefault',
'void',
[param('int', 'v'), param('std::string', 'name')])
## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EnumValue_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumValue const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): ns3::EnumValue::EnumValue(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function]
cls.add_method('Get',
'int',
[],
is_const=True)
## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): void ns3::EnumValue::Set(int v) [member function]
cls.add_method('Set',
'void',
[param('int', 'v')])
return
def register_Ns3EventImpl_methods(root_module, cls):
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventImpl const &', 'arg0')])
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor]
cls.add_constructor([])
## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[])
## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function]
cls.add_method('IsCancelled',
'bool',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function]
cls.add_method('Notify',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3IntegerValue_methods(root_module, cls):
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor]
cls.add_constructor([])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor]
cls.add_constructor([param('int64_t const &', 'value')])
## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## integer.h (module 'core'): bool ns3::IntegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function]
cls.add_method('Get',
'int64_t',
[],
is_const=True)
## integer.h (module 'core'): std::string ns3::IntegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('int64_t const &', 'value')])
return
def register_Ns3Ipv4AddressChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv4AddressValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Address const &', 'value')])
return
def register_Ns3Ipv4MaskChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')])
return
def register_Ns3Ipv4MaskValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Mask const &', 'value')])
return
def register_Ns3Ipv6AddressChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv6AddressValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Address const &', 'value')])
return
def register_Ns3Ipv6PrefixChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')])
return
def register_Ns3Ipv6PrefixValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Prefix',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Prefix const &', 'value')])
return
def register_Ns3MobilityModel_methods(root_module, cls):
## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel(ns3::MobilityModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MobilityModel const &', 'arg0')])
## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel() [constructor]
cls.add_constructor([])
## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr<const ns3::MobilityModel> position) const [member function]
cls.add_method('GetDistanceFrom',
'double',
[param('ns3::Ptr< ns3::MobilityModel const >', 'position')],
is_const=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetPosition() const [member function]
cls.add_method('GetPosition',
'ns3::Vector',
[],
is_const=True)
## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetRelativeSpeed(ns3::Ptr<const ns3::MobilityModel> other) const [member function]
cls.add_method('GetRelativeSpeed',
'double',
[param('ns3::Ptr< ns3::MobilityModel const >', 'other')],
is_const=True)
## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function]
cls.add_method('GetVelocity',
'ns3::Vector',
[],
is_const=True)
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function]
cls.add_method('SetPosition',
'void',
[param('ns3::Vector const &', 'position')])
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function]
cls.add_method('NotifyCourseChange',
'void',
[],
is_const=True, visibility='protected')
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function]
cls.add_method('DoGetPosition',
'ns3::Vector',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function]
cls.add_method('DoGetVelocity',
'ns3::Vector',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function]
cls.add_method('DoSetPosition',
'void',
[param('ns3::Vector const &', 'position')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3NetDevice_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDevice const &', 'arg0')])
## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3NixVector_methods(root_module, cls):
cls.add_output_stream_operator()
## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor]
cls.add_constructor([])
## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor]
cls.add_constructor([param('ns3::NixVector const &', 'o')])
## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function]
cls.add_method('AddNeighborIndex',
'void',
[param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function]
cls.add_method('BitCount',
'uint32_t',
[param('uint32_t', 'numberOfNeighbors')],
is_const=True)
## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint32_t const *', 'buffer'), param('uint32_t', 'size')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function]
cls.add_method('ExtractNeighborIndex',
'uint32_t',
[param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function]
cls.add_method('GetRemainingBits',
'uint32_t',
[])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3Node_methods(root_module, cls):
## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Node const &', 'arg0')])
## node.h (module 'network'): ns3::Node::Node() [constructor]
cls.add_constructor([])
## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor]
cls.add_constructor([param('uint32_t', 'systemId')])
## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('AddApplication',
'uint32_t',
[param('ns3::Ptr< ns3::Application >', 'application')])
## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddDevice',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function]
cls.add_method('ChecksumEnabled',
'bool',
[],
is_static=True)
## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function]
cls.add_method('GetApplication',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function]
cls.add_method('GetNApplications',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('RegisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function]
cls.add_method('RegisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')])
## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('UnregisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function]
cls.add_method('UnregisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')])
## node.h (module 'network'): void ns3::Node::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## node.h (module 'network'): void ns3::Node::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectFactoryChecker_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')])
return
def register_Ns3ObjectFactoryValue_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'value')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function]
cls.add_method('Get',
'ns3::ObjectFactory',
[],
is_const=True)
## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::ObjectFactory const &', 'value')])
return
def register_Ns3Packet_methods(root_module, cls):
cls.add_output_stream_operator()
## packet.h (module 'network'): ns3::Packet::Packet() [constructor]
cls.add_constructor([])
## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor]
cls.add_constructor([param('ns3::Packet const &', 'o')])
## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor]
cls.add_constructor([param('uint32_t', 'size')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddByteTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header')])
## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddPacketTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer')])
## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function]
cls.add_method('EnablePrinting',
'void',
[],
is_static=True)
## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function]
cls.add_method('FindFirstMatchingByteTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function]
cls.add_method('GetByteTagIterator',
'ns3::ByteTagIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function]
cls.add_method('GetNixVector',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function]
cls.add_method('GetPacketTagIterator',
'ns3::PacketTagIterator',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
deprecated=True, is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function]
cls.add_method('PeekHeader',
'uint32_t',
[param('ns3::Header &', 'header')],
is_const=True)
## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function]
cls.add_method('PeekPacketTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('PeekTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function]
cls.add_method('PrintByteTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function]
cls.add_method('PrintPacketTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function]
cls.add_method('RemoveAllByteTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function]
cls.add_method('RemoveAllPacketTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function]
cls.add_method('RemoveHeader',
'uint32_t',
[param('ns3::Header &', 'header')])
## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function]
cls.add_method('RemovePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('RemoveTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): 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> arg0) [member function]
cls.add_method('SetNixVector',
'void',
[param('ns3::Ptr< ns3::NixVector >', 'arg0')])
return
def register_Ns3PointerChecker_methods(root_module, cls):
## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker() [constructor]
cls.add_constructor([])
## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker(ns3::PointerChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PointerChecker const &', 'arg0')])
## pointer.h (module 'core'): ns3::TypeId ns3::PointerChecker::GetPointeeTypeId() const [member function]
cls.add_method('GetPointeeTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3PointerValue_methods(root_module, cls):
## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::PointerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PointerValue const &', 'arg0')])
## pointer.h (module 'core'): ns3::PointerValue::PointerValue() [constructor]
cls.add_constructor([])
## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::Ptr<ns3::Object> object) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Object >', 'object')])
## pointer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::PointerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## pointer.h (module 'core'): bool ns3::PointerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## pointer.h (module 'core'): ns3::Ptr<ns3::Object> ns3::PointerValue::GetObject() const [member function]
cls.add_method('GetObject',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## pointer.h (module 'core'): std::string ns3::PointerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## pointer.h (module 'core'): void ns3::PointerValue::SetObject(ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('SetObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'object')])
return
def register_Ns3TimeChecker_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker(ns3::TimeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeChecker const &', 'arg0')])
return
def register_Ns3TimeValue_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeValue const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor]
cls.add_constructor([param('ns3::Time const &', 'value')])
## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function]
cls.add_method('Get',
'ns3::Time',
[],
is_const=True)
## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Time const &', 'value')])
return
def register_Ns3TypeIdChecker_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')])
return
def register_Ns3TypeIdValue_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor]
cls.add_constructor([param('ns3::TypeId const &', 'value')])
## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function]
cls.add_method('Get',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::TypeId const &', 'value')])
return
def register_Ns3UanChannel_methods(root_module, cls):
## uan-channel.h (module 'uan'): ns3::UanChannel::UanChannel(ns3::UanChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanChannel const &', 'arg0')])
## uan-channel.h (module 'uan'): ns3::UanChannel::UanChannel() [constructor]
cls.add_constructor([])
## uan-channel.h (module 'uan'): void ns3::UanChannel::AddDevice(ns3::Ptr<ns3::UanNetDevice> dev, ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('AddDevice',
'void',
[param('ns3::Ptr< ns3::UanNetDevice >', 'dev'), param('ns3::Ptr< ns3::UanTransducer >', 'trans')])
## uan-channel.h (module 'uan'): void ns3::UanChannel::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## uan-channel.h (module 'uan'): ns3::Ptr<ns3::NetDevice> ns3::UanChannel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## uan-channel.h (module 'uan'): uint32_t ns3::UanChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-channel.h (module 'uan'): double ns3::UanChannel::GetNoiseDbHz(double fKhz) [member function]
cls.add_method('GetNoiseDbHz',
'double',
[param('double', 'fKhz')])
## uan-channel.h (module 'uan'): static ns3::TypeId ns3::UanChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-channel.h (module 'uan'): void ns3::UanChannel::SetNoiseModel(ns3::Ptr<ns3::UanNoiseModel> noise) [member function]
cls.add_method('SetNoiseModel',
'void',
[param('ns3::Ptr< ns3::UanNoiseModel >', 'noise')])
## uan-channel.h (module 'uan'): void ns3::UanChannel::SetPropagationModel(ns3::Ptr<ns3::UanPropModel> prop) [member function]
cls.add_method('SetPropagationModel',
'void',
[param('ns3::Ptr< ns3::UanPropModel >', 'prop')])
## uan-channel.h (module 'uan'): void ns3::UanChannel::TxPacket(ns3::Ptr<ns3::UanTransducer> src, ns3::Ptr<ns3::Packet> packet, double txPowerDb, ns3::UanTxMode txmode) [member function]
cls.add_method('TxPacket',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txmode')])
## uan-channel.h (module 'uan'): void ns3::UanChannel::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3UanModesListChecker_methods(root_module, cls):
## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker::UanModesListChecker() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker::UanModesListChecker(ns3::UanModesListChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanModesListChecker const &', 'arg0')])
return
def register_Ns3UanModesListValue_methods(root_module, cls):
## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue() [constructor]
cls.add_constructor([])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue(ns3::UanModesListValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanModesListValue const &', 'arg0')])
## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue(ns3::UanModesList const & value) [constructor]
cls.add_constructor([param('ns3::UanModesList const &', 'value')])
## uan-tx-mode.h (module 'uan'): ns3::Ptr<ns3::AttributeValue> ns3::UanModesListValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## uan-tx-mode.h (module 'uan'): bool ns3::UanModesListValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## uan-tx-mode.h (module 'uan'): ns3::UanModesList ns3::UanModesListValue::Get() const [member function]
cls.add_method('Get',
'ns3::UanModesList',
[],
is_const=True)
## uan-tx-mode.h (module 'uan'): std::string ns3::UanModesListValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## uan-tx-mode.h (module 'uan'): void ns3::UanModesListValue::Set(ns3::UanModesList const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::UanModesList const &', 'value')])
return
def register_Ns3UanNetDevice_methods(root_module, cls):
## uan-net-device.h (module 'uan'): ns3::UanNetDevice::UanNetDevice(ns3::UanNetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UanNetDevice const &', 'arg0')])
## uan-net-device.h (module 'uan'): ns3::UanNetDevice::UanNetDevice() [constructor]
cls.add_constructor([])
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::Channel> ns3::UanNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): uint32_t ns3::UanNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::UanMac> ns3::UanNetDevice::GetMac() const [member function]
cls.add_method('GetMac',
'ns3::Ptr< ns3::UanMac >',
[],
is_const=True)
## uan-net-device.h (module 'uan'): uint16_t ns3::UanNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::Node> ns3::UanNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::UanPhy> ns3::UanNetDevice::GetPhy() const [member function]
cls.add_method('GetPhy',
'ns3::Ptr< ns3::UanPhy >',
[],
is_const=True)
## uan-net-device.h (module 'uan'): ns3::Ptr<ns3::UanTransducer> ns3::UanNetDevice::GetTransducer() const [member function]
cls.add_method('GetTransducer',
'ns3::Ptr< ns3::UanTransducer >',
[],
is_const=True)
## uan-net-device.h (module 'uan'): static ns3::TypeId ns3::UanNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetChannel(ns3::Ptr<ns3::UanChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::UanChannel >', 'channel')])
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetMac(ns3::Ptr<ns3::UanMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::UanMac >', 'mac')])
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetPhy(ns3::Ptr<ns3::UanPhy> phy) [member function]
cls.add_method('SetPhy',
'void',
[param('ns3::Ptr< ns3::UanPhy >', 'phy')])
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetSleepMode(bool sleep) [member function]
cls.add_method('SetSleepMode',
'void',
[param('bool', 'sleep')])
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetTransducer(ns3::Ptr<ns3::UanTransducer> trans) [member function]
cls.add_method('SetTransducer',
'void',
[param('ns3::Ptr< ns3::UanTransducer >', 'trans')])
## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::ForwardUp(ns3::Ptr<ns3::Packet> pkt, ns3::UanAddress const & src) [member function]
cls.add_method('ForwardUp',
'void',
[param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::UanAddress const &', 'src')],
visibility='private', is_virtual=True)
return
def register_Ns3UintegerValue_methods(root_module, cls):
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor]
cls.add_constructor([])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor]
cls.add_constructor([param('uint64_t const &', 'value')])
## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function]
cls.add_method('Get',
'uint64_t',
[],
is_const=True)
## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('uint64_t const &', 'value')])
return
def register_Ns3Vector2DChecker_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')])
return
def register_Ns3Vector2DValue_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor]
cls.add_constructor([param('ns3::Vector2D const &', 'value')])
## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector2DValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## vector.h (module 'core'): bool ns3::Vector2DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function]
cls.add_method('Get',
'ns3::Vector2D',
[],
is_const=True)
## vector.h (module 'core'): std::string ns3::Vector2DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Vector2D const &', 'value')])
return
def register_Ns3Vector3DChecker_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')])
return
def register_Ns3Vector3DValue_methods(root_module, cls):
## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor]
cls.add_constructor([])
## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')])
## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor]
cls.add_constructor([param('ns3::Vector3D const &', 'value')])
## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector3DValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## vector.h (module 'core'): bool ns3::Vector3DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function]
cls.add_method('Get',
'ns3::Vector3D',
[],
is_const=True)
## vector.h (module 'core'): std::string ns3::Vector3DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Vector3D const &', 'value')])
return
def register_Ns3AcousticModemEnergyModel_methods(root_module, cls):
## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel::AcousticModemEnergyModel(ns3::AcousticModemEnergyModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AcousticModemEnergyModel const &', 'arg0')])
## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel::AcousticModemEnergyModel() [constructor]
cls.add_constructor([])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::ChangeState(int newState) [member function]
cls.add_method('ChangeState',
'void',
[param('int', 'newState')],
is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): int ns3::AcousticModemEnergyModel::GetCurrentState() const [member function]
cls.add_method('GetCurrentState',
'int',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetIdlePowerW() const [member function]
cls.add_method('GetIdlePowerW',
'double',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): ns3::Ptr<ns3::Node> ns3::AcousticModemEnergyModel::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetRxPowerW() const [member function]
cls.add_method('GetRxPowerW',
'double',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetSleepPowerW() const [member function]
cls.add_method('GetSleepPowerW',
'double',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetTotalEnergyConsumption() const [member function]
cls.add_method('GetTotalEnergyConsumption',
'double',
[],
is_const=True, is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetTxPowerW() const [member function]
cls.add_method('GetTxPowerW',
'double',
[],
is_const=True)
## acoustic-modem-energy-model.h (module 'uan'): static ns3::TypeId ns3::AcousticModemEnergyModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::HandleEnergyDepletion() [member function]
cls.add_method('HandleEnergyDepletion',
'void',
[],
is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergyDepletionCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetEnergyDepletionCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function]
cls.add_method('SetEnergySource',
'void',
[param('ns3::Ptr< ns3::EnergySource >', 'source')],
is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetIdlePowerW(double idlePowerW) [member function]
cls.add_method('SetIdlePowerW',
'void',
[param('double', 'idlePowerW')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetRxPowerW(double rxPowerW) [member function]
cls.add_method('SetRxPowerW',
'void',
[param('double', 'rxPowerW')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetSleepPowerW(double sleepPowerW) [member function]
cls.add_method('SetSleepPowerW',
'void',
[param('double', 'sleepPowerW')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetTxPowerW(double txPowerW) [member function]
cls.add_method('SetTxPowerW',
'void',
[param('double', 'txPowerW')])
## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::DoGetCurrentA() const [member function]
cls.add_method('DoGetCurrentA',
'double',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AddressChecker_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')])
return
def register_Ns3AddressValue_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressValue const &', 'arg0')])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor]
cls.add_constructor([param('ns3::Address const &', 'value')])
## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Address',
[],
is_const=True)
## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Address const &', 'value')])
return
def register_functions(root_module):
module = root_module
## uan-tx-mode.h (module 'uan'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeUanModesListChecker() [free function]
module.add_function('MakeUanModesListChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module)
register_functions_ns3_internal(module.get_submodule('internal'), root_module)
return
def register_functions_ns3_FatalImpl(module, root_module):
return
def register_functions_ns3_internal(module, root_module):
return
def main():
out = FileCodeSink(sys.stdout)
root_module = module_init()
register_types(root_module)
register_methods(root_module)
register_functions(root_module)
root_module.generate(out)
if __name__ == '__main__':
main()
|
henrytao-me/openerp.positionq | refs/heads/master | openerp/addons/account_asset/report/account_asset_report.py | 54 | # -*- encoding: 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/>.
#
##############################################################################
from openerp import tools
from openerp.osv import fields, osv
class asset_asset_report(osv.osv):
_name = "asset.asset.report"
_description = "Assets Analysis"
_auto = False
_columns = {
'name': fields.char('Year', size=16, required=False, readonly=True),
'purchase_date': fields.date('Purchase Date', readonly=True),
'depreciation_date': fields.date('Depreciation Date', readonly=True),
'asset_id': fields.many2one('account.asset.asset', string='Asset', readonly=True),
'asset_category_id': fields.many2one('account.asset.category',string='Asset category'),
'partner_id': fields.many2one('res.partner', 'Partner', readonly=True),
'state': fields.selection([('draft','Draft'),('open','Running'),('close','Close')], 'Status', readonly=True),
'depreciation_value': fields.float('Amount of Depreciation Lines', readonly=True),
'move_check': fields.boolean('Posted', readonly=True),
'nbr': fields.integer('# of Depreciation Lines', readonly=True),
'gross_value': fields.float('Gross Amount', readonly=True),
'posted_value': fields.float('Posted Amount', readonly=True),
'unposted_value': fields.float('Unposted Amount', readonly=True),
'company_id': fields.many2one('res.company', 'Company', readonly=True),
}
def init(self, cr):
tools.drop_view_if_exists(cr, 'asset_asset_report')
cr.execute("""
create or replace view asset_asset_report as (
select
min(dl.id) as id,
dl.name as name,
dl.depreciation_date as depreciation_date,
a.purchase_date as purchase_date,
(CASE WHEN (select min(d.id) from account_asset_depreciation_line as d
left join account_asset_asset as ac ON (ac.id=d.asset_id)
where a.id=ac.id) = min(dl.id)
THEN a.purchase_value
ELSE 0
END) as gross_value,
dl.amount as depreciation_value,
(CASE WHEN dl.move_check
THEN dl.amount
ELSE 0
END) as posted_value,
(CASE WHEN NOT dl.move_check
THEN dl.amount
ELSE 0
END) as unposted_value,
dl.asset_id as asset_id,
dl.move_check as move_check,
a.category_id as asset_category_id,
a.partner_id as partner_id,
a.state as state,
count(dl.*) as nbr,
a.company_id as company_id
from account_asset_depreciation_line dl
left join account_asset_asset a on (dl.asset_id=a.id)
group by
dl.amount,dl.asset_id,dl.depreciation_date,dl.name,
a.purchase_date, dl.move_check, a.state, a.category_id, a.partner_id, a.company_id,
a.purchase_value, a.id, a.salvage_value
)""")
asset_asset_report()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
JacerOmri/PokemonGo-Bot-Desktop | refs/heads/development | pywin/Lib/encodings/charmap.py | 860 | """ Generic Python Character Mapping Codec.
Use this codec directly rather than through the automatic
conversion mechanisms supplied by unicode() and .encode().
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
encode = codecs.charmap_encode
decode = codecs.charmap_decode
class IncrementalEncoder(codecs.IncrementalEncoder):
def __init__(self, errors='strict', mapping=None):
codecs.IncrementalEncoder.__init__(self, errors)
self.mapping = mapping
def encode(self, input, final=False):
return codecs.charmap_encode(input, self.errors, self.mapping)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def __init__(self, errors='strict', mapping=None):
codecs.IncrementalDecoder.__init__(self, errors)
self.mapping = mapping
def decode(self, input, final=False):
return codecs.charmap_decode(input, self.errors, self.mapping)[0]
class StreamWriter(Codec,codecs.StreamWriter):
def __init__(self,stream,errors='strict',mapping=None):
codecs.StreamWriter.__init__(self,stream,errors)
self.mapping = mapping
def encode(self,input,errors='strict'):
return Codec.encode(input,errors,self.mapping)
class StreamReader(Codec,codecs.StreamReader):
def __init__(self,stream,errors='strict',mapping=None):
codecs.StreamReader.__init__(self,stream,errors)
self.mapping = mapping
def decode(self,input,errors='strict'):
return Codec.decode(input,errors,self.mapping)
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='charmap',
encode=Codec.encode,
decode=Codec.decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamwriter=StreamWriter,
streamreader=StreamReader,
)
|
cslzchen/osf.io | refs/heads/develop | api_tests/wikis/views/test_wiki_content.py | 6 | from nose.tools import * # noqa:
from api.base.settings.defaults import API_BASE
from addons.wiki.models import WikiPage
from tests.base import ApiWikiTestCase
from osf_tests.factories import ProjectFactory, RegistrationFactory
class TestWikiContentView(ApiWikiTestCase):
def _set_up_public_project_with_wiki_page(self):
self.public_project = ProjectFactory(is_public=True, creator=self.user)
self.public_wiki = self._add_project_wiki_page(
self.public_project, self.user)
self.public_url = '/{}wikis/{}/content/'.format(
API_BASE, self.public_wiki._id)
def _set_up_private_project_with_wiki_page(self):
self.private_project = ProjectFactory(creator=self.user)
self.private_wiki = self._add_project_wiki_page(
self.private_project, self.user)
self.private_url = '/{}wikis/{}/content/'.format(
API_BASE, self.private_wiki._id)
def _set_up_public_registration_with_wiki_page(self):
self._set_up_public_project_with_wiki_page()
self.public_registration = RegistrationFactory(
project=self.public_project, user=self.user, is_public=True)
self.public_registration_wiki_id = WikiPage.objects.get_for_node(self.public_registration, 'home')._id
self.public_registration.save()
self.public_registration_url = '/{}wikis/{}/content/'.format(
API_BASE, self.public_registration_wiki_id)
def test_logged_out_user_can_get_public_wiki_content(self):
self._set_up_public_project_with_wiki_page()
res = self.app.get(self.public_url)
assert_equal(res.status_code, 200)
assert_equal(res.content_type, 'text/markdown')
assert_equal(res.body.decode(), self.public_wiki.get_version().content)
def test_logged_in_non_contributor_can_get_public_wiki_content(self):
self._set_up_public_project_with_wiki_page()
res = self.app.get(self.public_url, auth=self.non_contributor.auth)
assert_equal(res.status_code, 200)
assert_equal(res.content_type, 'text/markdown')
assert_equal(res.body.decode(), self.public_wiki.get_version().content)
def test_logged_in_contributor_can_get_public_wiki_content(self):
self._set_up_public_project_with_wiki_page()
res = self.app.get(self.public_url, auth=self.user.auth)
assert_equal(res.status_code, 200)
assert_equal(res.content_type, 'text/markdown')
assert_equal(res.body.decode(), self.public_wiki.get_version().content)
def test_logged_out_user_cannot_get_private_wiki_content(self):
self._set_up_private_project_with_wiki_page()
res = self.app.get(self.private_url, expect_errors=True)
assert_equal(res.status_code, 401)
def test_logged_in_non_contributor_cannot_get_private_wiki_content(self):
self._set_up_private_project_with_wiki_page()
res = self.app.get(
self.private_url,
auth=self.non_contributor.auth,
expect_errors=True)
assert_equal(res.status_code, 403)
def test_logged_in_contributor_can_get_private_wiki_content(self):
self._set_up_private_project_with_wiki_page()
res = self.app.get(self.private_url, auth=self.user.auth)
assert_equal(res.status_code, 200)
assert_equal(res.content_type, 'text/markdown')
assert_equal(res.body.decode(), self.private_wiki.get_version().content)
def test_user_cannot_get_withdrawn_registration_wiki_content(self):
self._set_up_public_registration_with_wiki_page()
withdrawal = self.public_registration.retract_registration(
user=self.user, save=True)
token = list(withdrawal.approval_state.values())[0]['approval_token']
withdrawal.approve_retraction(self.user, token)
withdrawal.save()
res = self.app.get(
self.public_registration_url,
auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 403)
|
disko/modoboa-admin-limits | refs/heads/master | tests.py | 1 | """Tests runner for modoboa_admin."""
import unittest
from modoboa.lib.test_utils import TestRunnerMixin
class TestRunner(TestRunnerMixin, unittest.TestCase):
"""The tests runner."""
extension = "modoboa_admin_limits"
dependencies = [
"modoboa_admin"
]
|
dsajkl/123 | refs/heads/master | common/djangoapps/student/management/commands/transfer_students.py | 2 | """
Transfer Student Management Command
"""
from django.db import transaction
from opaque_keys.edx.keys import CourseKey
from optparse import make_option
from django.contrib.auth.models import User
from student.models import CourseEnrollment
from shoppingcart.models import CertificateItem
from track.management.tracked_command import TrackedCommand
class TransferStudentError(Exception):
"""Generic Error when handling student transfers."""
pass
class Command(TrackedCommand):
"""Management Command for transferring students from one course to new courses."""
help = """
This command takes two course ids as input and transfers
all students enrolled in one course into the other. This will
remove them from the first class and enroll them in the specified
class(es) in the same mode as the first one. eg. honor, verified,
audit.
example:
# Transfer students from the old demoX class to a new one.
manage.py ... transfer_students -f edX/Open_DemoX/edx_demo_course -t edX/Open_DemoX/new_demoX
# Transfer students from old course to new, with original certificate items.
manage.py ... transfer_students -f edX/Open_DemoX/edx_demo_course -t edX/Open_DemoX/new_demoX -c true
# Transfer students from the old demoX class into two new classes.
manage.py ... transfer_students -f edX/Open_DemoX/edx_demo_course
-t edX/Open_DemoX/new_demoX,edX/Open_DemoX/edX_Insider
"""
option_list = TrackedCommand.option_list + (
make_option('-f', '--from',
metavar='SOURCE_COURSE',
dest='source_course',
help='The course to transfer students from.'),
make_option('-t', '--to',
metavar='DEST_COURSE_LIST',
dest='dest_course_list',
help='The new course(es) to enroll the student into.'),
make_option('-c', '--transfer-certificates',
metavar='TRANSFER_CERTIFICATES',
dest='transfer_certificates',
help="If True, try to transfer certificate items to the new course.")
)
@transaction.commit_manually
def handle(self, *args, **options): # pylint: disable=unused-argument
source_key = CourseKey.from_string(options.get('source_course', ''))
dest_keys = []
for course_key in options.get('dest_course_list', '').split(','):
dest_keys.append(CourseKey.from_string(course_key))
if not source_key or not dest_keys:
raise TransferStudentError(u"Must have a source course and destination course specified.")
tc_option = options.get('transfer_certificates', '')
transfer_certificates = ('true' == tc_option.lower()) if tc_option else False
if transfer_certificates and len(dest_keys) != 1:
raise TransferStudentError(u"Cannot transfer certificate items from one course to many.")
source_students = User.objects.filter(
courseenrollment__course_id=source_key
)
for user in source_students:
with transaction.commit_on_success():
print("Moving {}.".format(user.username))
# Find the old enrollment.
enrollment = CourseEnrollment.objects.get(
user=user,
course_id=source_key
)
# Move the Student between the classes.
mode = enrollment.mode
old_is_active = enrollment.is_active
CourseEnrollment.unenroll(user, source_key, emit_unenrollment_event=False)
print(u"Unenrolled {} from {}".format(user.username, unicode(source_key)))
for dest_key in dest_keys:
if CourseEnrollment.is_enrolled(user, dest_key):
# Un Enroll from source course but don't mess
# with the enrollment in the destination course.
msg = u"Skipping {}, already enrolled in destination course {}"
print(msg.format(user.username, unicode(dest_key)))
else:
new_enrollment = CourseEnrollment.enroll(user, dest_key, mode=mode)
# Un-enroll from the new course if the user had un-enrolled
# form the old course.
if not old_is_active:
new_enrollment.update_enrollment(is_active=False, emit_unenrollment_event=False)
if transfer_certificates:
self._transfer_certificate_item(source_key, enrollment, user, dest_keys, new_enrollment)
@staticmethod
def _transfer_certificate_item(source_key, enrollment, user, dest_keys, new_enrollment):
""" Transfer the certificate item from one course to another.
Do not use this generally, since certificate items are directly associated with a particular purchase.
This should only be used when a single course to a new location. This cannot be used when transferring
from one course to many.
Args:
source_key (str): The course key string representation for the original course.
enrollment (CourseEnrollment): The original enrollment to move the certificate item from.
user (User): The user to transfer the item for.
dest_keys (list): A list of course key strings to transfer the item to.
new_enrollment (CourseEnrollment): The new enrollment to associate the certificate item with.
Returns:
None
"""
try:
certificate_item = CertificateItem.objects.get(
course_id=source_key,
course_enrollment=enrollment
)
except CertificateItem.DoesNotExist:
print(u"No certificate for {}".format(user))
return
certificate_item.course_id = dest_keys[0]
certificate_item.course_enrollment = new_enrollment
|
vtss/linux-stable | refs/heads/vtss_3.14 | tools/perf/python/twatch.py | 1565 | #! /usr/bin/python
# -*- python -*-
# -*- coding: utf-8 -*-
# twatch - Experimental use of the perf python interface
# Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com>
#
# This application 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; version 2.
#
# This application 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.
import perf
def main():
cpus = perf.cpu_map()
threads = perf.thread_map()
evsel = perf.evsel(task = 1, comm = 1, mmap = 0,
wakeup_events = 1, watermark = 1,
sample_id_all = 1,
sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU)
evsel.open(cpus = cpus, threads = threads);
evlist = perf.evlist(cpus, threads)
evlist.add(evsel)
evlist.mmap()
while True:
evlist.poll(timeout = -1)
for cpu in cpus:
event = evlist.read_on_cpu(cpu)
if not event:
continue
print "cpu: %2d, pid: %4d, tid: %4d" % (event.sample_cpu,
event.sample_pid,
event.sample_tid),
print event
if __name__ == '__main__':
main()
|
beiko-lab/gengis | refs/heads/master | bin/Lib/site-packages/win32/test/test_win32file.py | 2 | import unittest
from pywin32_testutil import str2bytes, TestSkipped, testmain
import win32api, win32file, win32pipe, pywintypes, winerror, win32event
import win32con, ntsecuritycon
import sys
import os
import tempfile
import threading
import time
import shutil
import socket
import datetime
import random
try:
import win32timezone
except SyntaxError:
# win32timezone uses decorators and isn't compatible with py2.3
assert sys.version_info < (2,4)
try:
set
except NameError:
from sets import Set as set
class TestReadBuffer(unittest.TestCase):
def testLen(self):
buffer = win32file.AllocateReadBuffer(1)
self.failUnlessEqual(len(buffer), 1)
def testSimpleIndex(self):
val = str2bytes('\xFF')
buffer = win32file.AllocateReadBuffer(1)
buffer[0] = val
self.failUnlessEqual(buffer[0], val)
def testSimpleSlice(self):
buffer = win32file.AllocateReadBuffer(2)
val = str2bytes('\0\0')
buffer[:2] = val
self.failUnlessEqual(buffer[0:2], val)
class TestSimpleOps(unittest.TestCase):
def testSimpleFiles(self):
try:
fd, filename = tempfile.mkstemp()
except AttributeError:
self.fail("This test requires Python 2.3 or later")
os.close(fd)
os.unlink(filename)
handle = win32file.CreateFile(filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None)
test_data = str2bytes("Hello\0there")
try:
win32file.WriteFile(handle, test_data)
handle.Close()
# Try and open for read
handle = win32file.CreateFile(filename, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
rc, data = win32file.ReadFile(handle, 1024)
self.assertEquals(data, test_data)
finally:
handle.Close()
try:
os.unlink(filename)
except os.error:
pass
# A simple test using normal read/write operations.
def testMoreFiles(self):
# Create a file in the %TEMP% directory.
testName = os.path.join( win32api.GetTempPath(), "win32filetest.dat" )
desiredAccess = win32file.GENERIC_READ | win32file.GENERIC_WRITE
# Set a flag to delete the file automatically when it is closed.
fileFlags = win32file.FILE_FLAG_DELETE_ON_CLOSE
h = win32file.CreateFile( testName, desiredAccess, win32file.FILE_SHARE_READ, None, win32file.CREATE_ALWAYS, fileFlags, 0)
# Write a known number of bytes to the file.
data = str2bytes("z") * 1025
win32file.WriteFile(h, data)
self.failUnless(win32file.GetFileSize(h) == len(data), "WARNING: Written file does not have the same size as the length of the data in it!")
# Ensure we can read the data back.
win32file.SetFilePointer(h, 0, win32file.FILE_BEGIN)
hr, read_data = win32file.ReadFile(h, len(data)+10) # + 10 to get anything extra
self.failUnless(hr==0, "Readfile returned %d" % hr)
self.failUnless(read_data == data, "Read data is not what we wrote!")
# Now truncate the file at 1/2 its existing size.
newSize = len(data)//2
win32file.SetFilePointer(h, newSize, win32file.FILE_BEGIN)
win32file.SetEndOfFile(h)
self.failUnlessEqual(win32file.GetFileSize(h), newSize)
# GetFileAttributesEx/GetFileAttributesExW tests.
self.failUnlessEqual(win32file.GetFileAttributesEx(testName), win32file.GetFileAttributesExW(testName))
attr, ct, at, wt, size = win32file.GetFileAttributesEx(testName)
self.failUnless(size==newSize,
"Expected GetFileAttributesEx to return the same size as GetFileSize()")
self.failUnless(attr==win32file.GetFileAttributes(testName),
"Expected GetFileAttributesEx to return the same attributes as GetFileAttributes")
h = None # Close the file by removing the last reference to the handle!
self.failUnless(not os.path.isfile(testName), "After closing the file, it still exists!")
def testFilePointer(self):
# via [ 979270 ] SetFilePointer fails with negative offset
# Create a file in the %TEMP% directory.
filename = os.path.join( win32api.GetTempPath(), "win32filetest.dat" )
f = win32file.CreateFile(filename,
win32file.GENERIC_READ|win32file.GENERIC_WRITE,
0,
None,
win32file.CREATE_ALWAYS,
win32file.FILE_ATTRIBUTE_NORMAL,
0)
try:
#Write some data
data = str2bytes('Some data')
(res, written) = win32file.WriteFile(f, data)
self.failIf(res)
self.assertEqual(written, len(data))
#Move at the beginning and read the data
win32file.SetFilePointer(f, 0, win32file.FILE_BEGIN)
(res, s) = win32file.ReadFile(f, len(data))
self.failIf(res)
self.assertEqual(s, data)
#Move at the end and read the data
win32file.SetFilePointer(f, -len(data), win32file.FILE_END)
(res, s) = win32file.ReadFile(f, len(data))
self.failIf(res)
self.failUnlessEqual(s, data)
finally:
f.Close()
os.unlink(filename)
def testFileTimesTimezones(self):
if not issubclass(pywintypes.TimeType, datetime.datetime):
# maybe should report 'skipped', but that's not quite right as
# there is nothing you can do to avoid it being skipped!
return
filename = tempfile.mktemp("-testFileTimes")
now_utc = win32timezone.utcnow()
now_local = now_utc.astimezone(win32timezone.TimeZoneInfo.local())
h = win32file.CreateFile(filename,
win32file.GENERIC_READ|win32file.GENERIC_WRITE,
0, None, win32file.CREATE_ALWAYS, 0, 0)
try:
win32file.SetFileTime(h, now_utc, now_utc, now_utc)
ct, at, wt = win32file.GetFileTime(h)
self.failUnlessEqual(now_local, ct)
self.failUnlessEqual(now_local, at)
self.failUnlessEqual(now_local, wt)
# and the reverse - set local, check against utc
win32file.SetFileTime(h, now_local, now_local, now_local)
ct, at, wt = win32file.GetFileTime(h)
self.failUnlessEqual(now_utc, ct)
self.failUnlessEqual(now_utc, at)
self.failUnlessEqual(now_utc, wt)
finally:
h.close()
os.unlink(filename)
def testFileTimes(self):
if issubclass(pywintypes.TimeType, datetime.datetime):
from win32timezone import TimeZoneInfo
now = datetime.datetime.now(tz=TimeZoneInfo.local())
nowish = now + datetime.timedelta(seconds=1)
later = now + datetime.timedelta(seconds=120)
else:
rc, tzi = win32api.GetTimeZoneInformation()
bias = tzi[0]
if rc==2: # daylight-savings is in effect.
bias += tzi[-1]
bias *= 60 # minutes to seconds...
tick = int(time.time())
now = pywintypes.Time(tick+bias)
nowish = pywintypes.Time(tick+bias+1)
later = pywintypes.Time(tick+bias+120)
filename = tempfile.mktemp("-testFileTimes")
# Windows docs the 'last time' isn't valid until the last write
# handle is closed - so create the file, then re-open it to check.
open(filename,"w").close()
f = win32file.CreateFile(filename, win32file.GENERIC_READ|win32file.GENERIC_WRITE,
0, None,
win32con.OPEN_EXISTING, 0, None)
try:
ct, at, wt = win32file.GetFileTime(f)
self.failUnless(ct >= now, "File was created in the past - now=%s, created=%s" % (now, ct))
self.failUnless( now <= ct <= nowish, (now, ct))
self.failUnless(wt >= now, "File was written-to in the past now=%s, written=%s" % (now,wt))
self.failUnless( now <= wt <= nowish, (now, wt))
# Now set the times.
win32file.SetFileTime(f, later, later, later)
# Get them back.
ct, at, wt = win32file.GetFileTime(f)
# XXX - the builtin PyTime type appears to be out by a dst offset.
# just ignore that type here...
if issubclass(pywintypes.TimeType, datetime.datetime):
self.failUnlessEqual(ct, later)
self.failUnlessEqual(at, later)
self.failUnlessEqual(wt, later)
finally:
f.Close()
os.unlink(filename)
class TestOverlapped(unittest.TestCase):
def testSimpleOverlapped(self):
# Create a file in the %TEMP% directory.
import win32event
testName = os.path.join( win32api.GetTempPath(), "win32filetest.dat" )
desiredAccess = win32file.GENERIC_WRITE
overlapped = pywintypes.OVERLAPPED()
evt = win32event.CreateEvent(None, 0, 0, None)
overlapped.hEvent = evt
# Create the file and write shit-loads of data to it.
h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0)
chunk_data = str2bytes("z") * 0x8000
num_loops = 512
expected_size = num_loops * len(chunk_data)
for i in range(num_loops):
win32file.WriteFile(h, chunk_data, overlapped)
win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE)
overlapped.Offset = overlapped.Offset + len(chunk_data)
h.Close()
# Now read the data back overlapped
overlapped = pywintypes.OVERLAPPED()
evt = win32event.CreateEvent(None, 0, 0, None)
overlapped.hEvent = evt
desiredAccess = win32file.GENERIC_READ
h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.OPEN_EXISTING, 0, 0)
buffer = win32file.AllocateReadBuffer(0xFFFF)
while 1:
try:
hr, data = win32file.ReadFile(h, buffer, overlapped)
win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE)
overlapped.Offset = overlapped.Offset + len(data)
if not data is buffer:
self.fail("Unexpected result from ReadFile - should be the same buffer we passed it")
except win32api.error:
break
h.Close()
def testCompletionPortsMultiple(self):
# Mainly checking that we can "associate" an existing handle. This
# failed in build 203.
ioport = win32file.CreateIoCompletionPort(win32file.INVALID_HANDLE_VALUE,
0, 0, 0)
socks = []
for PORT in range(9123, 9125):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', PORT))
sock.listen(1)
socks.append(sock)
new = win32file.CreateIoCompletionPort(sock.fileno(), ioport, PORT, 0)
assert new is ioport
for s in socks:
s.close()
hv = int(ioport)
ioport = new = None
# The handle itself should be closed now (unless we leak references!)
# Check that.
try:
win32file.CloseHandle(hv)
raise RuntimeError("Expected close to fail!")
except win32file.error, details:
self.failUnlessEqual(details.winerror, winerror.ERROR_INVALID_HANDLE)
def testCompletionPortsQueued(self):
class Foo: pass
io_req_port = win32file.CreateIoCompletionPort(-1, None, 0, 0)
overlapped = pywintypes.OVERLAPPED()
overlapped.object = Foo()
win32file.PostQueuedCompletionStatus(io_req_port, 0, 99, overlapped)
errCode, bytes, key, overlapped = \
win32file.GetQueuedCompletionStatus(io_req_port, win32event.INFINITE)
self.failUnlessEqual(errCode, 0)
self.failUnless(isinstance(overlapped.object, Foo))
def _IOCPServerThread(self, handle, port, drop_overlapped_reference):
overlapped = pywintypes.OVERLAPPED()
win32pipe.ConnectNamedPipe(handle, overlapped)
if drop_overlapped_reference:
# Be naughty - the overlapped object is now dead, but
# GetQueuedCompletionStatus will still find it. Our check of
# reference counting should catch that error.
overlapped = None
# even if we fail, be sure to close the handle; prevents hangs
# on Vista 64...
try:
self.failUnlessRaises(RuntimeError,
win32file.GetQueuedCompletionStatus, port, -1)
finally:
handle.Close()
return
result = win32file.GetQueuedCompletionStatus(port, -1)
ol2 = result[-1]
self.failUnless(ol2 is overlapped)
data = win32file.ReadFile(handle, 512)[1]
win32file.WriteFile(handle, data)
def testCompletionPortsNonQueued(self, test_overlapped_death = 0):
# In 204 we had a reference count bug when OVERLAPPED objects were
# associated with a completion port other than via
# PostQueuedCompletionStatus. This test is based on the reproduction
# reported with that bug.
# Create the pipe.
BUFSIZE = 512
pipe_name = r"\\.\pipe\pywin32_test_pipe"
handle = win32pipe.CreateNamedPipe(pipe_name,
win32pipe.PIPE_ACCESS_DUPLEX|
win32file.FILE_FLAG_OVERLAPPED,
win32pipe.PIPE_TYPE_MESSAGE|
win32pipe.PIPE_READMODE_MESSAGE|
win32pipe.PIPE_WAIT,
1, BUFSIZE, BUFSIZE,
win32pipe.NMPWAIT_WAIT_FOREVER,
None)
# Create an IOCP and associate it with the handle.
port = win32file.CreateIoCompletionPort(-1, 0, 0, 0)
win32file.CreateIoCompletionPort(handle, port, 1, 0)
t = threading.Thread(target=self._IOCPServerThread, args=(handle,port, test_overlapped_death))
t.setDaemon(True) # avoid hanging entire test suite on failure.
t.start()
try:
time.sleep(0.1) # let thread do its thing.
try:
win32pipe.CallNamedPipe(r"\\.\pipe\pywin32_test_pipe", str2bytes("Hello there"), BUFSIZE, 0)
except win32pipe.error:
# Testing for overlapped death causes this
if not test_overlapped_death:
raise
finally:
if not test_overlapped_death:
handle.Close()
t.join(3)
self.failIf(t.isAlive(), "thread didn't finish")
def testCompletionPortsNonQueuedBadReference(self):
self.testCompletionPortsNonQueued(True)
def testHashable(self):
overlapped = pywintypes.OVERLAPPED()
d = {}
d[overlapped] = "hello"
self.failUnlessEqual(d[overlapped], "hello")
def testComparable(self):
overlapped = pywintypes.OVERLAPPED()
self.failUnlessEqual(overlapped, overlapped)
# ensure we explicitly test the operators.
self.failUnless(overlapped == overlapped)
self.failIf(overlapped != overlapped)
def testComparable2(self):
# 2 overlapped objects compare equal if their contents are the same.
overlapped1 = pywintypes.OVERLAPPED()
overlapped2 = pywintypes.OVERLAPPED()
self.failUnlessEqual(overlapped1, overlapped2)
# ensure we explicitly test the operators.
self.failUnless(overlapped1 == overlapped2)
self.failIf(overlapped1 != overlapped2)
# now change something in one of them - should no longer be equal.
overlapped1.hEvent = 1
self.failIfEqual(overlapped1, overlapped2)
# ensure we explicitly test the operators.
self.failIf(overlapped1 == overlapped2)
self.failUnless(overlapped1 != overlapped2)
class TestSocketExtensions(unittest.TestCase):
def acceptWorker(self, port, running_event, stopped_event):
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.bind(('', port))
listener.listen(200)
# create accept socket
accepter = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# An overlapped
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
# accept the connection.
# We used to allow strings etc to be passed here, and they would be
# modified! Obviously this is evil :)
buffer = " " * 1024 # EVIL - SHOULD NOT BE ALLOWED.
self.assertRaises(TypeError, win32file.AcceptEx, listener, accepter, buffer, overlapped)
# This is the correct way to allocate the buffer...
buffer = win32file.AllocateReadBuffer(1024)
rc = win32file.AcceptEx(listener, accepter, buffer, overlapped)
self.failUnlessEqual(rc, winerror.ERROR_IO_PENDING)
# Set the event to say we are all ready
running_event.set()
# and wait for the connection.
rc = win32event.WaitForSingleObject(overlapped.hEvent, 2000)
if rc == win32event.WAIT_TIMEOUT:
self.fail("timed out waiting for a connection")
nbytes = win32file.GetOverlappedResult(listener.fileno(), overlapped, False)
#fam, loc, rem = win32file.GetAcceptExSockaddrs(accepter, buffer)
accepter.send(buffer[:nbytes])
# NOT set in a finally - this means *successfully* stopped!
stopped_event.set()
def testAcceptEx(self):
port = 4680
running = threading.Event()
stopped = threading.Event()
t = threading.Thread(target=self.acceptWorker, args=(port, running,stopped))
t.start()
running.wait(2)
if not running.isSet():
self.fail("AcceptEx Worker thread failed to start")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', port))
win32file.WSASend(s, str2bytes("hello"), None)
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
# Like above - WSARecv used to allow strings as the receive buffer!!
buffer = " " * 10
self.assertRaises(TypeError, win32file.WSARecv, s, buffer, overlapped)
# This one should work :)
buffer = win32file.AllocateReadBuffer(10)
win32file.WSARecv(s, buffer, overlapped)
nbytes = win32file.GetOverlappedResult(s.fileno(), overlapped, True)
got = buffer[:nbytes]
self.failUnlessEqual(got, str2bytes("hello"))
# thread should have stopped
stopped.wait(2)
if not stopped.isSet():
self.fail("AcceptEx Worker thread failed to successfully stop")
class TestFindFiles(unittest.TestCase):
def testIter(self):
dir = os.path.join(os.getcwd(), "*")
files = win32file.FindFilesW(dir)
set1 = set()
set1.update(files)
set2 = set()
for file in win32file.FindFilesIterator(dir):
set2.add(file)
assert len(set2) > 5, "This directory has less than 5 files!?"
self.failUnlessEqual(set1, set2)
def testBadDir(self):
dir = os.path.join(os.getcwd(), "a dir that doesnt exist", "*")
self.assertRaises(win32file.error, win32file.FindFilesIterator, dir)
def testEmptySpec(self):
spec = os.path.join(os.getcwd(), "*.foo_bar")
num = 0
for i in win32file.FindFilesIterator(spec):
num += 1
self.failUnlessEqual(0, num)
def testEmptyDir(self):
test_path = os.path.join(win32api.GetTempPath(), "win32file_test_directory")
try:
# Note: previously used shutil.rmtree, but when looking for
# reference count leaks, that function showed leaks! os.rmdir
# doesn't have that problem.
os.rmdir(test_path)
except os.error:
pass
os.mkdir(test_path)
try:
num = 0
for i in win32file.FindFilesIterator(os.path.join(test_path, "*")):
num += 1
# Expecting "." and ".." only
self.failUnlessEqual(2, num)
finally:
os.rmdir(test_path)
class TestDirectoryChanges(unittest.TestCase):
num_test_dirs = 1
def setUp(self):
self.watcher_threads = []
self.watcher_thread_changes = []
self.dir_names = []
self.dir_handles = []
for i in range(self.num_test_dirs):
td = tempfile.mktemp("-test-directory-changes-%d" % i)
os.mkdir(td)
self.dir_names.append(td)
hdir = win32file.CreateFile(td,
ntsecuritycon.FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ,
None, # security desc
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS |
win32con.FILE_FLAG_OVERLAPPED,
None)
self.dir_handles.append(hdir)
changes = []
t = threading.Thread(target=self._watcherThreadOverlapped,
args=(td, hdir, changes))
t.start()
self.watcher_threads.append(t)
self.watcher_thread_changes.append(changes)
def _watcherThread(self, dn, dh, changes):
# A synchronous version:
# XXX - not used - I was having a whole lot of problems trying to
# get this to work. Specifically:
# * ReadDirectoryChangesW without an OVERLAPPED blocks infinitely.
# * If another thread attempts to close the handle while
# ReadDirectoryChangesW is waiting on it, the ::CloseHandle() method
# blocks (which has nothing to do with the GIL - it is correctly
# managed)
# Which ends up with no way to kill the thread!
flags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME
while 1:
try:
print "waiting", dh
changes = win32file.ReadDirectoryChangesW(dh,
8192,
False, #sub-tree
flags)
print "got", changes
except:
raise
changes.extend(changes)
def _watcherThreadOverlapped(self, dn, dh, changes):
flags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME
buf = win32file.AllocateReadBuffer(8192)
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
while 1:
win32file.ReadDirectoryChangesW(dh,
buf,
False, #sub-tree
flags,
overlapped)
# Wait for our event, or for 5 seconds.
rc = win32event.WaitForSingleObject(overlapped.hEvent, 5000)
if rc == win32event.WAIT_OBJECT_0:
# got some data! Must use GetOverlappedResult to find out
# how much is valid! 0 generally means the handle has
# been closed. Blocking is OK here, as the event has
# already been set.
nbytes = win32file.GetOverlappedResult(dh, overlapped, True)
if nbytes:
bits = win32file.FILE_NOTIFY_INFORMATION(buf, nbytes)
changes.extend(bits)
else:
# This is "normal" exit - our 'tearDown' closes the
# handle.
# print "looks like dir handle was closed!"
return
else:
print "ERROR: Watcher thread timed-out!"
return # kill the thread!
def tearDown(self):
# be careful about raising errors at teardown!
for h in self.dir_handles:
# See comments in _watcherThread above - this appears to
# deadlock if a synchronous ReadDirectoryChangesW is waiting...
# (No such problems with an asynch ReadDirectoryChangesW)
h.Close()
for dn in self.dir_names:
try:
shutil.rmtree(dn)
except OSError:
print "FAILED to remove directory", dn
for t in self.watcher_threads:
# closing dir handle should have killed threads!
t.join(5)
if t.isAlive():
print "FAILED to wait for thread termination"
def stablize(self):
time.sleep(0.5)
def testSimple(self):
self.stablize()
for dn in self.dir_names:
fn = os.path.join(dn, "test_file")
open(fn, "w").close()
self.stablize()
changes = self.watcher_thread_changes[0]
self.failUnlessEqual(changes, [(1, "test_file")])
def testSmall(self):
self.stablize()
for dn in self.dir_names:
fn = os.path.join(dn, "x")
open(fn, "w").close()
self.stablize()
changes = self.watcher_thread_changes[0]
self.failUnlessEqual(changes, [(1, "x")])
class TestEncrypt(unittest.TestCase):
def testEncrypt(self):
fname = tempfile.mktemp("win32file_test")
f = open(fname, "wb")
f.write(str2bytes("hello"))
f.close()
f = None
try:
try:
win32file.EncryptFile(fname)
except win32file.error, details:
if details.winerror != winerror.ERROR_ACCESS_DENIED:
raise
print "It appears this is not NTFS - cant encrypt/decrypt"
win32file.DecryptFile(fname)
finally:
if f is not None:
f.close()
os.unlink(fname)
class TestConnect(unittest.TestCase):
def connect_thread_runner(self, expect_payload, giveup_event):
# As Windows 2000 doesn't do ConnectEx, we need to use a non-blocking
# accept, as our test connection may never come. May as well use
# AcceptEx for this...
listener = socket.socket()
self.addr = ('localhost', random.randint(10000,64000))
listener.bind(self.addr)
listener.listen(1)
# create accept socket
accepter = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# An overlapped
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
# accept the connection.
if expect_payload:
buf_size = 1024
else:
# when we don't expect data we must be careful to only pass the
# exact number of bytes for the endpoint data...
buf_size = win32file.CalculateSocketEndPointSize(listener)
buffer = win32file.AllocateReadBuffer(buf_size)
win32file.AcceptEx(listener, accepter, buffer, overlapped)
# wait for the connection or our test to fail.
events = giveup_event, overlapped.hEvent
rc = win32event.WaitForMultipleObjects(events, False, 2000)
if rc == win32event.WAIT_TIMEOUT:
self.fail("timed out waiting for a connection")
if rc == win32event.WAIT_OBJECT_0:
# Our main thread running the test failed and will never connect.
return
# must be a connection.
nbytes = win32file.GetOverlappedResult(listener.fileno(), overlapped, False)
if expect_payload:
self.request = buffer[:nbytes]
accepter.send(str2bytes('some expected response'))
def test_connect_with_payload(self):
giveup_event = win32event.CreateEvent(None, 0, 0, None)
t = threading.Thread(target=self.connect_thread_runner,
args=(True, giveup_event))
t.start()
time.sleep(0.1)
s2 = socket.socket()
ol = pywintypes.OVERLAPPED()
s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand
try:
win32file.ConnectEx(s2, self.addr, ol, str2bytes("some expected request"))
except win32file.error, exc:
win32event.SetEvent(giveup_event)
if exc.winerror == 10022: # WSAEINVAL
raise TestSkipped("ConnectEx is not available on this platform")
raise # some error error we don't expect.
win32file.GetOverlappedResult(s2.fileno(), ol, 1)
ol = pywintypes.OVERLAPPED()
buff = win32file.AllocateReadBuffer(1024)
win32file.WSARecv(s2, buff, ol, 0)
length = win32file.GetOverlappedResult(s2.fileno(), ol, 1)
self.response = buff[:length]
self.assertEqual(self.response, str2bytes('some expected response'))
self.assertEqual(self.request, str2bytes('some expected request'))
t.join(5)
self.failIf(t.isAlive(), "worker thread didn't terminate")
def test_connect_without_payload(self):
giveup_event = win32event.CreateEvent(None, 0, 0, None)
t = threading.Thread(target=self.connect_thread_runner,
args=(False, giveup_event))
t.start()
time.sleep(0.1)
s2 = socket.socket()
ol = pywintypes.OVERLAPPED()
s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand
try:
win32file.ConnectEx(s2, self.addr, ol)
except win32file.error, exc:
win32event.SetEvent(giveup_event)
if exc.winerror == 10022: # WSAEINVAL
raise TestSkipped("ConnectEx is not available on this platform")
raise # some error error we don't expect.
win32file.GetOverlappedResult(s2.fileno(), ol, 1)
ol = pywintypes.OVERLAPPED()
buff = win32file.AllocateReadBuffer(1024)
win32file.WSARecv(s2, buff, ol, 0)
length = win32file.GetOverlappedResult(s2.fileno(), ol, 1)
self.response = buff[:length]
self.assertEqual(self.response, str2bytes('some expected response'))
t.join(5)
self.failIf(t.isAlive(), "worker thread didn't terminate")
class TestTransmit(unittest.TestCase):
def test_transmit(self):
import binascii
try:
bytes = os.urandom(1024*1024)
except AttributeError:
# must be py2.3...
bytes = ''.join([chr(random.randint(0,255)) for _ in range(5)])
val = binascii.hexlify(bytes)
val_length = len(val)
f = tempfile.TemporaryFile()
f.write(val)
def runner():
s1 = socket.socket()
self.addr = ('localhost', random.randint(10000,64000))
s1.bind(self.addr)
s1.listen(1)
cli, addr = s1.accept()
buf = 1
self.request = []
while buf:
buf = cli.recv(1024*100)
self.request.append(buf)
th = threading.Thread(target=runner)
th.start()
time.sleep(0.5)
s2 = socket.socket()
s2.connect(self.addr)
length = 0
aaa = str2bytes("[AAA]")
bbb = str2bytes("[BBB]")
ccc = str2bytes("[CCC]")
ddd = str2bytes("[DDD]")
empty = str2bytes("")
ol = pywintypes.OVERLAPPED()
f.seek(0)
win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0)
length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
ol = pywintypes.OVERLAPPED()
f.seek(0)
win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, aaa, bbb)
length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
ol = pywintypes.OVERLAPPED()
f.seek(0)
win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, empty, empty)
length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
ol = pywintypes.OVERLAPPED()
f.seek(0)
win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, None, ccc)
length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
ol = pywintypes.OVERLAPPED()
f.seek(0)
win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, ddd)
length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
s2.close()
th.join()
buf = str2bytes('').join(self.request)
self.assertEqual(length, len(buf))
expected = val + aaa + val + bbb + val + val + ccc + ddd + val
self.assertEqual(type(expected), type(buf))
self.assert_(expected == buf)
class TestWSAEnumNetworkEvents(unittest.TestCase):
def test_basics(self):
s = socket.socket()
e = win32event.CreateEvent(None, 1, 0, None)
win32file.WSAEventSelect(s, e, 0)
self.assertEquals(win32file.WSAEnumNetworkEvents(s), {})
self.assertEquals(win32file.WSAEnumNetworkEvents(s, e), {})
self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, s, e, 3)
self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, s, "spam")
self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, "spam", e)
self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, "spam")
f = open("NUL")
h = win32file._get_osfhandle(f.fileno())
self.assertRaises(win32file.error, win32file.WSAEnumNetworkEvents, h)
self.assertRaises(win32file.error, win32file.WSAEnumNetworkEvents, s, h)
try:
win32file.WSAEnumNetworkEvents(h)
except win32file.error, e:
self.assertEquals(e.winerror, win32file.WSAENOTSOCK)
try:
win32file.WSAEnumNetworkEvents(s, h)
except win32file.error, e:
# According to the docs it would seem reasonable that
# this would fail with WSAEINVAL, but it doesn't.
self.assertEquals(e.winerror, win32file.WSAENOTSOCK)
def test_functional(self):
# This is not really a unit test, but it does exercise the code
# quite well and can serve as an example of WSAEventSelect and
# WSAEnumNetworkEvents usage.
port = socket.socket()
port.setblocking(0)
port_event = win32event.CreateEvent(None, 0, 0, None)
win32file.WSAEventSelect(port, port_event,
win32file.FD_ACCEPT |
win32file.FD_CLOSE)
port.bind(("127.0.0.1", 0))
port.listen(10)
client = socket.socket()
client.setblocking(0)
client_event = win32event.CreateEvent(None, 0, 0, None)
win32file.WSAEventSelect(client, client_event,
win32file.FD_CONNECT |
win32file.FD_READ |
win32file.FD_WRITE |
win32file.FD_CLOSE)
err = client.connect_ex(port.getsockname())
self.assertEquals(err, win32file.WSAEWOULDBLOCK)
res = win32event.WaitForSingleObject(port_event, 1000)
self.assertEquals(res, win32event.WAIT_OBJECT_0)
events = win32file.WSAEnumNetworkEvents(port, port_event)
self.assertEquals(events, {win32file.FD_ACCEPT: 0})
server, addr = port.accept()
server.setblocking(0)
server_event = win32event.CreateEvent(None, 1, 0, None)
win32file.WSAEventSelect(server, server_event,
win32file.FD_READ |
win32file.FD_WRITE |
win32file.FD_CLOSE)
res = win32event.WaitForSingleObject(server_event, 1000)
self.assertEquals(res, win32event.WAIT_OBJECT_0)
events = win32file.WSAEnumNetworkEvents(server, server_event)
self.assertEquals(events, {win32file.FD_WRITE: 0})
res = win32event.WaitForSingleObject(client_event, 1000)
self.assertEquals(res, win32event.WAIT_OBJECT_0)
events = win32file.WSAEnumNetworkEvents(client, client_event)
self.assertEquals(events, {win32file.FD_CONNECT: 0,
win32file.FD_WRITE: 0})
sent = 0
data = str2bytes("x") * 16 * 1024
while sent < 16 * 1024 * 1024:
try:
sent += client.send(data)
except socket.error, e:
if e.args[0] == win32file.WSAEINTR:
continue
elif e.args[0] in (win32file.WSAEWOULDBLOCK, win32file.WSAENOBUFS):
break
else:
raise
else:
self.fail("could not find socket buffer limit")
events = win32file.WSAEnumNetworkEvents(client)
self.assertEquals(events, {})
res = win32event.WaitForSingleObject(server_event, 1000)
self.assertEquals(res, win32event.WAIT_OBJECT_0)
events = win32file.WSAEnumNetworkEvents(server, server_event)
self.assertEquals(events, {win32file.FD_READ: 0})
received = 0
while received < sent:
try:
received += len(server.recv(16 * 1024))
except socket.error, e:
if e.args[0] in [win32file.WSAEINTR, win32file.WSAEWOULDBLOCK]:
continue
else:
raise
self.assertEquals(received, sent)
events = win32file.WSAEnumNetworkEvents(server)
self.assertEquals(events, {})
res = win32event.WaitForSingleObject(client_event, 1000)
self.assertEquals(res, win32event.WAIT_OBJECT_0)
events = win32file.WSAEnumNetworkEvents(client, client_event)
self.assertEquals(events, {win32file.FD_WRITE: 0})
client.shutdown(socket.SHUT_WR)
res = win32event.WaitForSingleObject(server_event, 1000)
self.assertEquals(res, win32event.WAIT_OBJECT_0)
# strange timing issues...
for i in range(5):
events = win32file.WSAEnumNetworkEvents(server, server_event)
if events: break
win32api.Sleep(100)
else:
raise AssertionError("failed to get events")
self.assertEquals(events, {win32file.FD_CLOSE: 0})
events = win32file.WSAEnumNetworkEvents(client)
self.assertEquals(events, {})
server.close()
res = win32event.WaitForSingleObject(client_event, 1000)
self.assertEquals(res, win32event.WAIT_OBJECT_0)
events = win32file.WSAEnumNetworkEvents(client, client_event)
self.assertEquals(events, {win32file.FD_CLOSE: 0})
client.close()
events = win32file.WSAEnumNetworkEvents(port)
self.assertEquals(events, {})
if __name__ == '__main__':
testmain()
|
Loisel/colorview2d | refs/heads/master | colorview2d/data.py | 1 | #!/bin/python
"""
A module to handle 3D data with axes.
colorview2d.Data consists of a 2d array and x and y axes.
The class provides methods to rotate, flipp, copy and save
the datafile.
Example
-------
::
file = Data(np.random.random(100, 100))
file.rotate_cw()
file.report()
file.save('newdata.dat')
"""
import copy
import logging
import numpy as np
class Data(object):
"""
``Data`` hosts, well, the data and its axes.
Data is stored in a 2d :class:`numpy-ndarray`.
For the axes, only the bounds are stored. We assume linear scaling of the axes.
If no bounds are specified, we use ``(0, n)`` as boundaries, ``n``
being the number of rows and columns, respectively.
"""
def __init__(self, data, range_bounds=None):
"""Initialize a data object.
Args:
data (numpy.array): the two-dimensional array holding the data.
range_bounds (tuple of tuples): y-range boundaries as a tuple (bottom, top),
x-range boundaries as a tuple (left, right)
"""
self._zdata = data
self._xrange_bounds = None
self._yrange_bounds = None
try:
self.xrange_bounds = range_bounds[1]
self.yrange_bounds = range_bounds[0]
except (AssertionError, IndexError, TypeError):
logging.warn('Ranges not specified correctly. '
'Should be ((y_bottom, y_top), (x_left, x_right)). '
'Using index dimensions as ranges.')
self._xrange_bounds = (0., float(self._zdata.shape[1] - 1))
self._yrange_bounds = (0., float(self._zdata.shape[0] - 1))
@property
def xleft(self):
"""Right boundary value of the x-axis."""
return self._xrange_bounds[0]
@property
def xright(self):
"""Left boundary value of the x-axis."""
return self._xrange_bounds[1]
@property
def xmin(self):
"""Minimum value of the x-axis range."""
return min(self._xrange_bounds)
@property
def xmax(self):
"""Maximum value of the x-axis range."""
return max(self._xrange_bounds)
@property
def dx(self):
"""Spacing of x-axis values."""
return (self._xrange_bounds[1] - self._xrange_bounds[0]) /\
(self._zdata.shape[1] - 1)
@property
def ytop(self):
"""Top boundary value of the y-axis."""
return self._yrange_bounds[1]
@property
def ybottom(self):
"""Bottom boundary value of the y-axis."""
return self._yrange_bounds[0]
@property
def ymin(self):
"""Minimum value of the y-axis range."""
return min(self._yrange_bounds)
@property
def ymax(self):
"""Maximum value of the y-axis range."""
return max(self._yrange_bounds)
@property
def dy(self):
"""Spacing of y-axis values."""
return (self._yrange_bounds[1] - self._yrange_bounds[0]) /\
(self._zdata.shape[0] - 1)
@property
def zdata(self):
"""2d :class:`numpy.ndarray`."""
return self._zdata
@property
def zmin(self):
"""Minimum value of the 2d :class:`numpy.ndarray`."""
return np.amin(self._zdata)
@property
def zmax(self):
"""Maximum value of the 2d :class:`numpy.ndarray`."""
return np.amax(self._zdata)
@property
def xwidth(self):
"""Size of the array along the x-axis."""
return self._zdata.shape[1]
@property
def ywidth(self):
"""Size of the array along the y-axis."""
return self._zdata.shape[0]
@zdata.setter
def zdata(self, data):
"""Set a new 2d :class:`numpy.ndarray`."""
assert isinstance(data, np.ndarray), \
'Not a numpy array. Please provide a numpy array for Data creation.'
assert len(data.shape) == 2, 'Provide a two-dimensional array for Data creation.'
self._zdata = data
@property
def y_range(self):
"""A linear y-range array."""
return np.linspace(
self._yrange_bounds[0], self._yrange_bounds[1], self.zdata.shape[0])
@property
def x_range(self):
"""A linear x-range array."""
return np.linspace(
self._xrange_bounds[0], self._xrange_bounds[1], self.zdata.shape[1])
@property
def xrange_bounds(self):
"""Boundary values on the x-axis as a tuple (left, right)."""
return self._xrange_bounds
@xrange_bounds.setter
def xrange_bounds(self, range_boundaries):
assert len(range_boundaries) == 2, 'Boundaries of x-axis range not specified correctly.'
self._xrange_bounds = (float(range_boundaries[0]), float(range_boundaries[1]))
@property
def yrange_bounds(self):
"""Boundary values on the y-axis as a tuple (bottom, top)."""
return self._yrange_bounds
@yrange_bounds.setter
def yrange_bounds(self, range_boundaries):
assert len(range_boundaries) == 2, 'Boundaries of y-axis range not specified correctly.'
self._yrange_bounds = (float(range_boundaries[0]), float(range_boundaries[1]))
def report(self):
"""
Print a data report to the standart output.
"""
print(
"There are {0} lines and {1} columns in the datafile.\n"
.format(self._zdata.shape[0], self._zdata.shape[1]))
print(
"X-axis range from {0} to {1}".format(self.xleft, self.xright),
"Y-axis range from {0} to {1}".format(self.ybottom, self.ytop))
def deep_copy(self):
"""
Deep copy the :class:`colorview2d.Data` object and return the copy.
Returns:
A copy of the :class:`Colorview2d.Data` instance.
"""
tmp = copy.deepcopy(self)
tmp.zdata = np.copy(self._zdata)
return tmp
def rotate_cw(self):
"""
Rotate the data clockwise. The axes are updated as well.
"""
self.zdata = np.rot90(self._zdata, k=1)
old_xrange_boundaries = self._xrange_bounds
old_yrange_boundaries = self._yrange_bounds
self._xrange_bounds = old_yrange_boundaries
self._yrange_bounds = old_xrange_boundaries[::-1]
def rotate_ccw(self):
"""
Rotate the data counter-clockwise. The axes are updated as well.
"""
self.zdata = np.rot90(self._zdata, k=3)
old_xrange_boundaries = self._xrange_bounds
old_yrange_boundaries = self._yrange_bounds
self._xrange_bounds = old_yrange_boundaries[::-1]
self._yrange_bounds = old_xrange_boundaries
def flip_lr(self):
"""
Flip the left and the right side of the data. The axes are updated as well.
"""
self.zdata = np.fliplr(self._zdata)
self._xrange_bounds = self._xrange_bounds[::-1]
def flip_ud(self):
"""
Flip the up and the down side of the data. The axes are updated as well.
"""
self.zdata = np.flipud(self._zdata)
self._yrange_bounds = self._yrange_bounds[::-1]
def is_within_xbounds(self, val):
"""Check if the given value is within the xrange.
Returns:
a boolean.
"""
return val >= self.xmin or val <= self.xmax
def is_within_ybounds(self, val):
"""Check if the given value is within the yrange.
Returns:
a boolean.
"""
return val >= self.ymin or val <= self.ymax
def is_within_bounds(self, coordinate):
"""Check if the given coordinate (y, x) is within the ranges
of the axes.
Returns:
a boolean.
"""
return self.is_within_xbounds(coordinate[1]) or self.is_within_ybounds(coordinate[0])
def crop(self, boundaries):
"""
Crop the data to a subset of the array specifiying the corners of the subset in
units of the axes ranges.
Args:
boundaries (tuple): (bottom boundary, top boundary,
left boundary, right boundary)
"""
bottom_boundary, top_boundary = (boundaries[0], boundaries[1])
left_boundary, right_boundary = (boundaries[2], boundaries[3])
assert self.is_within_bounds((bottom_boundary, left_boundary)),\
'crop: Bottom left edge not within boundaries.'
assert self.is_within_bounds((top_boundary, right_boundary)),\
'crop: Top right edge not within boundaries.'
xleft_idx = self.x_range_idx_by_val(left_boundary)
xright_idx = self.x_range_idx_by_val(right_boundary)
ybottom_idx = self.y_range_idx_by_val(bottom_boundary)
ytop_idx = self.y_range_idx_by_val(top_boundary)
self._xrange_bounds = (left_boundary, right_boundary)
self._yrange_bounds = (bottom_boundary, top_boundary)
self.zdata = self._zdata[ybottom_idx:ytop_idx + 1, xleft_idx:xright_idx + 1]
def x_range_idx_by_val(self, value):
"""
Return the nearest index of a value within the x axis range.
Args:
value: A value in the range of the x axis
Returns:
The closest index on the x axis range.
"""
assert self.is_within_xbounds(value), 'Value %f out of xrange.' % value
return int(round(abs(self.xleft - value) / self.dx))
def y_range_idx_by_val(self, value):
"""
Return the nearest index of a value within the y axis range.
Args:
value: A value in the range of the y axis
Returns:
The closest index on the y axis range.
"""
assert self.is_within_ybounds(value), 'Value %f out of yrange.' % value
return int(round(abs(self.ybottom - value) / self.dy))
def idx_by_val_coordinate(self, coordinate):
"""Return the nearest index pair for a coordinate pair (y, x) along the
two axes.
Args:
coordinate (tuple): y-axis value, x-axis value (inverse order!)
Returns:
(y-axis index, x-axis index) -- both integer
"""
return (self.y_range_idx_by_val(coordinate[0]), self.x_range_idx_by_val(coordinate[1]))
def extract_ylinetrace(self, xval, ystartval, ystopval):
"""Extract a linetrace along a given y-axis range vor a specific
value on the x axis.
Args:
xval (float): Position of the linecut along the x-axis.
ystartval (float): First and ...
ystopval (float): last value of the range along the y-axis.
Returns:
numpy array with two rows
[0] linecutdata
[1] y-axis range
"""
y_start_idx = self.y_range_idx_by_val(ystartval)
y_stop_idx = self.y_range_idx_by_val(ystopval)
assert y_start_idx != y_stop_idx,\
'Startindex and stopindex %d are equal for ylinetrace.' % y_start_idx
sign = np.sign(y_stop_idx - y_start_idx)
if sign == 1:
return np.vstack(
(self.zdata[y_start_idx:y_stop_idx + 1, self.x_range_idx_by_val(xval)],
self.y_range[y_start_idx:y_stop_idx + 1]))
else:
data = self.zdata[y_stop_idx:y_start_idx + 1, self.x_range_idx_by_val(xval)]
y_range = self.y_range[y_stop_idx:y_start_idx + 1]
return np.vstack((data[::-1], y_range[::-1]))
def extract_xlinetrace(self, yval, xstartval, xstopval):
"""Extract a linetrace along a given y-axis range vor a specific
value on the x axis.
Args:
yval (float): Position of the linecut along the y-axis.
xstartval (float): Start and ...
xstopval (float): stop value of the range along the x-axis.
Returns:
numpy array with two rows
[0] linecutdata
[1] x-axis range
"""
x_start_idx = self.x_range_idx_by_val(xstartval)
x_stop_idx = self.x_range_idx_by_val(xstopval)
assert x_start_idx != x_stop_idx,\
'Startindex and stopindex %d are equal for xlinetrace.' % x_start_idx
sign = np.sign(x_stop_idx - x_start_idx)
if sign == 1:
return np.vstack(
(self.zdata[self.y_range_idx_by_val(yval), x_start_idx:x_stop_idx + 1],
self.x_range[x_start_idx:x_stop_idx + 1]))
else:
data = self.zdata[self.y_range_idx_by_val(yval), x_stop_idx:x_start_idx + 1]
x_range = self.x_range[x_stop_idx:x_start_idx + 1]
return np.vstack((data[::-1], x_range[::-1]))
def extract_ylinetrace_series(self, x_first, x_last, x_interval, ystart, ystop):
"""Extract linetraces along a given y-axis range for
values on the x axis within a given range and separated by
a given interval.
Args:
x_first (float): value on the x-axis for the first line trace in the series.
x_last (float): value on the x-axis for the last line trace in the series.
x_interval (float): the (positive) interval between two linecuts on the x-axis.
ystart (float): Start and ...
ystop (float): stop value of the range along the y-axis.
Returns:
a numpy array with n + 1 rows with the length equal to the y-dimensions of zdata.
n is the number of linecuts, i.e., abs(x_last - x_first) / x_interval.
The last row contains the y-axis range.
"""
result_array = self.extract_ylinetrace(x_first, ystart, ystop)
if self.x_range_idx_by_val(x_first) == self.x_range_idx_by_val(x_last):
return result_array
result_range = result_array[1]
result_array = result_array[0]
x_sign = np.sign(x_last - x_first)
x_pos = x_first + x_interval * x_sign
while x_pos * x_sign <= x_last * x_sign:
result_array = np.vstack((result_array, self.extract_ylinetrace(x_pos, ystart, ystop)[0]))
x_pos += x_interval * x_sign
return np.vstack((result_array, result_range))
def extract_xlinetrace_series(self, y_first, y_last, y_interval, xstart, xstop):
"""Extract linetraces along a given x-axis range for
values on the y axis within a given range and separated by
a given interval.
Args:
y_first (float): value on the y-axis for the first line trace in the series.
y_last (float): value on the y-axis for the last line trace in the series.
y_interval (float): the (positive) interval between two linecuts on the y-axis.
xstart (float): Start and ...
xstop (float): stop value of the range along the x-axis.
Returns:
a numpy array with n + 1 rows with the length equal to the x-dimensions of zdata.
n is the number of linecuts, i.e., abs(y_last - y_first) / y_interval.
The last row contains the x-axis range.
"""
result_array = self.extract_xlinetrace(y_first, xstart, xstop)
if self.y_range_idx_by_val(y_first) == self.y_range_idx_by_val(y_last):
return result_array
y_sign = np.sign(y_last - y_first)
y_pos = y_first + y_interval * y_sign
# For now we remove the range axis
result_range = result_array[1]
result_array = result_array[0]
while y_pos * y_sign <= y_last * y_sign:
# add the next linetrace to the other linetraces
result_array = np.vstack((result_array, self.extract_xlinetrace(y_pos, xstart, xstop)[0]))
y_pos += y_interval * y_sign
return np.vstack((result_array, result_range))
def extract_arbitrary_linetrace(self, coordinate_one, coordinate_two):
"""Extract a linetrace between two arbitrary points.
Args:
coordinate_one (tuple): coordinate in the coordinate system of the axis.
The order is (yval, xval)!
coordinate_two (tuple): coordinates in the coordinate system of the
x and y axes. The order is (yval, xval)!
Returns:
Array with the linetrace. No axis range is supplied since it does not make sense
along any arbitrary direction.
"""
# we transform to the grid
idx_one = self.idx_by_val_coordinate(coordinate_one)
idx_two = self.idx_by_val_coordinate(coordinate_two)
assert idx_one != idx_two, (
'Coordinate one and two are equal: (y=%d, x=%d).' % (idx_one[0], idx_one[1]),\
'Can not extract linetrace of zero length.')
# if one of the two coordinate axis has zero difference,
# we call the orthogonal version
# y axis difference is zero:
if idx_one[0] == idx_two[0]:
return self.extract_xlinetrace(
coordinate_one[0], coordinate_one[1], coordinate_two[1])[0]
# x axis difference is zero:
elif idx_one[1] == idx_two[1]:
return self.extract_ylinetrace(
coordinate_one[1], coordinate_one[0], coordinate_two[0])[0]
# which is the primary axis of the linetrace?
if abs(idx_one[0] - idx_two[0]) > abs(idx_one[1] - idx_two[1]):
primary_axis_index, secondary_axis_index = (0, 1)
else:
primary_axis_index, secondary_axis_index = (1, 0)
linetrace_slope = float(idx_two[secondary_axis_index] - idx_one[secondary_axis_index]) /\
float(idx_two[primary_axis_index] - idx_one[primary_axis_index])
# Note that the linetrace has one more points than its length
linetrace_size = abs(idx_two[primary_axis_index] - idx_one[primary_axis_index]) + 1
axis_sign = np.sign(idx_two[primary_axis_index] - idx_one[primary_axis_index])
# go along primary axis and extract closest point
# if the primary axis is y-axis
if primary_axis_index == 0:
# dy and dx are positive: increment on both axis postive (trivial case)
# dy > 0, dx < 0: increment on first axis positive, slope negative -> increment
# on second axis negative.
# dy < 0, dx > 0: increment on y negative, slope negative -> dx positive
# dy < 0, dx < 0: increment negative, slope positive -> dx negative
linetrace = np.array(
[self.zdata[yidx + idx_one[0], int(round(yidx * linetrace_slope + idx_one[1]))]
for yidx in np.arange(linetrace_size) * axis_sign])
else:
linetrace = np.array(
[self.zdata[int(round(xidx * linetrace_slope + idx_one[0])), xidx + idx_one[1]]
for xidx in np.arange(linetrace_size) * axis_sign])
return linetrace
def resize(self, new_ywidth, new_xwidth, order=1):
"""Interpolate the array to a new, larger size.
Uses scipy.misc.imresize.
The ranges are interpolated accordingly.
Args:
new_ywidth (int): new dimensions along the y-axis.
new_xwidth (int): new dimensions along the x-axis.
order (int): order of the interpolation. See ``scipy.misc.imresize()``
"""
# Check if scipy is available
try:
from scipy.ndimage import zoom
except ImportError:
logging.error(
'Module scipy is not available. scipy.misc.imresize is used for interpolation.')
return
xfactor = float(new_xwidth) / self.xwidth
yfactor = float(new_ywidth) / self.ywidth
self._zdata = zoom(self._zdata, (yfactor, xfactor), order=order)
|
bikash/kaggleCompetition | refs/heads/master | microsoft malware/code/single_20.py | 1 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 01:55:47 2015
@author: marios michailidis
"""
# licence: FreeBSD
"""
Copyright (c) 2015, Marios Michailidis
All rights reserved.
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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import random
import numpy as np
import scipy as spss
from scipy.sparse import csr_matrix
import sys
sys.path.append("../../xgboost/wrapper")
import xgboost as xgb
from sklearn.ensemble import ExtraTreesClassifier
thre=25
num_round=11500
lr=0.005
max_de=7
subsam=0.4
colsample_bytree=0.5
gamma =0.001
min_child_weight=0.05
seed=1
objective='multi:softprob'
param = {}
param['booster']= 'gbtree'#gblinear
param['objective'] = objective
param['bst:eta'] = lr
param['seed']=seed
param['bst:max_depth'] = max_de
param['eval_metric'] = 'auc'
param['bst:min_child_weight']=min_child_weight
param['silent'] = 1
param['nthread'] = thre
param['bst:subsample'] = subsam
param['num_class'] = 9
param['gamma'] = gamma
param['colsample_bytree']=colsample_bytree
def transform2dtos(D2,y2):
# transform a 2d array of predictions to single array
# we also change
d1=[]
y1=[]
for i in range (0,len(D2)):
for j in range (0,len(D2[0])):
d1.append(float(D2[i][j]))
if y2[i]==float(j):
y1.append(1.0)
else:
y1.append(0.0)
return d1,y1
""" print predictions in file"""
def printfilewithtarget(X, name):
print("start print the training file with target")
wfile=open(name + ".csv", "w")
for i in range (0, len(X)):
wfile.write(str(X[i][0]) )
for j in range (1, len(X[i])):
wfile.write("," +str(X[i][j]) )
wfile.write("\n")
wfile.close()
print("done")
""" the metric we are being tested on"""
def logloss_metric(p, y):
logloss=0
for i in range (0, len(p)):
for j in range (0,len(p[i])):
if y[i]==float(j):
logloss+= np.log(spss.maximum(spss.minimum(p[i][j],1-(1e-15) ),1e-15 ))
return -logloss/float(len(y))
"""Load a csv file"""
def load(name):
print("start reading file with target")
wfile=open(name , "r")
line=wfile.readline().replace("\n","")
splits=line.split(",")
datalen=len(splits)
wfile.close()
X = np.loadtxt(open( name), delimiter=',',usecols=range(0, datalen), skiprows=0)
print("done")
return np.array(X)
""" use to concatebate the various kfold sets together"""
def cving(x1, x2, x3, x4,x5, y1 ,y2, y3, y4, y5, ind1, ind2, ind3, ind4 ,ind5, num):
if num==0:
xwhole=np.concatenate((x2,x3,x4,x5), axis=0)
yhol=np.concatenate((y2,y3,y4,y5), axis=0)
return x1,y1 ,ind1,xwhole,yhol
elif num==1:
xwhole=np.concatenate((x1,x3,x4,x5), axis=0)
yhol=np.concatenate((y1,y3,y4,y5), axis=0)
return x2,y2 ,ind2,xwhole,yhol
elif num==2:
xwhole=np.concatenate((x1,x2,x4,x5), axis=0)
yhol=np.concatenate((y1,y2,y4,y5), axis=0)
return x3,y3 ,ind3,xwhole,yhol
elif num==3:
xwhole=np.concatenate((x1,x2,x3,x5), axis=0)
yhol=np.concatenate((y1,y2,y3,y5), axis=0)
return x4,y4 ,ind4,xwhole,yhol
else :
xwhole=np.concatenate((x1,x2,x3,x4), axis=0)
yhol=np.concatenate((y1,y2,y3,y4), axis=0)
return x5,y5 ,ind5,xwhole,yhol
""" Splits data to 5 kfold sets"""
def split_array_in_5(array, seed):
random.seed(seed)
new_arra1=[]
new_arra2=[]
new_arra3=[]
new_arra4=[]
new_arra5=[]
indiceds1=[]
indiceds2=[]
indiceds3=[]
indiceds4=[]
indiceds5=[]
for j in range (0,len(array)):
rand=random.random()
if rand <0.2:
new_arra1.append(array[j])
indiceds1.append(j)
elif rand <0.4:
new_arra2.append(array[j])
indiceds2.append(j)
elif rand <0.6:
new_arra3.append(array[j])
indiceds3.append(j)
elif rand <0.8:
new_arra4.append(array[j])
indiceds4.append(j)
else :
new_arra5.append(array[j])
indiceds5.append(j)
#convert to numpy
new_arra1=np.array(new_arra1)
new_arra2=np.array(new_arra2)
new_arra3=np.array(new_arra3)
new_arra4=np.array(new_arra4)
new_arra5=np.array(new_arra5)
#return arrays and indices
return new_arra1,new_arra2,new_arra3,new_arra4,new_arra5,indiceds1,indiceds2,indiceds3,indiceds4,indiceds5
def scalepreds(prs):
for i in range (0, len(prs)):
suum=0.0
for j in range (0,9):
suum+=prs[i][j]
for j in range (0,9):
prs[i][j]/=suum
"""loads first columns of a file"""
def loadfirstcolumn(filename):
pred=[]
op=open(filename,'r')
op.readline() #header
for line in op:
line=line.replace('\n','')
sp=line.split(',')
#load always the last columns
pred.append(sp[0])
op.close()
return pred
"""loads last columns of a file"""
def loadlastcolumn(filename):
pred=[]
op=open(filename,'r')
op.readline() #header
for line in op:
line=line.replace('\n','')
sp=line.split(',')
#load always the last columns
pred.append(float(sp[len(sp)-1])-1.0)
op.close()
return pred
""" This is the main method"""
def main():
directory=''
train_file="train_20.csv"
test_file="test_20.csv"
SEED= 15
outset="Gert202xtra115k"
y= loadlastcolumn(directory+"trainLabels.csv")
ids=loadfirstcolumn(directory+"sampleSubmission.csv")
model=ExtraTreesClassifier(n_estimators=1000, criterion='entropy', max_depth=16, min_samples_split=2,min_samples_leaf=1, max_features=0.5,n_jobs=25, random_state=1)
X=load(train_file)
print ("train samples: %d columns: %d " % (len(X) , len(X[0])))
X_test=load(test_file)
print ("train samples: %d columns: %d" % (len(X_test) , len(X_test[0])))
number_of_folds=5 # repeat the CV procedure 10 times to get more precise results
train_stacker=[ [0.0 for d in range (0,9)] for k in range (0,len(X)) ]
test_stacker=[[0.0 for d in range (0,9)] for k in range (0,len(X_test))]
#label_stacker=[0 for k in range (0,len(X))]
#split trainingg
x1,x2,x3,x4,x5,in1,in2,in3,in4,in5=split_array_in_5(X, SEED)
y1,y2,y3,y4,y5,iny1,iny2,iny3,iny4,iny5=split_array_in_5(y, SEED)
#create target variable
mean_log = 0.0
for i in range(0,number_of_folds):
X_cv,y_cv,indcv,X_train,y_train=cving(x1, x2, x3, x4,x5, y1 ,y2, y3, y4, y5,in1, in2, in3, in4 ,in5, i)
print (" train size: %d. test size: %d, cols: %d " % (len(X_train) ,len(X_cv) ,len(X_train[0]) ))
""" model XGBOOST classifier"""
xgmat = xgb.DMatrix( csr_matrix(X_train), label=y_train, missing =-999.0 )
bst = xgb.train( param.items(), xgmat, num_round );
xgmat_cv = xgb.DMatrix( csr_matrix(X_cv), missing =-999.0)
preds =bst.predict( xgmat_cv ).reshape( len(X_cv), 9).tolist()
scalepreds(preds)
"""now model scikit classifier"""
model.fit(X_train, y_train)
predsextra = model.predict_proba(X_cv)
scalepreds(predsextra)
for pr in range (0,len(preds)):
for d in range (0,9):
preds[pr][d]=preds[pr][d]*0.8 + predsextra[pr][d]*0.2
# compute Loglikelihood metric for this CV fold
loglike = logloss_metric( preds,y_cv)
print "size train: %d size cv: %d Loglikelihood (fold %d/%d): %f" % (len(X_train), len(X_cv), i + 1, number_of_folds, loglike)
mean_log += loglike
#save the results
no=0
for real_index in indcv:
for d in range (0,9):
train_stacker[real_index][d]=(preds[no][d])
no+=1
if (number_of_folds)>0:
mean_log/=number_of_folds
print (" Average M loglikelihood: %f" % (mean_log) )
xgmat = xgb.DMatrix( csr_matrix(X), label=y, missing =-999.0 )
bst = xgb.train( param.items(), xgmat, num_round );
xgmat_cv = xgb.DMatrix(csr_matrix(X_test), missing =-999.0)
preds =bst.predict( xgmat_cv ).reshape( len(X_test), 9 ).tolist()
scalepreds(preds)
#predicting for test
model.fit(X, y)
predsextra = model.predict_proba(X_test)
scalepreds(predsextra)
for pr in range (0,len(preds)):
for d in range (0,9):
test_stacker[pr][d]=preds[pr][d]*0.8 + predsextra[pr][d]*0.2
# === Predictions === #
print (" printing datasets ")
printfilewithtarget(train_stacker, outset + "train")
printfilewithtarget(test_stacker, outset + "test")
print("Write results...")
output_file = "submission_"+str( (mean_log ))+".csv"
print("Writing submission to %s" % output_file)
f = open(output_file, "w")
f.write("Id")# the header
for b in range (1,10):
f.write("," + str("Prediction" + str(b) ) )
f.write("\n")
for g in range(0, len(test_stacker)) :
f.write("%s" % ((ids[g])))
for prediction in test_stacker[g]:
f.write(",%f" % (prediction))
f.write("\n")
f.close()
print("Done.")
if __name__=="__main__":
main() |
shirishgoyal/crowdsource-platform | refs/heads/develop2 | mturk/migrations/0002_auto_20160629_1710.py | 1 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-06-29 17:10
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('mturk', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='MTurkHITType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('string_id', models.CharField(max_length=64, null=True)),
('name', models.CharField(max_length=128)),
('description', models.CharField(blank=True, max_length=512, null=True)),
('price', models.DecimalField(decimal_places=2, max_digits=8)),
('keywords', models.CharField(blank=True, max_length=128, null=True)),
('duration', models.DurationField(null=True)),
('boomerang_threshold', models.IntegerField(default=300, null=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Qualification',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=64)),
('description', models.CharField(max_length=512)),
('status', models.CharField(default='Active', max_length=16)),
('auto_granted', models.BooleanField(default=False)),
('keywords', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=128), default=[], null=True, size=None)),
('auto_granted_value', models.IntegerField(default=199, null=True)),
('type_id', models.CharField(max_length=128)),
('flag', models.IntegerField()),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='mturk_qualifications', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.RenameField(
model_name='mturkaccount',
old_name='created_timestamp',
new_name='created_at',
),
migrations.RenameField(
model_name='mturkaccount',
old_name='last_updated',
new_name='updated_at',
),
migrations.RenameField(
model_name='mturkassignment',
old_name='created_timestamp',
new_name='created_at',
),
migrations.RenameField(
model_name='mturkassignment',
old_name='last_updated',
new_name='updated_at',
),
migrations.RenameField(
model_name='mturkhit',
old_name='created_timestamp',
new_name='created_at',
),
migrations.RenameField(
model_name='mturkhit',
old_name='last_updated',
new_name='updated_at',
),
migrations.RenameField(
model_name='mturknotification',
old_name='created_timestamp',
new_name='created_at',
),
migrations.RenameField(
model_name='mturknotification',
old_name='last_updated',
new_name='updated_at',
),
]
|
shreyasp/erpnext | refs/heads/develop | erpnext/accounts/doctype/sales_invoice_timesheet/__init__.py | 12133432 | |
smharper/openmc | refs/heads/develop | tests/regression_tests/tallies/__init__.py | 12133432 | |
dawran6/zulip | refs/heads/master | zerver/views/__init__.py | 12133432 | |
PcBoy111/PCBOT | refs/heads/master | plugins/moderate.py | 1 | """ Plugin for server moderation
The bot will perform different tasks when some settings are enabled in a server:
_____________________________________NSFW Filter_____________________________________
If enabled on the server, spots any text containing the keyword nsfw and a link.
Then tries to delete their message, and post a link to the dedicated nsfw channel.
Commands:
moderate
mute
unmute
timeout
suspend
"""
from collections import defaultdict
import discord
import asyncio
from pcbot import Config, utils, Annotate
import plugins
client = plugins.client # type: discord.Client
moderate = Config("moderate", data=defaultdict(dict))
default_config = {} # Used by add_setting helper function
def setup_default_config(server: discord.Server):
""" Setup default settings for a server. """
# Set to defaults if there is no config for the server
if server.id not in moderate.data:
moderate.data[server.id] = default_config
moderate.save()
return
# Set to defaults if server's config is missing values
if not all(k in moderate.data[server.id].keys() for k in default_config):
moderate.data[server.id] = default_config
moderate.save()
@plugins.command(name="moderate", permissions="manage_messages")
async def moderate_(message, _: utils.placeholder):
""" Change moderation settings. """
pass
def add_setting(setting: str, default=True, name=None, permissions=None):
""" Create a set of subcommands for the given setting (True or False).
:param setting: display name for the setting.
:param default: The default value for this setting.
:param name: optionally set the name of the subcommand.
:param permissions: what permissions are required to change this setting (list of str). """
if not name:
name = setting.lower().replace("\n", "").replace(" ", "")
default_config[name] = default
@moderate_.command(name=name, usage="[on | off]", permissions=permissions,
description="Display current {} setting or enable/disable it.".format(setting))
async def display_setting(message: discord.Message):
""" The command to display the current setting. """
setup_default_config(message.server)
current = moderate.data[message.server.id][name]
await client.say(message, "{} is **{}**.".format(setting, "enabled" if current else "disabled"))
@display_setting.command(hidden=True, aliases="true set enable", permissions=permissions)
async def on(message: discord.Message):
""" The command to enable this setting. """
moderate.data[message.server.id][name] = True
moderate.save()
await client.say(message, "{} **enabled**.".format(setting))
@display_setting.command(hidden=True, aliases="false unset disable", permissions=permissions)
async def off(message: discord.Message):
""" The command to enable this setting. """
moderate.data[message.server.id][name] = False
moderate.save()
await client.say(message, "{} **disabled**.".format(setting))
add_setting("NSFW filter", permissions=["manage_server"])
add_setting("Changelog", permissions=["manage_server"], default=False)
async def manage_mute(message: discord.Message, function, *members: discord.Member):
""" Add or remove Muted role for given members.
:param function: either client.add_roles or client.remove_roles
:return: list of muted/unmuted members or None """
# Manage Roles is required to add or remove the Muted role
assert message.server.me.permissions_in(message.channel).manage_roles, \
"I need `Manage Roles` permission to use this command."
muted_role = discord.utils.get(message.server.roles, name="Muted")
# The server needs to properly manage the Muted role
assert muted_role, "No role assigned for muting. Please create a `Muted` role."
muted_members = []
# Try giving members the Muted role
for member in members:
if member is message.server.me:
await client.say(message, "I refuse to mute myself!")
continue
while True:
try:
await function(member, muted_role)
except discord.errors.Forbidden:
await client.say(message, "I do not have permission to give members the `Muted` role.")
return None
except discord.errors.HTTPException:
continue
else:
muted_members.append(member)
break
return muted_members or None
@plugins.command(pos_check=True, permissions="manage_messages")
async def mute(message: discord.Message, *members: discord.Member):
""" Mute the specified members. """
muted_members = await manage_mute(message, client.add_roles, *members)
# Some members were muted, success!
if muted_members:
await client.say(message, "Muted {}".format(utils.format_objects(*muted_members, dec="`")))
@plugins.command(pos_check=True, permissions="manage_messages")
async def unmute(message: discord.Message, *members: discord.Member):
""" Unmute the specified members. """
muted_members = await manage_mute(message, client.remove_roles, *members)
# Some members were unmuted, success!
if muted_members:
await client.say(message, "Unmuted {}".format(utils.format_objects(*muted_members, dec="`")))
@plugins.command(permissions="manage_messages")
async def timeout(message: discord.Message, member: discord.Member, minutes: float, reason: Annotate.Content):
""" Timeout a user in minutes (will accept decimal numbers), send them
the reason for being timed out and post the reason in the server's
changelog if it has one. """
client.loop.create_task(client.delete_message(message))
muted_members = await manage_mute(message, client.add_roles, member)
# Do not progress if the members were not successfully muted
# At this point, manage_mute will have reported any errors
if not muted_members:
return
changelog_channel = get_changelog_channel(message.server)
# Tell the member and post in the changelog
m = "You were timed out from **{}** for **{} minutes**. \n**Reason:** {}".format(message.server, minutes, reason)
await client.send_message(member, m)
if changelog_channel:
await client.send_message(changelog_channel, "{} Timed out {} for **{} minutes**. **Reason:** {}".format(
message.author.mention, member.mention, minutes, reason
))
# Sleep for the given hours and unmute the member
await asyncio.sleep(minutes * 60) # Since asyncio.sleep takes seconds, multiply by 60^2
await manage_mute(message, client.remove_roles, *muted_members)
@plugins.command(aliases="muteall mute* unmuteall unmute*", permissions="manage_messages")
async def suspend(message: discord.Message, channel: discord.Channel=Annotate.Self):
""" Suspends a channel by removing send permission for the server's default role.
This function acts like a toggle. """
send = channel.overwrites_for(message.server.default_role).send_messages
print(send, False if send is None else not send)
overwrite = discord.PermissionOverwrite(send_messages=False if send is None else not send)
await client.edit_channel_permissions(channel, message.server.default_role, overwrite)
try:
if overwrite.send_messages:
await client.say(message, "{} is no longer suspended.".format(channel.mention))
else:
await client.say(message, "Suspended {}.".format(channel.mention))
except discord.Forbidden: # ...
await client.send_message(message.author, "You just removed my send permission in {}.".format(channel.mention))
@plugins.argument("{open}member/#channel {suffix}{close}", pass_message=True)
def members_and_channels(message: discord.Message, arg: str):
""" Look for both members and channel mentions. """
if utils.channel_mention_pattern.match(arg):
return utils.find_channel(message.server, arg)
return utils.find_member(message.server, arg)
@plugins.command(permissions="manage_messages")
async def purge(message: discord.Message, *instances: members_and_channels, num: utils.int_range(1, 100)):
""" Purge the given amount of messages from the specified members or all.
You may also specify a channel to delete from.
`num` is a number from 1 to 100. """
instances = list(instances)
channel = message.channel
for instance in instances:
if type(instance) is discord.Channel:
channel = instance
instances.remove(instance)
break
assert not any(i for i in instances if type(i) is discord.Channel), "**I can only purge in one channel.**"
to_delete = []
async for m in client.logs_from(channel, limit=100, before=message):
if len(to_delete) >= num:
break
if not instances or m.author in instances:
to_delete.append(m)
deleted = len(to_delete)
if deleted > 1:
await client.delete_messages(to_delete)
elif deleted == 1:
await client.delete_message(to_delete[0])
m = await client.say(message, "Purged **{}** message{}.".format(deleted, "" if deleted == 1 else "s"))
# Remove both the command message and the feedback after 5 seconds
await asyncio.sleep(5)
await client.delete_messages([m, message])
async def check_nsfw(message: discord.Message):
""" Check if the message is NSFW (very rough check). """
# Check if this server has nsfwfilter enabled
if not moderate.data[message.server.id]["nsfwfilter"]:
return False
# Do not check if the channel is designed for nsfw content
if "nsfw" in message.channel.name:
return False
# Check if message includes keyword nsfw and a link
msg = message.content.lower()
if "nsfw" in msg and ("http://" in msg or "https://" in msg):
if message.server.me.permissions_in(message.channel).manage_messages:
await client.delete_message(message)
nsfw_channel = discord.utils.find(lambda c: "nsfw" in c.name, message.server.channels)
if nsfw_channel:
await client.say(message, "{0.mention}: **Please post NSFW content in {1.mention}**".format(
message.author, nsfw_channel))
return True
@plugins.event()
async def on_message(message: discord.Message):
""" Check plugin settings. """
# Do not check in private messages
if message.channel.is_private:
return False
setup_default_config(message.server)
nsfw_success = await check_nsfw(message)
if nsfw_success is True:
return True
def get_changelog_channel(server: discord.Server):
""" Return the changelog channel for a server. """
setup_default_config(server)
if not moderate.data[server.id]["changelog"]:
return
channel = discord.utils.get(server.channels, name="changelog")
if not channel:
return
permissions = channel.permissions_for(server.me)
if not permissions.send_messages or not permissions.read_messages:
return
return channel
@plugins.event()
async def on_message_delete(message: discord.Message):
""" Update the changelog with deleted messages. """
changelog_channel = get_changelog_channel(message.server)
# Don't log any message the bot deleted
for m in client.last_deleted_messages:
if m.id == message.id:
return
if not changelog_channel:
return
if message.channel == changelog_channel:
return
if message.author == client.user:
return
await client.send_message(
changelog_channel,
"{0.author.mention}'s message was deleted in {0.channel.mention}:\n{0.clean_content}".format(message)
)
@plugins.event()
async def on_channel_create(channel: discord.Channel):
""" Update the changelog with created channels. """
if channel.is_private:
return
changelog_channel = get_changelog_channel(channel.server)
if not changelog_channel:
return
# Differ between voice channels and text channels
if channel.type == discord.ChannelType.text:
await client.send_message(changelog_channel, "Channel {0.mention} was created.".format(channel))
else:
await client.send_message(changelog_channel, "Voice channel **{0.name}** was created.".format(channel))
@plugins.event()
async def on_channel_delete(channel: discord.Channel):
""" Update the changelog with deleted channels. """
if channel.is_private:
return
changelog_channel = get_changelog_channel(channel.server)
if not changelog_channel:
return
# Differ between voice channels and text channels
if channel.type == discord.ChannelType.text:
await client.send_message(changelog_channel, "Channel **#{0.name}** was deleted.".format(channel))
else:
await client.send_message(changelog_channel, "Voice channel **{0.name}** was deleted.".format(channel))
@plugins.event()
async def on_channel_update(before: discord.Channel, after: discord.Channel):
""" Update the changelog when a channel changes name. """
if after.is_private:
return
changelog_channel = get_changelog_channel(after.server)
if not changelog_channel:
return
# We only want to update when a name change is performed
if before.name == after.name:
return
# Differ between voice channels and text channels
if after.type == discord.ChannelType.text:
await client.send_message(
changelog_channel, "Channel **#{0.name}** changed name to {1.mention}, **{1.name}**.".format(before, after))
else:
await client.send_message(
changelog_channel, "Voice channel **{0.name}** changed name to **{1.name}**.".format(before, after))
@plugins.event()
async def on_member_join(member: discord.Member):
""" Update the changelog with members joined. """
changelog_channel = get_changelog_channel(member.server)
if not changelog_channel:
return
await client.send_message(changelog_channel, "{0.mention} joined the server.".format(member))
@plugins.event()
async def on_member_remove(member: discord.Member):
""" Update the changelog with deleted channels. """
changelog_channel = get_changelog_channel(member.server)
if not changelog_channel:
return
await client.send_message(changelog_channel, "{0.mention} ({0.name}) left the server.".format(member))
@plugins.event()
async def on_member_update(before: discord.Member, after: discord.Member):
""" Update the changelog with any changed names and roles. """
name_change = not before.name == after.name
nick_change = not before.nick == after.nick
role_change = not before.roles == after.roles
changelog_channel = get_changelog_channel(after.server)
if not changelog_channel:
return
# Format the nickname or username changed
if name_change:
m = "{0.mention} (previously **{0.name}**) changed their username to **{1.name}**."
elif nick_change:
if not before.nick:
m = "{0.mention} got the nickname **{1.nick}**."
elif not after.nick:
m = "{0.mention} (previously **{0.nick}**) no longer has a nickname."
else:
m = "{0.mention} (previously **{0.nick}**) got the nickname **{1.nick}**."
elif role_change:
muted_role = discord.utils.get(after.server.roles, name="Muted")
if len(before.roles) > len(after.roles):
role = [r for r in before.roles if r not in after.roles][0]
if role == muted_role:
return
m = "{0.mention} lost the role **{1.name}**".format(after, role)
else:
role = [r for r in after.roles if r not in before.roles][0]
if role == muted_role:
return
m = "{0.mention} received the role **{1.name}**".format(after, role)
else:
return
if name_change or nick_change:
await client.send_message(changelog_channel, m.format(before, after))
else:
await client.send_message(changelog_channel, m)
@plugins.event()
async def on_member_ban(member: discord.Member):
""" Update the changelog with banned members. """
changelog_channel = get_changelog_channel(member.server)
if not changelog_channel:
return
await client.send_message(changelog_channel,
"{0.mention} ({0.name}) was banned from the server.".format(member))
@plugins.event()
async def on_member_unban(server: discord.Server, user: discord.Member):
""" Update the changelog with unbanned members. """
changelog_channel = get_changelog_channel(server)
if not changelog_channel:
return
await client.send_message(changelog_channel, "{0.mention} was unbanned from the server.".format(user))
|
makson96/free-engineer | refs/heads/master | tools/status.py | 2 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
##This software is available to you under the terms of the GPL-3, see "/usr/share/common-licenses/GPL-3".
##Copyright:
##- Tomasz Makarewicz (makson96@gmail.com)
import os
recultis_dir = os.getenv("HOME") + "/.recultis/"
def check(game, shop, engine_size, runtime_size):
#Setting initial variables
status = "Waiting for user action"
percent = 0
percent0 = 0
percent1 = 0
percent2 = 0
if shop == "none":
weight = [0.5, 0, 0.5]
percent1 = 100
elif shop == "steam":
weight = [0.1, 0.8, 0.1]
from tools import steam as shop_platform
elif shop == "gog":
weight = [0.1, 0.8, 0.1]
from tools import gog as shop_platform
#Checking runtime
status, percent0 = runtime_status(runtime_size)
#Checking shop
if percent0 == 100 and percent1 != 100:
status, percent1 = shop_platform.status()
#Checking game engine
if percent1 == 100:
status, percent2 = engine_status(game, engine_size)
#Final calculation
percent = int(percent0*weight[0]+percent1*weight[1]+percent2*weight[2])
return status, percent
def runtime_status(url_s):
file_path = recultis_dir + "/tmp/recultis-runtime.deb"
status = "Downloading runtime"
percent = 0
disk_s = 0
if os.path.isfile(file_path) == True:
f = open(file_path, "rb")
disk_s = int(len(f.read()))
f.close()
percent = int(100 * disk_s / url_s)
status = "Downloading runtime"
else:
percent = 100
if percent == 100:
status = "Runtime installation completed"
return status, percent
def engine_status(game, url_s):
#First check if there is error regarding engine download
if os.path.isfile(recultis_dir + "error.txt") == True:
error_file = open(recultis_dir + "error.txt", "r")
error_message = error_file.read()
error_file.close()
os.remove(recultis_dir + "error.txt")
return error_message, 0
#Now check engine download status
from games import installer
file_path = installer.game_info(game, ["deb_file_path"])[0]
status = "Downloading engine"
percent = 0
disk_s = 0
if os.path.isfile(file_path) == True:
f = open(file_path, "rb")
disk_s = int(len(f.read()))
f.close()
percent = 95 * disk_s / url_s
status = "Downloading engine"
elif os.path.isdir(recultis_dir + "tmp") == True:
status = "Installing engine"
percent = 96
else:
status = "Game installation completed"
percent = 100
return status, percent
|
aam-at/tensorflow | refs/heads/master | tensorflow/python/estimator/canned/boosted_trees_utils.py | 40 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""boosted_trees_utils python module.
Importing from tensorflow.python.estimator is unsupported
and will soon break!
"""
# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_estimator.python.estimator.canned import boosted_trees_utils
# Include attrs that start with single underscore.
_HAS_DYNAMIC_ATTRIBUTES = True
boosted_trees_utils.__all__ = [
s for s in dir(boosted_trees_utils) if not s.startswith('__')
]
from tensorflow_estimator.python.estimator.canned.boosted_trees_utils import *
|
mjs/pyweek11-cube | refs/heads/master | run.py | 2 | #! /usr/bin/env python
import sys
from os.path import join
sys.path.append(join('source', 'lib'))
from source.main import main
main()
|
hodgestar/genshi | refs/heads/master | examples/basic/kidrun.py | 13 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import time
import kid
def test():
base_path = os.path.dirname(os.path.abspath(__file__))
kid.path = kid.TemplatePath([base_path])
ctxt = dict(hello='<world>', hey='ZYX', bozz=None,
items=['Number %d' % num for num in range(1, 15)],
prefix='#')
start = time.clock()
template = kid.Template(file='test.kid', **ctxt)
print ' --> parse stage: %.4f ms' % ((time.clock() - start) * 1000)
for output in template.generate():
sys.stdout.write(output)
print
times = []
for i in range(1000):
start = time.clock()
list(template.generate())
times.append(time.clock() - start)
sys.stdout.write('.')
sys.stdout.flush()
print
print ' --> render stage: %s ms (average)' % (
(sum(times) / len(times) * 1000))
if __name__ == '__main__':
if '-p' in sys.argv:
import hotshot, hotshot.stats
prof = hotshot.Profile("template.prof")
benchtime = prof.runcall(test)
stats = hotshot.stats.load("template.prof")
stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats()
else:
test()
|
ZHAW-INES/rioxo-uClinux-dist | refs/heads/rtsp | user/python/python-2.4.4/Lib/plat-irix6/FILE.py | 8 | # Generated by h2py from /usr/include/sys/file.h
# Included from standards.h
# Included from sys/types.h
# Included from sgidefs.h
_MIPS_ISA_MIPS1 = 1
_MIPS_ISA_MIPS2 = 2
_MIPS_ISA_MIPS3 = 3
_MIPS_ISA_MIPS4 = 4
_MIPS_SIM_ABI32 = 1
_MIPS_SIM_NABI32 = 2
_MIPS_SIM_ABI64 = 3
# Included from sys/pthread.h
P_MYID = (-1)
P_MYHOSTID = (-1)
# Included from sys/bsd_types.h
# Included from sys/mkdev.h
ONBITSMAJOR = 7
ONBITSMINOR = 8
OMAXMAJ = 0x7f
OMAXMIN = 0xff
NBITSMAJOR = 14
NBITSMINOR = 18
MAXMAJ = 0x1ff
MAXMIN = 0x3ffff
OLDDEV = 0
NEWDEV = 1
MKDEV_VER = NEWDEV
def IS_STRING_SPEC_DEV(x): return ((dev_t)(x)==__makedev(MKDEV_VER, 0, 0))
def major(dev): return __major(MKDEV_VER, dev)
def minor(dev): return __minor(MKDEV_VER, dev)
# Included from sys/select.h
FD_SETSIZE = 1024
__NBBY = 8
# Included from string.h
NULL = 0L
NBBY = 8
# Included from sys/cpumask.h
MAXCPU = 128
def CPUMASK_INDEX(bit): return ((bit) >> 6)
def CPUMASK_SHFT(bit): return ((bit) & 0x3f)
def CPUMASK_IS_ZERO(p): return ((p) == 0)
def CPUMASK_IS_NONZERO(p): return ((p) != 0)
# Included from sys/nodemask.h
def CNODEMASK_IS_ZERO(p): return ((p) == 0)
def CNODEMASK_IS_NONZERO(p): return ((p) != 0)
# Included from sys/sema.h
# Included from sys/timespec.h
# Included from sys/param.h
# Included from sys/signal.h
SIGHUP = 1
SIGINT = 2
SIGQUIT = 3
SIGILL = 4
SIGTRAP = 5
SIGIOT = 6
SIGABRT = 6
SIGEMT = 7
SIGFPE = 8
SIGKILL = 9
SIGBUS = 10
SIGSEGV = 11
SIGSYS = 12
SIGPIPE = 13
SIGALRM = 14
SIGTERM = 15
SIGUSR1 = 16
SIGUSR2 = 17
SIGCLD = 18
SIGCHLD = 18
SIGPWR = 19
SIGWINCH = 20
SIGURG = 21
SIGPOLL = 22
SIGIO = 22
SIGSTOP = 23
SIGTSTP = 24
SIGCONT = 25
SIGTTIN = 26
SIGTTOU = 27
SIGVTALRM = 28
SIGPROF = 29
SIGXCPU = 30
SIGXFSZ = 31
SIGK32 = 32
SIGCKPT = 33
SIGRESTART = 34
SIGUME = 35
SIGPTINTR = 47
SIGPTRESCHED = 48
SIGRTMIN = 49
SIGRTMAX = 64
__sigargs = int
# Included from sys/sigevent.h
SIGEV_NONE = 128
SIGEV_SIGNAL = 129
SIGEV_CALLBACK = 130
SIGEV_THREAD = 131
# Included from sys/siginfo.h
SI_MAXSZ = 128
SI_USER = 0
SI_KILL = SI_USER
SI_QUEUE = -1
SI_ASYNCIO = -2
SI_TIMER = -3
SI_MESGQ = -4
ILL_ILLOPC = 1
ILL_ILLOPN = 2
ILL_ILLADR = 3
ILL_ILLTRP = 4
ILL_PRVOPC = 5
ILL_PRVREG = 6
ILL_COPROC = 7
ILL_BADSTK = 8
NSIGILL = 8
FPE_INTDIV = 1
FPE_INTOVF = 2
FPE_FLTDIV = 3
FPE_FLTOVF = 4
FPE_FLTUND = 5
FPE_FLTRES = 6
FPE_FLTINV = 7
FPE_FLTSUB = 8
NSIGFPE = 8
SEGV_MAPERR = 1
SEGV_ACCERR = 2
NSIGSEGV = 2
BUS_ADRALN = 1
BUS_ADRERR = 2
BUS_OBJERR = 3
NSIGBUS = 3
TRAP_BRKPT = 1
TRAP_TRACE = 2
NSIGTRAP = 2
CLD_EXITED = 1
CLD_KILLED = 2
CLD_DUMPED = 3
CLD_TRAPPED = 4
CLD_STOPPED = 5
CLD_CONTINUED = 6
NSIGCLD = 6
POLL_IN = 1
POLL_OUT = 2
POLL_MSG = 3
POLL_ERR = 4
POLL_PRI = 5
POLL_HUP = 6
NSIGPOLL = 6
UME_ECCERR = 1
NSIGUME = 1
SIG_NOP = 0
SIG_BLOCK = 1
SIG_UNBLOCK = 2
SIG_SETMASK = 3
SIG_SETMASK32 = 256
SA_ONSTACK = 0x00000001
SA_RESETHAND = 0x00000002
SA_RESTART = 0x00000004
SA_SIGINFO = 0x00000008
SA_NODEFER = 0x00000010
SA_NOCLDWAIT = 0x00010000
SA_NOCLDSTOP = 0x00020000
_SA_BSDCALL = 0x10000000
MINSIGSTKSZ = 512
SIGSTKSZ = 8192
SS_ONSTACK = 0x00000001
SS_DISABLE = 0x00000002
# Included from sys/ucontext.h
NGREG = 36
NGREG = 37
GETCONTEXT = 0
SETCONTEXT = 1
UC_SIGMASK = 001
UC_STACK = 002
UC_CPU = 004
UC_MAU = 010
UC_MCONTEXT = (UC_CPU|UC_MAU)
UC_ALL = (UC_SIGMASK|UC_STACK|UC_MCONTEXT)
CTX_R0 = 0
CTX_AT = 1
CTX_V0 = 2
CTX_V1 = 3
CTX_A0 = 4
CTX_A1 = 5
CTX_A2 = 6
CTX_A3 = 7
CTX_T0 = 8
CTX_T1 = 9
CTX_T2 = 10
CTX_T3 = 11
CTX_T4 = 12
CTX_T5 = 13
CTX_T6 = 14
CTX_T7 = 15
CTX_A4 = 8
CTX_A5 = 9
CTX_A6 = 10
CTX_A7 = 11
CTX_T0 = 12
CTX_T1 = 13
CTX_T2 = 14
CTX_T3 = 15
CTX_S0 = 16
CTX_S1 = 17
CTX_S2 = 18
CTX_S3 = 19
CTX_S4 = 20
CTX_S5 = 21
CTX_S6 = 22
CTX_S7 = 23
CTX_T8 = 24
CTX_T9 = 25
CTX_K0 = 26
CTX_K1 = 27
CTX_GP = 28
CTX_SP = 29
CTX_S8 = 30
CTX_RA = 31
CTX_MDLO = 32
CTX_MDHI = 33
CTX_CAUSE = 34
CTX_EPC = 35
CTX_SR = 36
CXT_R0 = CTX_R0
CXT_AT = CTX_AT
CXT_V0 = CTX_V0
CXT_V1 = CTX_V1
CXT_A0 = CTX_A0
CXT_A1 = CTX_A1
CXT_A2 = CTX_A2
CXT_A3 = CTX_A3
CXT_T0 = CTX_T0
CXT_T1 = CTX_T1
CXT_T2 = CTX_T2
CXT_T3 = CTX_T3
CXT_T4 = CTX_T4
CXT_T5 = CTX_T5
CXT_T6 = CTX_T6
CXT_T7 = CTX_T7
CXT_S0 = CTX_S0
CXT_S1 = CTX_S1
CXT_S2 = CTX_S2
CXT_S3 = CTX_S3
CXT_S4 = CTX_S4
CXT_S5 = CTX_S5
CXT_S6 = CTX_S6
CXT_S7 = CTX_S7
CXT_T8 = CTX_T8
CXT_T9 = CTX_T9
CXT_K0 = CTX_K0
CXT_K1 = CTX_K1
CXT_GP = CTX_GP
CXT_SP = CTX_SP
CXT_S8 = CTX_S8
CXT_RA = CTX_RA
CXT_MDLO = CTX_MDLO
CXT_MDHI = CTX_MDHI
CXT_CAUSE = CTX_CAUSE
CXT_EPC = CTX_EPC
CXT_SR = CTX_SR
CTX_FV0 = 0
CTX_FV1 = 2
CTX_FA0 = 12
CTX_FA1 = 13
CTX_FA2 = 14
CTX_FA3 = 15
CTX_FA4 = 16
CTX_FA5 = 17
CTX_FA6 = 18
CTX_FA7 = 19
CTX_FT0 = 4
CTX_FT1 = 5
CTX_FT2 = 6
CTX_FT3 = 7
CTX_FT4 = 8
CTX_FT5 = 9
CTX_FT6 = 10
CTX_FT7 = 11
CTX_FT8 = 20
CTX_FT9 = 21
CTX_FT10 = 22
CTX_FT11 = 23
CTX_FT12 = 1
CTX_FT13 = 3
CTX_FS0 = 24
CTX_FS1 = 25
CTX_FS2 = 26
CTX_FS3 = 27
CTX_FS4 = 28
CTX_FS5 = 29
CTX_FS6 = 30
CTX_FS7 = 31
CTX_FT8 = 21
CTX_FT9 = 23
CTX_FT10 = 25
CTX_FT11 = 27
CTX_FT12 = 29
CTX_FT13 = 31
CTX_FT14 = 1
CTX_FT15 = 3
CTX_FS0 = 20
CTX_FS1 = 22
CTX_FS2 = 24
CTX_FS3 = 26
CTX_FS4 = 28
CTX_FS5 = 30
SV_ONSTACK = 0x0001
SV_INTERRUPT = 0x0002
NUMBSDSIGS = (32)
def sigmask(sig): return (1L << ((sig)-1))
def sigmask(sig): return (1L << ((sig)-1))
SIG_ERR = (-1)
SIG_IGN = (1)
SIG_HOLD = (2)
SIG_DFL = (0)
NSIG = 65
MAXSIG = (NSIG-1)
NUMSIGS = (NSIG-1)
BRK_USERBP = 0
BRK_KERNELBP = 1
BRK_ABORT = 2
BRK_BD_TAKEN = 3
BRK_BD_NOTTAKEN = 4
BRK_SSTEPBP = 5
BRK_OVERFLOW = 6
BRK_DIVZERO = 7
BRK_RANGE = 8
BRK_PSEUDO_OP_BIT = 0x80
BRK_PSEUDO_OP_MAX = 0x3
BRK_CACHE_SYNC = 0x80
BRK_MULOVF = 1023
_POSIX_VERSION = 199506L
_POSIX_VERSION = 199506
_POSIX_VDISABLE = 0
MAX_INPUT = 512
MAX_CANON = 256
UID_NOBODY = 60001
GID_NOBODY = UID_NOBODY
UID_NOACCESS = 60002
MAXPID = 0x7ffffff0
MAXUID = 0x7fffffff
MAXLINK = 30000
SSIZE = 1
SINCR = 1
KSTKSIZE = 1
EXTKSTKSIZE = 1
KSTKIDX = 0
KSTEIDX = 1
EXTKSTKSIZE = 0
KSTKIDX = 0
CANBSIZ = 256
HZ = 100
TICK = 10000000
NOFILE = 20
NGROUPS_UMIN = 0
NGROUPS_UMAX = 32
NGROUPS = 16
PMASK = 0177
PCATCH = 0400
PLTWAIT = 01000
PRECALC = 01000
PSWP = 0
PINOD = 10
PSNDD = PINOD
PRIBIO = 20
PZERO = 25
PMEM = 0
NZERO = 20
PPIPE = 26
PVFS = 27
PWAIT = 30
PSLEP = 39
PUSER = 60
PBATCH_CRITICAL = -1
PTIME_SHARE = -2
PTIME_SHARE_OVER = -3
PBATCH = -4
PWEIGHTLESS = -5
IO_NBPC = 4096
IO_BPCSHIFT = 12
MIN_NBPC = 4096
MIN_BPCSHIFT = 12
MIN_CPSSHIFT = 10
BPCSHIFT = 12
CPSSHIFT = 10
BPCSHIFT = 14
CPSSHIFT = 12
CPSSHIFT = 11
BPSSHIFT = (BPCSHIFT+CPSSHIFT)
NULL = 0L
CMASK = 022
NODEV = (-1)
NOPAGE = (-1)
NBPSCTR = 512
SCTRSHFT = 9
def BASEPRI(psw): return (((psw) & SR_IMASK) == SR_IMASK0)
def BASEPRI(psw): return (((psw) & SR_IMASK) == SR_IMASK)
def USERMODE(psw): return (((psw) & SR_KSU_MSK) == SR_KSU_USR)
MAXPATHLEN = 1024
MAXSYMLINKS = 30
MAXNAMELEN = 256
PIPE_BUF = 10240
PIPE_MAX = 10240
NBBY = 8
BBSHIFT = 9
BBSIZE = (1<<BBSHIFT)
BBMASK = (BBSIZE-1)
def BBTOB(bbs): return ((bbs) << BBSHIFT)
def OFFTOBB(bytes): return (((__uint64_t)(bytes) + BBSIZE - 1) >> BBSHIFT)
def OFFTOBBT(bytes): return ((off_t)(bytes) >> BBSHIFT)
def BBTOOFF(bbs): return ((off_t)(bbs) << BBSHIFT)
SEEKLIMIT32 = 0x7fffffff
MAXBSIZE = 8192
DEV_BSIZE = BBSIZE
DEV_BSHIFT = BBSHIFT
def btodb(bytes): return \
def dbtob(db): return \
BLKDEV_IOSHIFT = BPCSHIFT
BLKDEV_IOSIZE = (1<<BLKDEV_IOSHIFT)
def BLKDEV_OFF(off): return ((off) & (BLKDEV_IOSIZE - 1))
def BLKDEV_LBN(off): return ((off) >> BLKDEV_IOSHIFT)
def BLKDEV_LTOP(bn): return ((bn) * BLKDEV_BB)
MAXHOSTNAMELEN = 256
def DELAY(n): return us_delay(n)
def DELAYBUS(n): return us_delaybus(n)
TIMEPOKE_NOW = -100L
MUTEX_DEFAULT = 0x0
METER_NAMSZ = 16
METER_NO_SEQ = -1
def mutex_spinlock(l): return splhi()
def mutex_spintrylock(l): return splhi()
def spinlock_initialized(l): return 1
SV_FIFO = 0x0
SV_LIFO = 0x2
SV_PRIO = 0x4
SV_KEYED = 0x6
SV_DEFAULT = SV_FIFO
SEMA_NOHIST = 0x0001
SEMA_LOCK = 0x0004
NSCHEDCLASS = (-(PWEIGHTLESS)+1)
MR_ACCESS = 1
MR_UPDATE = 2
MRLOCK_BARRIER = 0x1
MRLOCK_BEHAVIOR = 0x2
MRLOCK_DBLTRIPPABLE = 0x4
MRLOCK_ALLOW_EQUAL_PRI = 0x8
MRLOCK_DEFAULT = MRLOCK_BARRIER
def mraccess(mrp): return mraccessf(mrp, 0)
def mrupdate(mrp): return mrupdatef(mrp, 0)
def mp_mutex_unlock(m): return mutex_unlock(m)
def mp_mutex_trylock(m): return mutex_trylock(m)
def mp_mutex_spinlock(m): return mutex_spinlock(m)
# Included from sys/mon.h
MON_LOCKED = 0x01
MON_WAITING = 0x02
MON_TIMEOUT = 0x04
MON_DOSRV = 0x08
MON_RUN = 0x10
MR_READER_BUCKETS = 13
def initlock(l): return spinlock_init(l,0)
def ownlock(x): return 1
def mutex_enter(m): return mutex_lock(m, PZERO)
def mutex_tryenter(m): return mutex_trylock(m)
def mutex_exit(m): return mutex_unlock(m)
def cv_signal(cv): return sv_signal(cv)
def cv_broadcast(cv): return sv_broadcast(cv)
def cv_destroy(cv): return sv_destroy(cv)
RW_READER = MR_ACCESS
RW_WRITER = MR_UPDATE
def rw_exit(r): return mrunlock(r)
def rw_tryupgrade(r): return mrtrypromote(r)
def rw_downgrade(r): return mrdemote(r)
def rw_destroy(r): return mrfree(r)
def RW_WRITE_HELD(r): return ismrlocked(r, MR_UPDATE)
def RW_READ_HELD(r): return ismrlocked(r, MR_ACCESS)
MS_FREE = 0
MS_UPD = 1
MS_ACC = 2
MS_WAITERS = 4
# Included from sys/fcntl.h
FNDELAY = 0x04
FAPPEND = 0x08
FSYNC = 0x10
FDSYNC = 0x20
FRSYNC = 0x40
FNONBLOCK = 0x80
FASYNC = 0x1000
FLARGEFILE = 0x2000
FNONBLK = FNONBLOCK
FDIRECT = 0x8000
FBULK = 0x10000
FDIRENT64 = 0x8000
FCREAT = 0x0100
FTRUNC = 0x0200
FEXCL = 0x0400
FNOCTTY = 0x0800
O_RDONLY = 0
O_WRONLY = 1
O_RDWR = 2
O_NDELAY = 0x04
O_APPEND = 0x08
O_SYNC = 0x10
O_DSYNC = 0x20
O_RSYNC = 0x40
O_NONBLOCK = 0x80
O_LARGEFILE = 0x2000
O_DIRECT = 0x8000
O_BULK = 0x10000
O_CREAT = 0x100
O_TRUNC = 0x200
O_EXCL = 0x400
O_NOCTTY = 0x800
F_DUPFD = 0
F_GETFD = 1
F_SETFD = 2
F_GETFL = 3
F_SETFL = 4
F_SETLK = 6
F_SETLKW = 7
F_CHKFL = 8
F_ALLOCSP = 10
F_FREESP = 11
F_SETBSDLK = 12
F_SETBSDLKW = 13
F_GETLK = 14
F_CHKLK = 15
F_CHKLKW = 16
F_CLNLK = 17
F_RSETLK = 20
F_RGETLK = 21
F_RSETLKW = 22
F_GETOWN = 23
F_SETOWN = 24
F_DIOINFO = 30
F_FSGETXATTR = 31
F_FSSETXATTR = 32
F_GETLK64 = 33
F_SETLK64 = 34
F_SETLKW64 = 35
F_ALLOCSP64 = 36
F_FREESP64 = 37
F_GETBMAP = 38
F_FSSETDM = 39
F_RESVSP = 40
F_UNRESVSP = 41
F_RESVSP64 = 42
F_UNRESVSP64 = 43
F_GETBMAPA = 44
F_FSGETXATTRA = 45
F_SETBIOSIZE = 46
F_GETBIOSIZE = 47
F_GETOPS = 50
F_DMAPI = 51
F_FSYNC = 52
F_FSYNC64 = 53
F_GETBDSATTR = 54
F_SETBDSATTR = 55
F_GETBMAPX = 56
F_SETPRIO = 57
F_GETPRIO = 58
F_RDLCK = 01
F_WRLCK = 02
F_UNLCK = 03
O_ACCMODE = 3
FD_CLOEXEC = 1
FD_NODUP_FORK = 4
BMV_IF_ATTRFORK = 0x1
BMV_IF_NO_DMAPI_READ = 0x2
BMV_IF_PREALLOC = 0x4
BMV_IF_VALID = (BMV_IF_ATTRFORK|BMV_IF_NO_DMAPI_READ|BMV_IF_PREALLOC)
BMV_OF_PREALLOC = 0x1
BMV_IF_EXTENDED = 0x40000000
FMASK = 0x190FF
FOPEN = 0xFFFFFFFF
FREAD = 0x01
FWRITE = 0x02
FNDELAY = 0x04
FAPPEND = 0x08
FSYNC = 0x10
FDSYNC = 0x20
FRSYNC = 0x40
FNONBLOCK = 0x80
FASYNC = 0x1000
FNONBLK = FNONBLOCK
FLARGEFILE = 0x2000
FDIRECT = 0x8000
FBULK = 0x10000
FCREAT = 0x0100
FTRUNC = 0x0200
FEXCL = 0x0400
FNOCTTY = 0x0800
FINVIS = 0x0100
FSOCKET = 0x0200
FINPROGRESS = 0x0400
FPRIORITY = 0x0800
FPRIO = 0x4000
FDIRENT64 = 0x8000
FCLOSEXEC = 0x01
LOCK_SH = 1
LOCK_EX = 2
LOCK_NB = 4
LOCK_UN = 8
L_SET = 0
L_INCR = 1
L_XTND = 2
F_OK = 0
X_OK = 1
W_OK = 2
R_OK = 4
|
jmehnle/ansible | refs/heads/devel | lib/ansible/modules/storage/netapp/na_cdot_user_role.py | 69 | #!/usr/bin/python
# (c) 2017, NetApp, Inc
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: na_cdot_user_role
short_description: useradmin configuration and management
extends_documentation_fragment:
- netapp.ontap
version_added: '2.3'
author: Sumit Kumar (sumit4@netapp.com)
description:
- Create or destroy user roles
options:
state:
description:
- Whether the specified user should exist or not.
required: true
choices: ['present', 'absent']
name:
description:
- The name of the role to manage.
required: true
command_directory_name:
description:
- The command or command directory to which the role has an access.
required: true
access_level:
description:
- The name of the role to manage.
choices: ['none', 'readonly', 'all']
default: 'all'
vserver:
description:
- The name of the vserver to use.
required: true
'''
EXAMPLES = """
- name: Create User Role
na_cdot_user_role:
state: present
name: ansibleRole
command_directory_name: DEFAULT
access_level: none
vserver: ansibleVServer
hostname: "{{ netapp_hostname }}"
username: "{{ netapp_username }}"
password: "{{ netapp_password }}"
"""
RETURN = """
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
import ansible.module_utils.netapp as netapp_utils
HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
class NetAppCDOTUserRole(object):
def __init__(self):
self.argument_spec = netapp_utils.ontap_sf_host_argument_spec()
self.argument_spec.update(dict(
state=dict(required=True, choices=['present', 'absent']),
name=dict(required=True, type='str'),
command_directory_name=dict(required=True, type='str'),
access_level=dict(required=False, type='str', default='all',
choices=['none', 'readonly', 'all']),
vserver=dict(required=True, type='str'),
))
self.module = AnsibleModule(
argument_spec=self.argument_spec,
supports_check_mode=True
)
p = self.module.params
# set up state variables
self.state = p['state']
self.name = p['name']
self.command_directory_name = p['command_directory_name']
self.access_level = p['access_level']
self.vserver = p['vserver']
if HAS_NETAPP_LIB is False:
self.module.fail_json(msg="the python NetApp-Lib module is required")
else:
self.server = netapp_utils.setup_ontap_zapi(module=self.module)
def get_role(self):
"""
Checks if the role exists for specific command-directory-name.
:return:
True if role found
False if role is not found
:rtype: bool
"""
security_login_role_get_iter = netapp_utils.zapi.NaElement(
'security-login-role-get-iter')
query_details = netapp_utils.zapi.NaElement.create_node_with_children(
'security-login-role-info', **{'vserver': self.vserver,
'role-name': self.name,
'command-directory-name':
self.command_directory_name})
query = netapp_utils.zapi.NaElement('query')
query.add_child_elem(query_details)
security_login_role_get_iter.add_child_elem(query)
try:
result = self.server.invoke_successfully(
security_login_role_get_iter, enable_tunneling=False)
except netapp_utils.zapi.NaApiError:
e = get_exception()
# Error 16031 denotes a role not being found.
if str(e.code) == "16031":
return False
else:
self.module.fail_json(msg='Error getting role %s' % self.name, exception=str(e))
if (result.get_child_by_name('num-records') and
int(result.get_child_content('num-records')) >= 1):
return True
else:
return False
def create_role(self):
role_create = netapp_utils.zapi.NaElement.create_node_with_children(
'security-login-role-create', **{'vserver': self.vserver,
'role-name': self.name,
'command-directory-name':
self.command_directory_name,
'access-level':
self.access_level})
try:
self.server.invoke_successfully(role_create,
enable_tunneling=False)
except netapp_utils.zapi.NaApiError:
err = get_exception()
self.module.fail_json(msg='Error creating role %s' % self.name, exception=str(err))
def delete_role(self):
role_delete = netapp_utils.zapi.NaElement.create_node_with_children(
'security-login-role-delete', **{'vserver': self.vserver,
'role-name': self.name,
'command-directory-name':
self.command_directory_name})
try:
self.server.invoke_successfully(role_delete,
enable_tunneling=False)
except netapp_utils.zapi.NaApiError:
err = get_exception()
self.module.fail_json(msg='Error removing role %s' % self.name, exception=str(err))
def apply(self):
changed = False
role_exists = self.get_role()
if role_exists:
if self.state == 'absent':
changed = True
# Check if properties need to be updated
else:
if self.state == 'present':
changed = True
if changed:
if self.module.check_mode:
pass
else:
if self.state == 'present':
if not role_exists:
self.create_role()
# Update properties
elif self.state == 'absent':
self.delete_role()
self.module.exit_json(changed=changed)
def main():
v = NetAppCDOTUserRole()
v.apply()
if __name__ == '__main__':
main()
|
piqoni/onadata | refs/heads/master | onadata/apps/api/tools.py | 3 | import os
from datetime import datetime
import numpy as np
from django import forms
from django.conf import settings
from django.core.files.storage import get_storage_class
from django.contrib.auth.models import Permission
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.db.models import Q
from django.http import HttpResponseNotFound
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.shortcuts import get_object_or_404
from taggit.forms import TagField
from rest_framework import exceptions
from registration.models import RegistrationProfile
from onadata.apps.api.models.organization_profile import OrganizationProfile
from onadata.apps.api.models.team import Team
from onadata.apps.main.forms import QuickConverter
from onadata.apps.logger.models.project import Project
from onadata.apps.logger.models.xform import XForm
from onadata.apps.viewer.models.parsed_instance import datetime_from_str
from onadata.libs.data.query import get_field_records
from onadata.libs.data.query import get_numeric_fields
from onadata.libs.utils.logger_tools import publish_form
from onadata.libs.utils.logger_tools import response_with_mimetype_and_name
from onadata.libs.utils.project_utils import set_project_perms_to_xform
from onadata.libs.utils.user_auth import check_and_set_form_by_id
from onadata.libs.utils.user_auth import check_and_set_form_by_id_string
from onadata.libs.data.statistics import _chk_asarray
from onadata.libs.permissions import ROLES
from onadata.libs.permissions import get_role_in_org
DECIMAL_PRECISION = 2
def _get_first_last_names(name):
name_split = name.split()
first_name = name_split[0]
last_name = u''
if len(name_split) > 1:
last_name = u' '.join(name_split[1:])
return first_name, last_name
def _get_id_for_type(record, mongo_field):
date_field = datetime_from_str(record[mongo_field])
mongo_str = '$' + mongo_field
return {"$substr": [mongo_str, 0, 10]} if isinstance(date_field, datetime)\
else mongo_str
def get_accessible_forms(owner=None, shared_form=False, shared_data=False):
xforms = XForm.objects.filter()
if shared_form and not shared_data:
xforms = xforms.filter(shared=True)
elif (shared_form and shared_data) or \
(owner == 'public' and not shared_form and not shared_data):
xforms = xforms.filter(Q(shared=True) | Q(shared_data=True))
elif not shared_form and shared_data:
xforms = xforms.filter(shared_data=True)
if owner != 'public':
xforms = xforms.filter(user__username=owner)
return xforms.distinct()
def create_organization(name, creator):
"""
Organization created by a user
- create a team, OwnerTeam with full permissions to the creator
- Team(name='Owners', organization=organization).save()
"""
organization = User.objects.create(username=name)
organization_profile = OrganizationProfile.objects.create(
user=organization, creator=creator)
return organization_profile
def create_organization_object(org_name, creator, attrs={}):
'''Creates an OrganizationProfile object without saving to the database'''
name = attrs.get('name', org_name)
first_name, last_name = _get_first_last_names(name)
email = attrs.get('email', u'')
new_user = User(username=org_name, first_name=first_name,
last_name=last_name, email=email, is_active=True)
new_user.save()
registration_profile = RegistrationProfile.objects.create_profile(new_user)
if email:
site = Site.objects.get(pk=settings.SITE_ID)
registration_profile.send_activation_email(site)
profile = OrganizationProfile(
user=new_user, name=name, creator=creator,
created_by=creator,
city=attrs.get('city', u''),
country=attrs.get('country', u''),
organization=attrs.get('organization', u''),
home_page=attrs.get('home_page', u''),
twitter=attrs.get('twitter', u''))
return profile
def create_organization_team(organization, name, permission_names=[]):
organization = organization.user \
if isinstance(organization, OrganizationProfile) else organization
team = Team.objects.create(organization=organization, name=name)
content_type = ContentType.objects.get(
app_label='api', model='organizationprofile')
if permission_names:
# get permission objects
perms = Permission.objects.filter(
codename__in=permission_names, content_type=content_type)
if perms:
team.permissions.add(*tuple(perms))
return team
def get_organization_members_team(organization):
"""Get organization members team
create members team if it does not exist and add organization owner
to the members team"""
try:
team = Team.objects.get(
name=u'%s#%s' % (organization.user.username, 'members'))
except Team.DoesNotExist:
team = create_organization_team(organization, 'members')
add_user_to_team(team, organization.user)
return team
def remove_user_from_organization(organization, user):
"""Remove a user from an organization"""
team = get_organization_members_team(organization)
remove_user_from_team(team, user)
def remove_user_from_team(team, user):
user.groups.remove(team)
def add_user_to_organization(organization, user):
"""Add a user to an organization"""
team = get_organization_members_team(organization)
add_user_to_team(team, user)
def add_user_to_team(team, user):
user.groups.add(team)
def get_organization_members(organization):
"""Get members team user queryset"""
team = get_organization_members_team(organization)
return team.user_set.all()
def create_organization_project(organization, project_name, created_by):
"""Creates a project for a given organization
:param organization: User organization
:param project_name
:param created_by: User with permissions to create projects within the
organization
:returns: a Project instance
"""
profile = OrganizationProfile.objects.get(user=organization)
if not profile.is_organization_owner(created_by):
return None
project = Project.objects.create(name=project_name,
organization=organization,
created_by=created_by)
return project
def add_team_to_project(team, project):
"""Adds a team to a project
:param team:
:param project:
:returns: True if successful or project has already been added to the team
"""
if isinstance(team, Team) and isinstance(project, Project):
if not team.projects.filter(pk=project.pk):
team.projects.add(project)
return True
return False
def publish_xlsform(request, user, id_string=None):
if not request.user.has_perm('can_add_xform', user.profile):
raise exceptions.PermissionDenied(
detail=_(u"User %(user)s has no permission to add xforms to "
"account %(account)s" % {'user': request.user.username,
'account': user.username}))
def set_form():
form = QuickConverter(request.POST, request.FILES)
return form.publish(user, id_string=id_string, created_by=request.user)
return publish_form(set_form)
def publish_project_xform(request, project):
def set_form():
form = QuickConverter({'project': project.pk}, request.FILES)
return form.publish(project.organization, created_by=request.user)
xform = None
if 'formid' in request.DATA:
xform = get_object_or_404(XForm, pk=request.DATA.get('formid'))
xform.project = project
xform.save()
set_project_perms_to_xform(xform, project)
else:
xform = publish_form(set_form)
return xform
def mode(a, axis=0):
"""
Adapted from
https://github.com/scipy/scipy/blob/master/scipy/stats/stats.py#L568
"""
a, axis = _chk_asarray(a, axis)
scores = np.unique(np.ravel(a)) # get ALL unique values
testshape = list(a.shape)
testshape[axis] = 1
oldmostfreq = np.zeros(testshape)
oldcounts = np.zeros(testshape)
for score in scores:
template = (a == score)
counts = np.expand_dims(np.sum(template, axis), axis)
mostfrequent = np.where(counts > oldcounts, score, oldmostfreq)
oldcounts = np.maximum(counts, oldcounts)
oldmostfreq = mostfrequent
return mostfrequent, oldcounts
def get_median_for_field(field, xform):
return np.median(get_field_records(field, xform))
def get_median_for_numeric_fields_in_form(xform, field=None):
data = {}
for field_name in [field] if field else get_numeric_fields(xform):
median = get_median_for_field(field_name, xform)
data.update({field_name: median})
return data
def get_mean_for_field(field, xform):
return np.mean(get_field_records(field, xform))
def get_mean_for_numeric_fields_in_form(xform, field):
data = {}
for field_name in [field] if field else get_numeric_fields(xform):
mean = get_mean_for_field(field_name, xform)
data.update({field_name: round(mean, DECIMAL_PRECISION)})
return data
def get_mode_for_field(field, xform):
a = np.array(get_field_records(field, xform))
m, count = mode(a)
return m
def get_mode_for_numeric_fields_in_form(xform, field=None):
data = {}
for field_name in [field] if field else get_numeric_fields(xform):
mode = get_mode_for_field(field_name, xform)
data.update({field_name: round(mode, DECIMAL_PRECISION)})
return data
def get_min_max_range_for_field(field, xform):
a = np.array(get_field_records(field, xform))
_max = np.max(a)
_min = np.min(a)
_range = _max - _min
return _min, _max, _range
def get_min_max_range(xform, field=None):
data = {}
for field_name in [field] if field else get_numeric_fields(xform):
_min, _max, _range = get_min_max_range_for_field(field_name, xform)
data[field_name] = {'max': _max, 'min': _min, 'range': _range}
return data
def get_all_stats(xform, field=None):
data = {}
for field_name in [field] if field else get_numeric_fields(xform):
_min, _max, _range = get_min_max_range_for_field(field_name, xform)
mode = get_mode_for_field(field_name, xform)
mean = get_mean_for_field(field_name, xform)
median = get_median_for_field(field_name, xform)
data[field_name] = {
'mean': round(mean, DECIMAL_PRECISION),
'median': median,
'mode': round(mode, DECIMAL_PRECISION),
'max': _max,
'min': _min,
'range': _range
}
return data
def get_xform(formid, request, username=None):
try:
formid = int(formid)
except ValueError:
username = username is None and request.user.username
xform = check_and_set_form_by_id_string(username, formid, request)
else:
xform = check_and_set_form_by_id(int(formid), request)
if not xform:
raise exceptions.PermissionDenied(_(
"You do not have permission to view data from this form."))
return xform
def get_user_profile_or_none(username):
profile = None
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
else:
profile = user.profile
return profile
def add_tags_to_instance(request, instance):
class TagForm(forms.Form):
tags = TagField()
form = TagForm(request.DATA)
if form.is_valid():
tags = form.cleaned_data.get('tags', None)
if tags:
for tag in tags:
instance.instance.tags.add(tag)
instance.save()
def get_media_file_response(metadata):
if metadata.data_file:
file_path = metadata.data_file.name
filename, extension = os.path.splitext(file_path.split('/')[-1])
extension = extension.strip('.')
dfs = get_storage_class()()
if dfs.exists(file_path):
response = response_with_mimetype_and_name(
metadata.data_file_type,
filename, extension=extension, show_date=False,
file_path=file_path, full_mime=True)
return response
else:
return HttpResponseNotFound()
else:
return HttpResponseRedirect(metadata.data_value)
def check_inherit_permission_from_project(xform_id, user):
if xform_id == 'public':
return
try:
int(xform_id)
except ValueError:
return
# get the project_xform
xforms = XForm.objects.filter(pk=xform_id)
if not xforms:
return
# get and compare the project role to the xform role
project_role = get_role_in_org(user, xforms[0].project)
xform_role = get_role_in_org(user, xforms[0])
# if diff set the project role to the xform
if xform_role != project_role:
_set_xform_permission(project_role, user, xforms[0])
def _set_xform_permission(role, user, xform):
role_class = ROLES.get(role)
if role_class:
role_class.add(user, xform)
|
sajuptpm/neutron-ipam | refs/heads/stable/icehouse | neutron/plugins/metaplugin/__init__.py | 108 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012, Nachi Ueno, NTT MCL, 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.
|
ApuliaSoftware/odoo | refs/heads/8.0 | addons/pad/__openerp__.py | 249 | # -*- coding: utf-8 -*-
{
'name': 'Collaborative Pads',
'version': '2.0',
'category': 'Project Management',
'description': """
Adds enhanced support for (Ether)Pad attachments in the web client.
===================================================================
Lets the company customize which Pad installation should be used to link to new
pads (by default, http://etherpad.com/).
""",
'author': 'OpenERP SA',
'website': 'https://www.odoo.com/page/notes',
'depends': ['web'],
'data': [
'res_company.xml',
'views/pad.xml',
],
'demo': ['pad_demo.xml'],
'installable': True,
'auto_install': False,
'web': True,
'qweb' : ['static/src/xml/*.xml'],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
ahmedbodi/vertcoin | refs/heads/master | test/functional/wallet_fallbackfee.py | 42 | #!/usr/bin/env python3
# Copyright (c) 2017-2018 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 wallet replace-by-fee capabilities in conjunction with the fallbackfee."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_raises_rpc_error
class WalletRBFTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def run_test(self):
self.nodes[0].generate(101)
# sending a transaction without fee estimations must be possible by default on regtest
self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
# test sending a tx with disabled fallback fee (must fail)
self.restart_node(0, extra_args=["-fallbackfee=0"])
assert_raises_rpc_error(-4, "Fee estimation failed", lambda: self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1))
assert_raises_rpc_error(-4, "Fee estimation failed", lambda: self.nodes[0].fundrawtransaction(self.nodes[0].createrawtransaction([], {self.nodes[0].getnewaddress(): 1})))
assert_raises_rpc_error(-6, "Fee estimation failed", lambda: self.nodes[0].sendmany("", {self.nodes[0].getnewaddress(): 1}))
if __name__ == '__main__':
WalletRBFTest().main()
|
evidation-health/bokeh | refs/heads/master | bokeh/session.py | 42 | ''' The session module provides the Session class, which encapsulates a
connection to a Document that resides on a Bokeh server.
The Session class provides methods for creating, loading and storing
documents and objects, as well as methods for user-authentication. These
are useful when the server is run in multi-user mode.
'''
from __future__ import absolute_import, print_function
#--------
# logging
#--------
import logging
logger = logging.getLogger(__name__)
#-------------
# standard lib
#-------------
import time
import json
from os import makedirs
from os.path import expanduser, exists, join
import tempfile
#------------
# third party
#------------
from six.moves.urllib.parse import urlencode
from requests.exceptions import ConnectionError
#---------
# optional
#---------
try:
import pandas as pd
import tables
has_pandas = True
except ImportError as e:
has_pandas = False
#--------
# project
#--------
from . import browserlib
from . import protocol
from .embed import autoload_server
from .exceptions import DataIntegrityException
from .util.notebook import publish_display_data
from .util.serialization import dump, get_json, urljoin
DEFAULT_SERVER_URL = "http://localhost:5006/"
class Session(object):
""" Encapsulate a connection to a document stored on a Bokeh Server.
Args:
name (str, optional) : name of server
root_url (str, optional) : root url of server
userapikey (str, optional) : (default: "nokey")
username (str, optional) : (default: "defaultuser")
load_from_config (bool, optional) :
Whether to load login information from config. (default: True)
If False, then we may overwrite the user's config.
configdir (str) : location of user configuration information
Attributes:
base_url (str) :
configdir (str) :
configfile (str) :
http_session (requests.session) :
userapikey (str) :
userinfo (dict) :
username (str) :
"""
def __init__(
self,
name = DEFAULT_SERVER_URL,
root_url = DEFAULT_SERVER_URL,
userapikey = "nokey",
username = "defaultuser",
load_from_config = True,
configdir = None,
):
self.name = name
if not root_url.endswith("/"):
logger.warning("root_url should end with a /, adding one")
root_url = root_url + "/"
self.root_url = root_url
# single user mode case
self.userapikey = userapikey
self.username = username
self._configdir = None
if configdir:
self.configdir = configdir
if load_from_config:
self.load()
@property
def http_session(self):
if hasattr(self, "_http_session"):
return self._http_session
else:
import requests
self._http_session = requests.session()
return self._http_session
@property
def username(self):
return self.http_session.headers.get('BOKEHUSER')
@username.setter
def username(self, val):
self.http_session.headers.update({'BOKEHUSER': val})
@property
def userapikey(self):
return self.http_session.headers.get('BOKEHUSER-API-KEY')
@userapikey.setter
def userapikey(self, val):
self.http_session.headers.update({'BOKEHUSER-API-KEY': val})
@property
def configdir(self):
""" filename where our config are stored. """
if self._configdir:
return self._configdir
bokehdir = join(expanduser("~"), ".bokeh")
if not exists(bokehdir):
makedirs(bokehdir)
return bokehdir
# for testing
@configdir.setter
def configdir(self, path):
self._configdir = path
@property
def configfile(self):
return join(self.configdir, "config.json")
def load_dict(self):
configfile = self.configfile
if not exists(configfile):
data = {}
else:
with open(configfile, "r") as f:
data = json.load(f)
return data
def load(self):
""" Loads the server configuration information from disk
Returns:
None
"""
config_info = self.load_dict().get(self.name, {})
print("Using saved session configuration for %s" % self.name)
print("To override, pass 'load_from_config=False' to Session")
self.root_url = config_info.get('root_url', self.root_url)
self.userapikey = config_info.get('userapikey', self.userapikey)
self.username = config_info.get('username', self.username)
def save(self):
""" Save the server configuration information to JSON
Returns:
None
"""
data = self.load_dict()
data[self.name] = {'root_url': self.root_url,
'userapikey': self.userapikey,
'username': self.username}
configfile = self.configfile
with open(configfile, "w+") as f:
json.dump(data, f)
def register(self, username, password):
''' Register a new user with a bokeh server.
.. note::
This is useful in multi-user mode.
Args:
username (str) : user name to register
password (str) : user password for account
Returns:
None
'''
url = urljoin(self.root_url, "bokeh/register")
result = self.execute('post', url, data={
'username': username,
'password': password,
'api': 'true'
})
if result.status_code != 200:
raise RuntimeError("Unknown Error")
result = get_json(result)
if result['status']:
self.username = username
self.userapikey = result['userapikey']
self.save()
else:
raise RuntimeError(result['error'])
def login(self, username, password):
''' Log a user into a bokeh server.
.. note::
This is useful in multi-user mode.
Args:
username (str) : user name to log in
password (str) : user password
Returns:
None
'''
url = urljoin(self.root_url, "bokeh/login")
result = self.execute('post', url, data={
'username': username,
'password': password,
'api': 'true'
})
if result.status_code != 200:
raise RuntimeError("Unknown Error")
result = get_json(result)
if result['status']:
self.username = username
self.userapikey = result['userapikey']
self.save()
else:
raise RuntimeError(result['error'])
self.save()
def browser_login(self):
""" Open a browser with a token that logs the user into a bokeh server.
.. note::
This is useful in multi-user mode.
Return:
None
"""
controller = browserlib.get_browser_controller()
url = urljoin(self.root_url, "bokeh/loginfromapikey")
url += "?" + urlencode({'username': self.username,
'userapikey': self.userapikey})
controller.open(url)
def data_source(self, name, data):
""" Makes and uploads a server data source to the server.
.. note::
The server must be configured with a data directory.
Args:
name (str) : name for the data source object
data (pd.DataFrame or np.array) : data to upload
Returns:
a ServerDataSource
"""
raise NotImplementedError
def list_data(self):
""" Return all the data soruces on the server.
Returns:
sources : JSON
"""
raise NotImplementedError
def publish(self):
url = urljoin(self.root_url, "/bokeh/%s/publish" % self.docid)
self.post_json(url)
def execute(self, method, url, headers=None, **kwargs):
""" Execute an HTTP request using the current session.
Returns the response
Args:
method (string) : 'get' or 'post'
url (string) : url
headers (dict, optional) : any extra HTTP headers
Keyword Args:
Any extra arguments to pass into the requests library
Returns:
response
Returns the response
"""
import requests
import warnings
func = getattr(self.http_session, method)
try:
resp = func(url, headers=headers, **kwargs)
except requests.exceptions.ConnectionError as e:
warnings.warn("You need to start the bokeh-server to see this example.")
raise e
if resp.status_code == 409:
raise DataIntegrityException
if resp.status_code == 401:
raise Exception('HTTP Unauthorized accessing')
return resp
def execute_json(self, method, url, headers=None, **kwargs):
""" same as execute, except ensure that json content-type is
set in headers and interprets and returns the json response
"""
if headers is None:
headers = {}
headers['content-type'] = 'application/json'
resp = self.execute(method, url, headers=headers, **kwargs)
return get_json(resp)
def get_json(self, url, headers=None, **kwargs):
""" Return the result of an HTTP 'get'.
Args:
url (str) : the URL for the 'get' request
headers (dict, optional) : any extra HTTP headers
Keyword Args:
Any extra arguments to pass into the requests library
Returns:
response: JSON
"""
return self.execute_json('get', url, headers=headers, **kwargs)
def post_json(self, url, headers=None, **kwargs):
""" Return the result of an HTTP 'post'
Args:
url (str) : the URL for the 'get' request
headers (dict, optional) : any extra HTTP headers
Keyword Args:
Any extra arguments to pass into the requests library
Returns:
response: JSON
"""
return self.execute_json('post', url, headers=headers, **kwargs)
@property
def userinfo(self):
if not hasattr(self, "_userinfo"):
url = urljoin(self.root_url, 'bokeh/userinfo/')
self._userinfo = self.get_json(url)
return self._userinfo
@userinfo.setter
def userinfo(self, val):
self._userinfo = val
@property
def base_url(self):
return urljoin(self.root_url, "bokeh/bb/")
def get_api_key(self, docid):
""" Retrieve the document API key from the server.
Args:
docid (string) : docid of the document to retrive API key for
Returns:
apikey : string
"""
url = urljoin(self.root_url,"bokeh/getdocapikey/%s" % docid)
apikey = self.get_json(url)
if 'apikey' in apikey:
apikey = apikey['apikey']
logger.info('got read write apikey')
else:
apikey = apikey['readonlyapikey']
logger.info('got read only apikey')
return apikey
def find_doc(self, name):
""" Return the docid of the document with a title matching ``name``.
.. note::
Creates a new document with the given title if one is not found.
Args:
name (string) : name for the document
Returns:
docid : str
"""
docs = self.userinfo.get('docs')
matching = [x for x in docs if x.get('title') == name]
if len(matching) == 0:
logger.info("No documents found, creating new document '%s'" % name)
self.make_doc(name)
return self.find_doc(name)
elif len(matching) > 1:
logger.warning("Multiple documents with name '%s'" % name)
return matching[0]['docid']
def use_doc(self, name=None, docid=None):
""" Configure the session to use a given document.
Args:
name (str, optional) : name of the document to use
docid (str, optional) : id of the document to use
.. note::
only one of ``name`` or ``docid`` may be supplied.
Creates a document for with the given name if one is not present on
the server.
Returns:
None
"""
if docid is not None and name is not None:
raise ValueError("only one of 'name' or 'docid' can be supplied to use_doc(...)")
if docid:
self.docid = docid
else:
self.docid = self.find_doc(name)
self.apikey = self.get_api_key(self.docid)
def make_doc(self, title):
""" Makes a new document with the given title on the server
.. note:: user information is reloaded
Returns:
None
"""
url = urljoin(self.root_url,"bokeh/doc/")
data = protocol.serialize_json({'title' : title})
self.userinfo = self.post_json(url, data=data)
def pull(self, typename=None, objid=None):
""" Pull JSON objects from the server.
Returns a specific object if both ``typename`` and ``objid`` are
supplied. Otherwise, returns all objects for the currently configured
document.
This is a low-level function.
Args:
typename (str, optional) : name of the type of object to pull
objid (str, optional) : ID of the object to pull
.. note::
you must supply either ``typename`` AND ``objid`` or omit both.
Returns:
attrs : JSON
"""
if typename is None and objid is None:
url = urljoin(self.base_url, self.docid +"/")
attrs = self.get_json(url)
elif typename is None or objid is None:
raise ValueError("typename and objid must both be None, or neither.")
else:
url = urljoin(
self.base_url,
self.docid + "/" + typename + "/" + objid + "/"
)
attr = self.get_json(url)
attrs = [{
'type': typename,
'id': objid,
'attributes': attr
}]
return attrs
def push(self, *jsonobjs):
""" Push JSON objects to the server.
This is a low-level function.
Args:
*jsonobjs (JSON) : objects to push to the server
Returns:
None
"""
data = protocol.serialize_json(jsonobjs)
url = urljoin(self.base_url, self.docid + "/", "bulkupsert")
self.post_json(url, data=data)
def gc(self):
url = urljoin(self.base_url, self.docid + "/", "gc")
self.post_json(url)
# convenience functions to use a session and store/fetch from server
def load_document(self, doc):
""" Loads data for the session and merge with the given document.
Args:
doc (Document) : document to load data into
Returns:
None
"""
self.gc()
json_objs = self.pull()
doc.merge(json_objs)
doc.docid = self.docid
def load_object(self, obj, doc):
""" Update an object in a document with data pulled from the server.
Args:
obj (PlotObject) : object to be updated
doc (Document) : the object's document
Returns:
None
"""
assert obj._id in doc._models
attrs = self.pull(typename=obj.__view_model__, objid=obj._id)
doc.load(*attrs)
def store_document(self, doc, dirty_only=True):
""" Store a document on the server.
Returns the models that were actually pushed.
Args:
doc (Document) : the document to store
dirty_only (bool, optional) : whether to store only dirty objects. (default: True)
Returns:
models : list[PlotObject]
"""
doc._add_all()
models = doc._models.values()
if dirty_only:
models = [x for x in models if getattr(x, '_dirty', False)]
json_objs = doc.dump(*models)
self.push(*json_objs)
for model in models:
model._dirty = False
return models
def store_objects(self, *objs, **kwargs):
""" Store objects on the server
Returns the objects that were actually stored.
Args:
*objs (PlotObject) : objects to store
Keywords Args:
dirty_only (bool, optional) : whether to store only dirty objects. (default: True)
Returns:
models : set[PlotObject]
"""
models = set()
for obj in objs:
models.update(obj.references())
if kwargs.pop('dirty_only', True):
models = list(models)
json_objs = dump(models, self.docid)
self.push(*json_objs)
for model in models:
model._dirty = False
return models
def object_link(self, obj):
""" Return a URL to a server page that will render the given object.
Args:
obj (PlotObject) : object to render
Returns:
URL string
"""
link = "bokeh/doc/%s/%s" % (self.docid, obj._id)
return urljoin(self.root_url, link)
def show(self, obj):
""" Display an object as HTML in IPython using its display protocol.
Args:
obj (PlotObject) : object to display
Returns:
None
"""
data = {'text/html': autoload_server(obj, self)}
publish_display_data(data)
def poll_document(self, document, interval=0.5):
""" Periodically ask the server for updates to the `document`. """
try:
while True:
self.load_document(document)
time.sleep(interval)
except KeyboardInterrupt:
print()
except ConnectionError:
print("Connection to bokeh-server was terminated")
# helper methods
def _prep_data_source_df(self, name, dataframe):
name = tempfile.NamedTemporaryFile(prefix="bokeh_data",
suffix=".pandas").name
store = pd.HDFStore(name)
store.append("__data__", dataframe, format="table", data_columns=True)
store.close()
return name
def _prep_data_source_numpy(self, name, arr):
name = tempfile.NamedTemporaryFile(prefix="bokeh_data",
suffix=".table").name
store = tables.File(name, 'w')
store.createArray("/", "__data__", obj=arr)
store.close()
return name
class TestSession(Session):
"""Currently, register and login do not work, everything else should work
in theory, but we'll have to test this as we go along and convert tests
"""
def __init__(self, *args, **kwargs):
if 'load_from_config' not in kwargs:
kwargs['load_from_config'] = False
self.client = kwargs.pop('client')
self.headers = {}
super(TestSession, self).__init__(*args, **kwargs)
@property
def username(self):
return self.headers.get('BOKEHUSER')
@username.setter
def username(self, val):
self.headers.update({'BOKEHUSER': val})
@property
def userapikey(self):
return self.headers.get('BOKEHUSER-API-KEY')
@userapikey.setter
def userapikey(self, val):
self.headers.update({'BOKEHUSER-API-KEY': val})
def execute(self, method, url, headers=None, **kwargs):
if headers is None:
headers = {}
func = getattr(self.client, method)
resp = func(url, headers=headers, **kwargs)
if resp.status_code == 409:
raise DataIntegrityException
if resp.status_code == 401:
raise Exception('HTTP Unauthorized accessing')
return resp
|
project-generator/project_generator | refs/heads/master | project_generator/tools/iar.py | 1 | # Copyright 2015 0xc0170
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import logging
import xmltodict
import subprocess
from subprocess import Popen, PIPE
import time
import copy
import re
import os
from os import getcwd
from os.path import join, normpath
from collections import OrderedDict
from project_generator_definitions.definitions import ProGenDef
from .tool import Tool, Builder, Exporter
from ..util import SOURCE_KEYS, FILES_EXTENSIONS, fix_paths
logger = logging.getLogger('progen.tools.iar')
class IARDefinitions():
""" Definitions for IAR Workbench IDE """
# TODO: Fix this with the parser!
debuggers = {
'cmsis-dap': {
'OCDynDriverList': {
'state' : 'CMSISDAP_ID',
},
'interface': {
'name' : 'CMSISDAPInterfaceRadio', # each debuger has own names for th1s
'jtag' : 0, # TODO: verify that jtag maches for all debuggers to have it just defined once
'swd' : 1,
}
},
'j-link': {
'OCDynDriverList': {
'state' : 'JLINK_ID',
},
'interface': {
'name' : 'CCJLinkInterfaceRadio',
'jtag' : 0,
'swd' : 1,
}
},
'st-link': {
'OCDynDriverList': {
'state' : 'STLINK_ID',
},
'interface': {
'name' : 'CCSTLinkInterfaceRadio',
'jtag' : 0,
'swd' : 1,
}
},
}
class IAREmbeddedWorkbenchProject:
""" This class handles all related project settings """
# IAR misc contains enable check and then state. Therefore we map here
# each flag to dict to know which one to enable and set those options
FLAG_TO_IAR = {
'asm_flags' : {
'enable': 'AExtraOptionsCheckV2',
'set' : 'AExtraOptionsV2',
},
'c_flags' : {
'enable': 'IExtraOptionsCheck',
'set' : 'IExtraOptions',
},
'cxx_flags' : {
'enable': 'IExtraOptionsCheck',
'set' : 'IExtraOptions',
},
'ld_flags' : {
'enable': 'IlinkUseExtraOptions',
'set' : 'IlinkExtraOptions',
},
}
def _set_option(self, settings, value):
""" Set option (state) """
settings['state'] = value
def _get_option(self, settings, find_key):
""" Return index for provided key """
# This is used as in IAR template, everything
# is as an array with random positions. We look for key with an index
for option in settings:
if option['name'] == find_key:
return settings.index(option)
def _set_multiple_option(self, settings, value_list):
settings['state'] = []
for value in value_list:
settings['state'].append(value)
def _ewp_general_set(self, ewp_dic, project_dic):
index_general = self._get_option(ewp_dic, 'General')
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'ExePath')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], join('$PROJ_DIR$', project_dic['build_dir'], 'Exe'))
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'ObjPath')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], join('$PROJ_DIR$', project_dic['build_dir'], 'Obj'))
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'ListPath')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], join('$PROJ_DIR$', project_dic['build_dir'], 'List'))
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'GOutputBinary')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], 0 if project_dic['output_type'] == 'exe' else 1)
def _ewp_iccarm_set(self, ewp_dic, project_dic):
""" C/C++ options (ICCARM) """
index_iccarm = self._get_option(ewp_dic, 'ICCARM')
index_option = self._get_option(ewp_dic[index_iccarm]['data']['option'], 'CCDefines')
self._set_multiple_option(ewp_dic[index_iccarm]['data']['option'][index_option], project_dic['macros'])
index_option = self._get_option(ewp_dic[index_iccarm]['data']['option'], 'CCIncludePath2')
self._set_multiple_option(ewp_dic[index_iccarm]['data']['option'][index_option], project_dic['include_paths'])
iccarm_dic = ewp_dic[index_iccarm]['data']['option']
self._ewp_flags_set(iccarm_dic, project_dic, 'cxx_flags', self.FLAG_TO_IAR['cxx_flags'])
self._ewp_flags_set(iccarm_dic, project_dic, 'c_flags', self.FLAG_TO_IAR['c_flags'])
def _ewp_aarm_set(self, ewp_dic, project_dic):
""" Assembly options (AARM) """
index_aarm = self._get_option(ewp_dic, 'AARM')
aarm_dic = ewp_dic[index_aarm]['data']['option']
self._ewp_flags_set(aarm_dic, project_dic, 'asm_flags', self.FLAG_TO_IAR['asm_flags'])
def _ewp_ilink_set(self, ewp_dic, project_dic):
""" Linker options (ILINK) """
index_ilink = self._get_option(ewp_dic, 'ILINK')
index_option = self._get_option(ewp_dic[index_ilink]['data']['option'], 'IlinkIcfFile')
self._set_option(ewp_dic[index_ilink]['data']['option'][index_option], project_dic['linker_file'])
ilink_dic = ewp_dic[index_ilink]['data']['option']
self._ewp_flags_set(ilink_dic, project_dic, 'ld_flags', self.FLAG_TO_IAR['ld_flags'])
def _ewp_flags_set(self, ewp_dic_subset, project_dic, flag_type, flag_dic):
""" Flags from misc to set to ewp project """
try:
if flag_type in project_dic['misc'].keys():
# enable commands
index_option = self._get_option(ewp_dic_subset, flag_dic['enable'])
self._set_option(ewp_dic_subset[index_option], '1')
index_option = self._get_option(ewp_dic_subset, flag_dic['set'])
if type(ewp_dic_subset[index_option]['state']) != list:
# if it's string, only one state
previous_state = ewp_dic_subset[index_option]['state']
ewp_dic_subset[index_option]['state'] = []
ewp_dic_subset[index_option]['state'].append(previous_state)
for item in project_dic['misc'][flag_type]:
ewp_dic_subset[index_option]['state'].append(item)
except KeyError:
return
def _ewp_files_set(self, ewp_dic, project_dic):
""" Fills files in the ewp dictionary """
# empty any files in the template which are not grouped
try:
ewp_dic['project']['file'] = []
except KeyError:
pass
# empty groups
ewp_dic['project']['group'] = []
i = 0
for group_name, files in project_dic['groups'].items():
ewp_dic['project']['group'].append({'name': group_name, 'file': []})
for file in files:
ewp_dic['project']['group'][i]['file'].append({'name': file})
ewp_dic['project']['group'][i]['file'] = sorted(ewp_dic['project']['group'][i]['file'], key=lambda x: os.path.basename(x['name'].lower()))
i += 1
def _clean_xmldict_option(self, dictionary):
""" xml parser puts None to empty fields, this functions replaces them with empty strings """
for option in dictionary['data']['option']:
if option['state'] is None:
option['state'] = ''
def _clean_xmldict_single_dic(self, dictionary):
""" Every None replace by '' in the dic, as xml parsers puts None in those fiels, which is not valid for IAR """
for k, v in dictionary.items():
if v is None:
dictionary[k] = ''
def _clean_xmldict_ewp(self, ewp_dic):
for setting in ewp_dic['settings']:
if setting['name'] == 'BICOMP' or setting['name'] == 'BILINK':
self._clean_xmldict_single_dic(setting)
elif setting['name'] == 'BUILDACTION' or setting['name'] == 'CUSTOM':
self._clean_xmldict_single_dic(setting['data'])
elif 'option' in setting['data']:
self._clean_xmldict_option(setting)
def _ewp_set_toolchain(self, ewp_dic, toolchain):
ewp_dic['toolchain']['name'] = toolchain
def _ewp_set_name(self, ewp_dic, name):
ewp_dic['name'] = name
def _ewd_set_name(self, ewd_dic, name):
ewd_dic['name'] = name
def _eww_set_path_single_project(self, eww_dic, name):
eww_dic['workspace']['project']['path'] = join('$WS_DIR$', name + '.ewp')
def _eww_set_path_multiple_project(self, eww_dic):
eww_dic['workspace']['project'] = []
for project in self.workspace['projects']:
# We check how far is project from root and workspace. IF they dont match,
# get relpath for project and inject it into workspace
path_project = os.path.dirname(project['files']['ewp'])
path_workspace = os.path.dirname(self.workspace['settings']['path'] + '\\')
destination = os.path.join(os.path.relpath(os.getcwd(), path_project), project['files']['ewp'])
if path_project != path_workspace:
destination = os.path.join(os.path.relpath(os.getcwd(), path_workspace), project['files']['ewp'])
eww_dic['workspace']['project'].append( { 'path' : join('$WS_DIR$', destination) })
def _ewp_set_target(self, ewp_dic, mcu_def_dic):
index_general = self._get_option(ewp_dic, 'General')
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'OGChipSelectEditMenu')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], mcu_def_dic['OGChipSelectEditMenu']['state'])
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'OGCoreOrChip')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], mcu_def_dic['OGCoreOrChip']['state'])
# get version based on FPU
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'FPU2')
if index_option == None:
fileVersion = 1
else:
fileVersion = 2
def _get_mcu_option(option):
try:
return mcu_def_dic[option]['state']
except KeyError:
return None
# Get variant
Variant = _get_mcu_option('Variant')
if not Variant:
Variant = _get_mcu_option('CoreVariant')
GFPUCoreSlave = _get_mcu_option('GFPUCoreSlave')
if not GFPUCoreSlave:
GFPUCoreSlave = _get_mcu_option('GFPUCoreSlave2')
GBECoreSlave = _get_mcu_option('GBECoreSlave')
if fileVersion == 1:
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'Variant')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], Variant)
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'GFPUCoreSlave')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], GFPUCoreSlave)
elif fileVersion == 2:
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'CoreVariant')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], Variant)
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'GFPUCoreSlave2')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], GFPUCoreSlave)
if GBECoreSlave:
index_option = self._get_option(ewp_dic[index_general]['data']['option'], 'GBECoreSlave')
self._set_option(ewp_dic[index_general]['data']['option'][index_option], mcu_def_dic['GBECoreSlave']['state'])
GFPUDeviceSlave = {
'state': mcu_def_dic['OGChipSelectEditMenu']['state'], # should be same
'name': 'GFPUDeviceSlave',
}
ewp_dic[index_general]['data']['option'].append(GFPUDeviceSlave)
def _ewd_set_debugger(self, ewd_dic, debugger):
try:
debugger_def = self.definitions.debuggers[debugger['name']]
except TypeError:
return
index_cspy = self._get_option(ewd_dic, 'C-SPY')
index_option = self._get_option(ewd_dic[index_cspy]['data']['option'], 'OCDynDriverList')
self._set_option(ewd_dic[index_cspy]['data']['option'][index_option], debugger_def['OCDynDriverList']['state'])
# find InterfaceRadio (jtag or swd)
try:
debugger_interface = self.definitions.debuggers[debugger['name']]['interface']
index_debugger_settings = self._get_option(ewd_dic, debugger_def['OCDynDriverList']['state'])
index_option = self._get_option(ewd_dic[index_debugger_settings]['data']['option'], debugger_interface['name'])
self._set_option(ewd_dic[index_debugger_settings]['data']['option'][index_option], debugger_def['interface'][debugger['interface']])
except TypeError as e:
# use default
pass
class IAREmbeddedWorkbench(Tool, Builder, Exporter, IAREmbeddedWorkbenchProject):
generated_project = {
'path': '',
'files': {
'ewp': '',
'ewd': '',
'eww': '',
}
}
def __init__(self, workspace, env_settings):
self.definitions = IARDefinitions()
self.workspace = workspace
self.env_settings = env_settings
self.ewp_file = join(self.TEMPLATE_DIR, "iar.ewp")
self.eww_file = join(self.TEMPLATE_DIR, "iar.eww")
self.ewd_file = join(self.TEMPLATE_DIR, "iar.ewd")
@staticmethod
def get_toolnames():
return ['iar_arm']
@staticmethod
def get_toolchain():
return 'iar'
def _normalize_mcu_def(self, mcu_def):
""" Normalizes mcu definitions to the required format """
# hack to insert tab as IAR using tab for MCU definitions
mcu_def['OGChipSelectEditMenu']['state'] = mcu_def['OGChipSelectEditMenu']['state'][0].replace(' ', '\t', 1)
mcu_def['OGCoreOrChip']['state'] = mcu_def['OGCoreOrChip']['state'][0]
def _fix_paths(self, data):
""" All paths needs to be fixed - add PROJ_DIR prefix + normalize """
data['include_paths'] = [join('$PROJ_DIR$', path) for path in data['include_paths']]
if data['linker_file']:
data['linker_file'] = join('$PROJ_DIR$', data['linker_file'])
data['groups'] = {}
for attribute in SOURCE_KEYS:
for k, v in data[attribute].items():
if k not in data['groups']:
data['groups'][k] = []
data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v])
for k,v in data['include_files'].items():
if k not in data['groups']:
data['groups'][k] = []
data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v])
# sort groups
data['groups'] = OrderedDict(sorted(data['groups'].items(), key=lambda t: t[0]))
def _get_default_templates(self):
ewp_dic = xmltodict.parse(open(self.ewp_file).read())
ewd_dic = xmltodict.parse(open(self.ewd_file).read())
return ewp_dic, ewd_dic
def _export_single_project(self):
""" A single project export """
expanded_dic = self.workspace.copy()
self._fix_paths(expanded_dic)
# generic tool template specified or project
if expanded_dic['template']:
template_ewp = False
template_ewd = False
# process each template file
for template in expanded_dic['template']:
template = join(getcwd(), template)
# we support .ewp or .ewp.tmpl templates
if os.path.splitext(template)[1] == '.ewp' or re.match('.*\.ewp.tmpl$', template):
try:
ewp_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewp = True
except IOError:
logger.info("Template file %s not found" % template)
ewp_dic = xmltodict.parse(open(self.ewp_file).read())
if os.path.splitext(template)[1] == '.ewd' or re.match('.*\.ewd.tmpl$', template):
try:
ewd_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewd = True
except IOError:
logger.info("Template file %s not found" % template)
ewd_dic = xmltodict.parse(open(self.ewd_file).read())
# handle non valid template files or not specified
if not template_ewp and template_ewd:
ewp_dic, _ = self._get_default_templates()
elif not template_ewd and template_ewp:
_, ewd_dic = self._get_default_templates()
else:
ewp_dic, ewd_dic = self._get_default_templates()
elif 'iar' in self.env_settings.templates.keys():
template_ewp = False
template_ewd = False
# template overrides what is set in the yaml files
for template in self.env_settings.templates['iar']:
template = join(getcwd(), template)
if os.path.splitext(template)[1] == '.ewp' or re.match('.*\.ewp.tmpl$', template):
try:
ewp_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewp = True
except IOError:
logger.info("Template file %s not found" % template)
ewp_dic = xmltodict.parse(open(self.ewp_file).read())
if os.path.splitext(template)[1] == '.ewd' or re.match('.*\.ewd.tmpl$', template):
# get ewd template
try:
ewd_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewd = True
except IOError:
logger.info("Template file %s not found" % template)
ewd_dic = xmltodict.parse(open(self.ewd_file).read())
# handle non valid template files or not specified
if not template_ewp and template_ewd:
ewp_dic, _ = self._get_default_templates()
elif not template_ewd and template_ewp:
_, ewd_dic = self._get_default_templates()
else:
ewp_dic, ewd_dic = self._get_default_templates()
else:
ewp_dic, ewd_dic = self._get_default_templates()
eww = None
if self.workspace['singular']:
# TODO 0xc0170: if we use here self.definitions.eww, travis fails. I cant reproduce it and dont see
# eww used anywhere prior to exporting this.
eww_dic = {u'workspace': {u'project': {u'path': u''}, u'batchBuild': None}}
# set eww
self._eww_set_path_single_project(eww_dic, expanded_dic['name'])
eww_xml = xmltodict.unparse(eww_dic, pretty=True)
project_path, eww = self.gen_file_raw(eww_xml, '%s.eww' % expanded_dic['name'], expanded_dic['output_dir']['path'])
try:
ewp_configuration = ewp_dic['project']['configuration'][0]
logging.debug("Provided .ewp file has multiple configuration, we use only the first one")
ewp_dic['project']['configuration'] = ewp_dic['project']['configuration'][0]
except KeyError:
ewp_configuration = ewp_dic['project']['configuration']
try:
ewp_configuration = ewp_dic['project']['configuration'][0]
logging.debug("Provided .ewp file has multiple configuration, we use only the first one")
ewp_dic['project']['configuration'] = ewp_dic['project']['configuration'][0]
except KeyError:
ewp_configuration = ewp_dic['project']['configuration']
# replace all None with empty strings ''
self._clean_xmldict_ewp(ewp_configuration)
#self._clean_xmldict_ewd(ewd_dic)
try:
self._ewp_set_name(ewp_configuration, expanded_dic['name'])
except KeyError:
raise RuntimeError("The IAR template is not valid .ewp file")
# set ARM toolchain and project name\
self._ewp_set_toolchain(ewp_configuration, 'ARM')
# set common things we have for IAR
self._ewp_general_set(ewp_configuration['settings'], expanded_dic)
self._ewp_iccarm_set(ewp_configuration['settings'], expanded_dic)
self._ewp_aarm_set(ewp_configuration['settings'], expanded_dic)
self._ewp_ilink_set(ewp_configuration['settings'], expanded_dic)
self._ewp_files_set(ewp_dic, expanded_dic)
# set target only if defined, otherwise use from template/default one
if expanded_dic['target']:
# get target definition (target + mcu)
proj_def = ProGenDef('iar')
if not proj_def.is_supported(expanded_dic['target'].lower()):
raise RuntimeError("Target %s is not supported." % expanded_dic['target'].lower())
mcu_def_dic = proj_def.get_tool_definition(expanded_dic['target'].lower())
if not mcu_def_dic:
raise RuntimeError(
"Mcu definitions were not found for %s. Please add them to https://github.com/project-generator/project_generator_definitions" % expanded_dic['target'].lower())
self._normalize_mcu_def(mcu_def_dic)
logger.debug("Mcu definitions: %s" % mcu_def_dic)
self._ewp_set_target(ewp_configuration['settings'], mcu_def_dic)
try:
debugger = proj_def.get_debugger(expanded_dic['target'])
self._ewd_set_debugger(ewd_dic['project']['configuration']['settings'], debugger)
except KeyError as err:
# TODO: worth reporting?
pass
# overwrite debugger only if defined in the project file, otherwise use either default or from template
if expanded_dic['debugger']:
try:
self._ewd_set_debugger(ewd_dic['project']['configuration']['settings'], expanded_dic['debugger'])
except KeyError:
raise RuntimeError("Debugger %s is not supported" % expanded_dic['debugger'])
self._ewd_set_name(ewd_dic['project']['configuration'], expanded_dic['name'])
# IAR uses ident 2 spaces, encoding iso-8859-1
ewp_xml = xmltodict.unparse(ewp_dic, encoding='iso-8859-1', pretty=True, indent=' ')
project_path, ewp = self.gen_file_raw(ewp_xml, '%s.ewp' % expanded_dic['name'], expanded_dic['output_dir']['path'])
ewd_xml = xmltodict.unparse(ewd_dic, encoding='iso-8859-1', pretty=True, indent=' ')
project_path, ewd = self.gen_file_raw(ewd_xml, '%s.ewd' % expanded_dic['name'], expanded_dic['output_dir']['path'])
return project_path, [ewp, eww, ewd]
def _generate_eww_file(self):
eww_dic = xmltodict.parse(open(self.eww_file).read())
self._eww_set_path_multiple_project(eww_dic)
# generate the file
eww_xml = xmltodict.unparse(eww_dic, pretty=True)
project_path, eww = self.gen_file_raw(eww_xml, '%s.eww' % self.workspace['settings']['name'], self.workspace['settings']['path'])
return project_path, [eww]
def _parse_subprocess_output(self, output):
num_errors = 0
lines = output.split("\n")
error_re = '\s*Total number of errors:\s*(\d+)\s*'
for line in lines:
m = re.match(error_re, line)
if m is not None:
num_errors = m.group(1)
return int(num_errors)
def export_workspace(self):
""" Export a workspace file """
# we got a workspace defined, therefore one ewp generated only
path, workspace = self._generate_eww_file()
return path, [workspace]
def export_project(self):
""" Processes groups and misc options specific for IAR, and run generator """
path, files = self._export_single_project()
generated_projects = copy.deepcopy(self.generated_project)
generated_projects['path'] = path
generated_projects['files']['ewp'] = files[0]
generated_projects['files']['eww'] = files[1]
generated_projects['files']['ewd'] = files[2]
return generated_projects
def build_project(self, **kwargs):
""" Build IAR project """
# > IarBuild [project_path] -build [project_name]
proj_path = join(getcwd(), self.workspace['files']['ewp'])
if proj_path.split('.')[-1] != 'ewp':
proj_path += '.ewp'
if not os.path.exists(proj_path):
logger.debug("The file: %s does not exists, exported prior building?" % proj_path)
return -1
logger.debug("Building IAR project: %s" % proj_path)
args = [join(self.env_settings.get_env_settings('iar'), 'IarBuild.exe'), proj_path, '-build', os.path.splitext(os.path.basename(self.workspace['files']['ewp']))[0]]
logger.debug(args)
try:
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
except:
logger.error("Project: %s build failed. Please check IARBUILD path in the user_settings.py file." % self.workspace['files']['ewp'])
return -1
else:
build_log_path = os.path.join(os.path.dirname(proj_path),'build_log.txt')
with open(build_log_path, 'w') as f:
f.write(output)
num_errors = self._parse_subprocess_output(output)
if num_errors == 0:
logger.info("Project: %s build completed." % self.workspace['files']['ewp'])
return 0
else:
logger.error("Project: %s build failed with %d errors" %
(self.workspace['files']['ewp'], num_errors))
return -1
def get_generated_project_files(self):
return {'path': self.workspace['path'], 'files': [self.workspace['files']['ewp'], self.workspace['files']['eww'],
self.workspace['files']['ewd']]}
|
qtproject/qtwebkit | refs/heads/dev | Source/JavaScriptCore/Scripts/builtins/builtins_generate_separate_implementation.py | 3 | #!/usr/bin/env python
#
# Copyright (c) 2014, 2015 Apple Inc. All rights reserved.
# Copyright (c) 2014 University of Washington. All rights reserved.
#
# 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
import logging
import re
import string
from string import Template
from builtins_generator import BuiltinsGenerator, WK_lcfirst
from builtins_model import Framework, Frameworks
from builtins_templates import BuiltinsGeneratorTemplates as Templates
log = logging.getLogger('global')
class BuiltinsSeparateImplementationGenerator(BuiltinsGenerator):
def __init__(self, model, object):
BuiltinsGenerator.__init__(self, model)
self.object = object
def output_filename(self):
return "%sBuiltins.cpp" % BuiltinsGenerator.mangledNameForObject(self.object)
def macro_prefix(self):
return self.model().framework.setting('macro_prefix')
def generate_output(self):
args = {
'namespace': self.model().framework.setting('namespace'),
'macroPrefix': self.macro_prefix(),
'objectMacro': self.object.object_name.upper(),
'objectNameLC': WK_lcfirst(self.object.object_name),
}
conditional_guard = self.object.annotations.get('conditional')
sections = []
sections.append(self.generate_license())
sections.append(Template(Templates.DoNotEditWarning).substitute(args))
sections.append(self.generate_primary_header_includes())
if conditional_guard is not None:
sections.append("#if %s" % conditional_guard)
sections.append(self.generate_secondary_header_includes())
sections.append(Template(Templates.NamespaceTop).substitute(args))
for function in self.object.functions:
sections.append(self.generate_embedded_code_string_section_for_function(function))
if self.model().framework is Frameworks.JavaScriptCore:
sections.append(Template(Templates.SeparateJSCImplementationStaticMacros).substitute(args))
elif self.model().framework is Frameworks.WebCore:
sections.append(Template(Templates.SeparateWebCoreImplementationStaticMacros).substitute(args))
sections.append(Template(Templates.NamespaceBottom).substitute(args))
if conditional_guard is not None:
sections.append("#endif // %s\n" % conditional_guard)
return "\n\n".join(sections)
def generate_secondary_header_includes(self):
header_includes = [
(["JavaScriptCore"],
("JavaScriptCore", "builtins/BuiltinExecutables.h"),
),
(["JavaScriptCore", "WebCore"],
("JavaScriptCore", "runtime/Executable.h"),
),
(["JavaScriptCore", "WebCore"],
("JavaScriptCore", "runtime/JSCellInlines.h"),
),
(["WebCore"],
("JavaScriptCore", "runtime/StructureInlines.h"),
),
(["WebCore"],
("JavaScriptCore", "runtime/JSCJSValueInlines.h"),
),
(["JavaScriptCore", "WebCore"],
("JavaScriptCore", "runtime/VM.h"),
),
(["WebCore"],
("WebCore", "bindings/js/WebCoreJSClientData.h"),
),
]
return '\n'.join(self.generate_includes_from_entries(header_includes))
|
optiminimalist/movingdata | refs/heads/master | deploy/ec2/__init__.py | 2 | """Handles EC2 communication via boto"""
__author__ = 'ml483'
|
stonebig/flexx | refs/heads/master | flexx/pyscript/parser3.py | 21 | """
Python Builtins
---------------
Most buildin functions (that make sense in JS) are automatically
translated to JavaScript: isinstance, issubclass, callable, hasattr,
getattr, setattr, delattr, print, len, max, min, chr, ord, dict, list,
tuple, range, pow, sum, round, int, float, str, bool, abs, divmod, all,
any, enumerate, zip, reversed, sorted, filter, map.
.. pyscript_example::
# "self" is replaced with "this"
self.foo
# Printing just works
print('some test')
print(a, b, c, sep='-')
# Getting the length of a string or array
len(foo)
# Rounding and abs
round(foo) # round to nearest integer
int(foo) # round towards 0 as in Python
abs(foo)
# min and max
min(foo)
min(a, b, c)
max(foo)
max(a, b, c)
# divmod
a, b = divmod(100, 7) # -> 14, 2
# Aggregation
sum(foo)
all(foo)
any(foo)
# Turning things into numbers, bools and strings
str(s)
float(x)
bool(y)
int(z) # this rounds towards zero like in Python
chr(65) # -> 'A'
ord('A') # -> 65
# Turning things into lists and dicts
dict([['foo', 1], ['bar', 2]]) # -> {'foo': 1, 'bar': 2}
list('abc') # -> ['a', 'b', 'c']
dict(other_dict) # make a copy
list(other_list) # make copy
The isinstance function (and friends)
-------------------------------------
The ``isinstance()`` function works for all JS primitive types, but also
for user-defined classes.
.. pyscript_example::
# Basic types
isinstance(3, float) # in JS there are no ints
isinstance('', str)
isinstance([], list)
isinstance({}, dict)
isinstance(foo, types.FunctionType)
# Can also use JS strings
isinstance(3, 'number')
isinstance('', 'string')
isinstance([], 'array')
isinstance({}, 'object')
isinstance(foo, 'function')
# You can use it on your own types too ...
isinstance(x, MyClass)
isinstance(x, 'MyClass') # equivalent
isinstance(x, 'Object') # also yields true (subclass of Object)
# issubclass works too
issubclass(Foo, Bar)
# As well as callable
callable(foo)
hasattr, getattr, setattr and delattr
-------------------------------------
.. pyscript_example::
a = {'foo': 1, 'bar': 2}
hasattr(a, 'foo') # -> True
hasattr(a, 'fooo') # -> False
hasattr(null, 'foo') # -> False
getattr(a, 'foo') # -> 1
getattr(a, 'fooo') # -> raise AttributeError
getattr(a, 'fooo', 3) # -> 3
getattr(null, 'foo', 3) # -> 3
setattr(a, 'foo', 2)
delattr(a, 'foo')
Creating sequences
------------------
.. pyscript_example::
range(10)
range(2, 10, 2)
range(100, 0, -1)
reversed(foo)
sorted(foo)
enumerate(foo)
zip(foo, bar)
filter(func, foo)
map(func, foo)
List methods
------------
.. pyscript_example::
# Call a.append() if it exists, otherwise a.push()
a.append(x)
# Similar for remove()
a.remove(x)
Dict methods
------------
.. pyscript_example::
a = {'foo': 3}
a['foo']
a.get('foo', 0)
a.get('foo')
a.keys()
Str methods
-----------
.. pyscript_example::
"foobar".startswith('foo')
Additional sugar
----------------
.. pyscript_example::
# Get time (number of seconds since epoch)
print(time.time())
# High resolution timer (as in time.perf_counter on Python 3)
t0 = time.perf_counter()
do_something()
t1 = time.perf_counter()
print('this took me', t1-t0, 'seconds')
"""
import ast
from .parser2 import Parser2, JSError, unify # noqa
# List of possibly relevant builtin functions:
#
# abs all any bin bool callable chr complex delattr dict dir divmod
# enumerate eval exec filter float format getattr globals hasattr hash
# hex id int isinstance issubclass iter len list locals map max min next
# object oct ord pow print property range repr reversed round set setattr
# slice sorted str sum super tuple type vars zip
#
# Further, all methods of: list, dict, str, set?
# todo: make these more robust by not applying the Python version if a JS version exists.
class Parser3(Parser2):
""" Parser to transcompile Python to JS, allowing more Pythonic
code, like ``self``, ``print()``, ``len()``, list methods, etc.
"""
NAME_MAP = {'self': 'this', }
NAME_MAP.update(Parser2.NAME_MAP)
## Hardcore functions (hide JS functions with the same name)
def function_isinstance(self, node):
if len(node.args) != 2:
raise JSError('isinstance() expects two arguments.')
ob = unify(self.parse(node.args[0]))
cls = unify(self.parse(node.args[1]))
if cls[0] in '"\'':
cls = cls[1:-1] # remove quotes
BASIC_TYPES = ('number', 'boolean', 'string', 'function', 'array',
'object', 'null', 'undefined')
MAP = {'[int, float]': 'number', '[float, int]': 'number', 'float': 'number',
'str': 'string', 'basestring': 'string', 'string_types': 'string',
'bool': 'boolean',
'FunctionType': 'function', 'types.FunctionType': 'function',
'list': 'array', 'tuple': 'array',
'[list, tuple]': 'array', '[tuple, list]': 'array',
'dict': 'object',
}
cmp = MAP.get(cls, cls)
if cmp.lower() in BASIC_TYPES:
# Basic type, use Object.prototype.toString
# http://stackoverflow.com/questions/11108877
return ["({}).toString.call(",
ob,
").match(/\s([a-zA-Z]+)/)[1].toLowerCase() === ",
repr(cmp.lower())
]
else:
# User defined type, use instanceof
# http://tobyho.com/2011/01/28/checking-types-in-javascript/
cmp = unify(cls)
if cmp[0] == '(':
raise JSError('isinstance() can only compare to simple types')
return ob, " instanceof ", cmp
def function_issubclass(self, node):
# issubclass only needs to work on custom classes
if len(node.args) != 2:
raise JSError('issubclass() expects two arguments.')
cls1 = unify(self.parse(node.args[0]))
cls2 = unify(self.parse(node.args[1]))
if cls2 == 'object':
cls2 = 'Object'
return '(%s.prototype instanceof %s)' % (cls1, cls2)
def function_hasattr(self, node):
if len(node.args) == 2:
ob = unify(self.parse(node.args[0]))
name = unify(self.parse(node.args[1]))
dummy1 = self.dummy()
t = "((%s=%s) !== undefined && %s !== null && %s[%s] !== undefined)"
return t % (dummy1, ob, dummy1, dummy1, name)
else:
raise JSError('hasattr() expects two arguments.')
def function_getattr(self, node):
is_ok = "(ob !== undefined && ob !== null && ob[name] !== undefined)"
if len(node.args) == 2:
ob = unify(self.parse(node.args[0]))
name = unify(self.parse(node.args[1]))
func = "(function (ob, name) {if %s {return ob[name];} " % is_ok
func += "else {var e = Error(name); e.name='AttributeError'; throw e;}})"
return func + '(%s, %s)' % (ob, name)
elif len(node.args) == 3:
ob = unify(self.parse(node.args[0]))
name = unify(self.parse(node.args[1]))
default = unify(self.parse(node.args[2]))
func = "(function (ob, name, dflt) {if %s {return ob[name];} " % is_ok
func += "else {return dflt;}})"
return func + '(%s, %s, %s)' % (ob, name, default)
else:
raise JSError('hasattr() expects two or three arguments.')
def function_setattr(self, node):
is_ok = "(ob !== undefined && ob !== null && ob[name] !== undefined)"
if len(node.args) == 3:
ob = unify(self.parse(node.args[0]))
name = unify(self.parse(node.args[1]))
value = unify(self.parse(node.args[2]))
return '%s[%s] = %s' % (ob, name, value)
else:
raise JSError('setattr() expects three arguments.')
def function_delattr(self, node):
if len(node.args) == 2:
ob = unify(self.parse(node.args[0]))
name = unify(self.parse(node.args[1]))
return 'delete %s[%s]' % (ob, name)
else:
raise JSError('delattr() expects two arguments.')
def function_print(self, node):
# Process keywords
sep, end = '" "', ''
for kw in node.keywords:
if kw.arg == 'sep':
sep = ''.join(self.parse(kw.value))
elif kw.arg == 'end':
end = ''.join(self.parse(kw.value))
elif kw.arg in ('file', 'flush'):
raise JSError('print() file and flush args not supported')
else:
raise JSError('Invalid argument for print(): %r' % kw.arg)
# Combine args
args = [unify(self.parse(arg)) for arg in node.args]
end = (" + %s" % end) if (args and end and end != '\n') else ''
combiner = ' + %s + ' % sep
args_concat = combiner.join(args)
return 'console.log(' + args_concat + end + ')'
def function_len(self, node):
if len(node.args) == 1:
return unify(self.parse(node.args[0])), '.length'
else:
return None # don't apply this feature
def function_max(self, node):
if len(node.args) == 0:
raise JSError('max() needs at least one argument')
elif len(node.args) == 1:
arg = ''.join(self.parse(node.args[0]))
return 'Math.max.apply(null, ', arg, ')'
else:
args = ', '.join([unify(self.parse(arg)) for arg in node.args])
return 'Math.max(', args, ')'
def function_min(self, node):
if len(node.args) == 0:
raise JSError('min() needs at least one argument')
elif len(node.args) == 1:
arg = ''.join(self.parse(node.args[0]))
return 'Math.min.apply(null, ', arg, ')'
else:
args = ', '.join([unify(self.parse(arg)) for arg in node.args])
return 'Math.min(', args, ')'
def function_callable(self, node):
if len(node.args) == 1:
arg = unify(self.parse(node.args[0]))
return '(typeof %s === "function")' % arg
else:
raise JSError('callable() needs at least one argument')
def function_chr(self, node):
if len(node.args) == 1:
arg = ''.join(self.parse(node.args[0]))
return 'String.fromCharCode(%s)' % arg
else:
raise JSError('chr() needs at least one argument')
def function_ord(self, node):
if len(node.args) == 1:
arg = ''.join(self.parse(node.args[0]))
return '%s.charCodeAt(0)' % arg
else:
raise JSError('ord() needs at least one argument')
def function_dict(self, node):
if len(node.args) == 0:
return '{}'
if len(node.args) == 1:
code = '(function(x) {var t, i, keys, r={};'
code += 'if (Array.isArray(x)) {'
code += 'for (i=0; i<x.length; i++) {t=x[i]; r[t[0]] = t[1];} return r;'
code += '} else {'
code += 'keys = Object.keys(x); for (i=0; i<keys.length; i++) {t=keys[i]; r[t] = x[t];} return r;}})'
return code + '(%s)' % ''.join(self.parse(node.args[0]))
else:
raise JSError('dict() needs at least one argument')
def function_list(self, node):
if len(node.args) == 0:
return '[]'
if len(node.args) == 1:
code = '(function(x) {var r=[];'
code += 'if (typeof x==="object" && !Array.isArray(x)) {x=Object.keys(x)}'
code += 'for (var i=0; i<x.length; i++) {r.push(x[i]);} return r;})'
return code + '(%s)' % ''.join(self.parse(node.args[0]))
else:
raise JSError('list() needs at least one argument')
def function_tuple(self, node):
return self.function_list(node)
def function_range(self, node):
fun = 'function (start, end, step) {var i, res = []; for (i=start; i<end; i+=step) {res.push(i);} return res;}'
if len(node.args) == 1:
end = unify(self.parse(node.args[0]))
return '(%s)(0, %s, 1)' % (fun, end)
elif len(node.args) == 2:
start = unify(self.parse(node.args[0]))
end = unify(self.parse(node.args[1]))
return '(%s)(%s, %s, 1)' % (fun, start, end)
elif len(node.args) == 3:
start = unify(self.parse(node.args[0]))
end = unify(self.parse(node.args[1]))
step = ''.join(self.parse(node.args[2]))
if step.lstrip('+-').isnumeric() and float(step) < 0:
fun = fun.replace('<', '>')
return '(%s)(%s, %s, %s)' % (fun, start, end, step)
else:
raise JSError('range() needs 1, 2 or 3 arguments')
## Normal functions (can be overloaded)
def function_pow(self, node):
if len(node.args) == 2:
self.vars_for_functions['pow'] = 'Math.pow'
return None
else:
raise JSError('pow() needs exactly two argument2')
def function_sum(self, node):
if len(node.args) == 1:
code = 'function (x) {return x.reduce(function(a, b) {return a + b;});}'
self.vars_for_functions['sum'] = code
return None
else:
raise JSError('sum() needs exactly one argument')
def function_round(self, node):
if len(node.args) == 1:
self.vars_for_functions['round'] = 'Math.round'
else:
raise JSError('round() needs at least one argument')
def function_int(self, node):
# No need to turn into number first
if len(node.args) == 1:
code = 'function (x) {return x<0 ? Math.ceil(x): Math.floor(x);}'
self.vars_for_functions['int'] = code
else:
raise JSError('int() needs one argument')
def function_float(self, node):
if len(node.args) == 1:
self.vars_for_functions['float'] = 'Number'
else:
raise JSError('float() needs one argument')
def function_str(self, node):
if len(node.args) in (0, 1):
self.vars_for_functions['str'] = 'String'
else:
raise JSError('str() needs zero or one argument')
def function_repr(self, node):
if len(node.args) == 1:
# code = 'function (x) {if (typeof x === "object") {return JSON.stringify(x);}'
# code += ' else if (typeof x === "string") {return "\'" + x + "\'";}'
# code += ' else {return x.toString();}}'
self.vars_for_functions['repr'] = 'JSON.stringify'
else:
raise JSError('repr() needs one argument')
def function_bool(self, node):
if len(node.args) == 1:
self._wrap_truthy(ast.Name('x', '')) # trigger _truthy function declaration
self.vars_for_functions['bool'] = 'function (x) {return Boolean(_truthy(x));}'
else:
raise JSError('bool() needs one argument')
def function_abs(self, node):
if len(node.args) == 1:
self.vars_for_functions['abs'] = 'Math.abs'
else:
raise JSError('abs() needs one argument')
def function_divmod(self, node):
if len(node.args) == 2:
code = 'function (x, y) {var m = x % y; return [(x-m)/y, m];}'
self.vars_for_functions['divmod'] = code
else:
raise JSError('divmod() needs two arguments')
def function_all(self, node):
if len(node.args) == 1:
self._wrap_truthy(ast.Name('x', '')) # trigger _truthy function declaration
code = 'function (x) {for (var i=0; i<x.length; i++) {if (!_truthy(x[i])){return false}} return true;}'
self.vars_for_functions['all'] = code
else:
raise JSError('all() needs one argument')
def function_any(self, node):
if len(node.args) == 1:
self._wrap_truthy(ast.Name('x', '')) # trigger _truthy function declaration
code = 'function (x) {for (var i=0; i<x.length; i++) {if (_truthy(x[i])){return true}} return false;}'
self.vars_for_functions['any'] = code
else:
raise JSError('any() needs one argument')
def function_enumerate(self, node):
if len(node.args) == 1:
code = 'function (iter) { var i, res=[];'
code += self._make_iterable('iter', 'iter', False)
code += 'for (i=0; i<iter.length; i++) {res.push([i, iter[i]]);}'
code += 'return res;}'
self.vars_for_functions['enumerate'] = code
else:
raise JSError('enumerate() needs one argument')
def function_zip(self, node):
if len(node.args) == 2:
code = 'function (iter1, iter2) { var i, res=[];'
code += self._make_iterable('iter1', 'iter1', False)
code += self._make_iterable('iter2', 'iter2', False)
code += 'var len = Math.min(iter1.length, iter2.length);'
code += 'for (i=0; i<len; i++) {res.push([iter1[i], iter2[i]]);}'
code += 'return res;}'
self.vars_for_functions['zip'] = code
else:
raise JSError('zip() needs two arguments')
def function_reversed(self, node):
if len(node.args) == 1:
code = 'function (iter) {'
code += self._make_iterable('iter', 'iter', False)
code += 'return iter.slice().reverse();}'
self.vars_for_functions['reversed'] = code
else:
raise JSError('reversed() needs one argument')
def function_sorted(self, node):
if len(node.args) == 1:
code = 'function (iter) {'
code += self._make_iterable('iter', 'iter', False)
code += 'return iter.slice().sort();}'
self.vars_for_functions['sorted'] = code
else:
raise JSError('sorted() needs one argument')
def function_filter(self, node):
if len(node.args) == 2:
code = 'function (func, iter) {'
code += 'if (typeof func === "undefined" || func === null) {func = function(x) {return x;}}'
code += 'return iter.filter(func);}'
self.vars_for_functions['filter'] = code
else:
raise JSError('filter() needs two arguments')
def function_map(self, node):
if len(node.args) == 2:
code = 'function (func, iter) {return iter.map(func);}'
self.vars_for_functions['map'] = code
else:
raise JSError('map() needs two arguments')
## List methods
def method_append(self, node, base):
if len(node.args) == 1:
code = []
code.append('(%s.append || %s.push).apply(%s, [' % (base, base, base))
code += self.parse(node.args[0])
code.append('])')
return code
def method_remove(self, node, base):
if len(node.args) == 1:
code = []
remove_func = 'function (x) {this.splice(this.indexOf(x), 1);}'
code.append('(%s.remove || %s).apply(%s, [' % (base, remove_func, base))
code += self.parse(node.args[0])
code.append('])')
return code
## Dict methods
def method_get(self, node, base):
if len(node.args) in (1, 2):
# Get name to call object - use simple name if we can
ob_name = base
ob_name1 = base
if not base.isalnum():
dummy = self.dummy()
ob_name = dummy
ob_name1 = '(%s=%s)' % (dummy, base)
# Get args
key = unify(self.parse(node.args[0]))
default = 'null'
normal_args = ''.join(self.parse(node.args[0]))
if len(node.args) == 2:
default = unify(self.parse(node.args[1]))
normal_args += ', ' + ''.join(self.parse(node.args[1]))
# Compose
dict_get = '(%s[%s] || %s)' % (ob_name, key, default)
normal_get = '%s.get(%s)' % (ob_name, normal_args)
return '(/*py-dict.get*/typeof %s.get==="function" ? %s : %s)' % (
ob_name1, normal_get, dict_get)
def method_keys(self, node, base):
if len(node.args) == 0:
return 'Object.keys(%s)' % base
## Str methods
def method_startswith(self, node, base):
if len(node.args) == 1:
arg = unify(self.parse(node.args[0]))
return unify(base), '.indexOf(', arg, ') == 0'
## Extra functions / methods
def method_time(self, node, base): # time.time()
if base == 'time':
if len(node.args) == 0:
return '((new Date()).getTime() / 1000)'
else:
raise JSError('time() needs no argument')
def method_perf_counter(self, node, base): # time.perf_counter()
if base == 'time':
if len(node.args) == 0:
# Work in nodejs and browser
dummy = self.dummy()
return '(typeof(process) === "undefined" ? performance.now()*1e-3 : ((%s=process.hrtime())[0] + %s[1]*1e-9))' % (dummy, dummy)
else:
raise JSError('perf_counter() needs no argument')
|
StefanDuan/IntroToComSci | refs/heads/master | ps1a_3.py | 2 | __author__ = 'wnduan'
# Problem Set 1-a From: MIT OPEN COURSEWARE
# Write a program computes and prints 1000th prime number.
# 1. Initialize some state variables:
i = 1 # ith prime number, the program started from 2nd prime number 3.(the 1st one is 2)
n = 1 # generates odd integers
maxI = 2000 #
p = [2,]
total_steps = 0
# def is_prime(n):
# for i in range(2,n):
# if n%i == 0:
# return False
# return True
# 2. Generate all (odd) integers > 1 as candidates to be prime
while i < maxI:
n += 2
is_prime = True
# 3. For each candidate test wether it's prime:
for j in p:
total_steps += 1
if n%j == 0:
is_prime = False
break
if is_prime:
i += 1 # the program started from 2nd prime number 3.(the 1st one is 2)
p.append(n)
# print '{:d} is the {:d}th prime'.format(n,i)
# 3. Print the results:
print '{:d} is the {:d}th prime'.format(n,i)
print 'total step: {}'.format(total_steps)
# print is_prime(2), 2
# print is_prime(3), 3
# print is_prime(9), 9
|
macks22/scikit-learn | refs/heads/master | benchmarks/bench_plot_fastkmeans.py | 294 | from __future__ import print_function
from collections import defaultdict
from time import time
import numpy as np
from numpy import random as nr
from sklearn.cluster.k_means_ import KMeans, MiniBatchKMeans
def compute_bench(samples_range, features_range):
it = 0
results = defaultdict(lambda: [])
chunk = 100
max_it = len(samples_range) * len(features_range)
for n_samples in samples_range:
for n_features in features_range:
it += 1
print('==============================')
print('Iteration %03d of %03d' % (it, max_it))
print('==============================')
print()
data = nr.random_integers(-50, 50, (n_samples, n_features))
print('K-Means')
tstart = time()
kmeans = KMeans(init='k-means++', n_clusters=10).fit(data)
delta = time() - tstart
print("Speed: %0.3fs" % delta)
print("Inertia: %0.5f" % kmeans.inertia_)
print()
results['kmeans_speed'].append(delta)
results['kmeans_quality'].append(kmeans.inertia_)
print('Fast K-Means')
# let's prepare the data in small chunks
mbkmeans = MiniBatchKMeans(init='k-means++',
n_clusters=10,
batch_size=chunk)
tstart = time()
mbkmeans.fit(data)
delta = time() - tstart
print("Speed: %0.3fs" % delta)
print("Inertia: %f" % mbkmeans.inertia_)
print()
print()
results['MiniBatchKMeans Speed'].append(delta)
results['MiniBatchKMeans Quality'].append(mbkmeans.inertia_)
return results
def compute_bench_2(chunks):
results = defaultdict(lambda: [])
n_features = 50000
means = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1],
[0.5, 0.5], [0.75, -0.5], [-1, 0.75], [1, 0]])
X = np.empty((0, 2))
for i in range(8):
X = np.r_[X, means[i] + 0.8 * np.random.randn(n_features, 2)]
max_it = len(chunks)
it = 0
for chunk in chunks:
it += 1
print('==============================')
print('Iteration %03d of %03d' % (it, max_it))
print('==============================')
print()
print('Fast K-Means')
tstart = time()
mbkmeans = MiniBatchKMeans(init='k-means++',
n_clusters=8,
batch_size=chunk)
mbkmeans.fit(X)
delta = time() - tstart
print("Speed: %0.3fs" % delta)
print("Inertia: %0.3fs" % mbkmeans.inertia_)
print()
results['MiniBatchKMeans Speed'].append(delta)
results['MiniBatchKMeans Quality'].append(mbkmeans.inertia_)
return results
if __name__ == '__main__':
from mpl_toolkits.mplot3d import axes3d # register the 3d projection
import matplotlib.pyplot as plt
samples_range = np.linspace(50, 150, 5).astype(np.int)
features_range = np.linspace(150, 50000, 5).astype(np.int)
chunks = np.linspace(500, 10000, 15).astype(np.int)
results = compute_bench(samples_range, features_range)
results_2 = compute_bench_2(chunks)
max_time = max([max(i) for i in [t for (label, t) in results.iteritems()
if "speed" in label]])
max_inertia = max([max(i) for i in [
t for (label, t) in results.iteritems()
if "speed" not in label]])
fig = plt.figure('scikit-learn K-Means benchmark results')
for c, (label, timings) in zip('brcy',
sorted(results.iteritems())):
if 'speed' in label:
ax = fig.add_subplot(2, 2, 1, projection='3d')
ax.set_zlim3d(0.0, max_time * 1.1)
else:
ax = fig.add_subplot(2, 2, 2, projection='3d')
ax.set_zlim3d(0.0, max_inertia * 1.1)
X, Y = np.meshgrid(samples_range, features_range)
Z = np.asarray(timings).reshape(samples_range.shape[0],
features_range.shape[0])
ax.plot_surface(X, Y, Z.T, cstride=1, rstride=1, color=c, alpha=0.5)
ax.set_xlabel('n_samples')
ax.set_ylabel('n_features')
i = 0
for c, (label, timings) in zip('br',
sorted(results_2.iteritems())):
i += 1
ax = fig.add_subplot(2, 2, i + 2)
y = np.asarray(timings)
ax.plot(chunks, y, color=c, alpha=0.8)
ax.set_xlabel('Chunks')
ax.set_ylabel(label)
plt.show()
|
chetan51/neon | refs/heads/master | neon/backends/float_ew.py | 10 | # ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems 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.
# ----------------------------------------------------------------------------
"""
Floating point elementwise operations on GPU.
"""
import os.path
import re
import traceback as tb
import numpy as np
from pycuda.compiler import SourceModule
from pycuda.tools import context_dependent_memoize
from pytools import memoize
# from pytools import memoize_method
# import pycuda.driver as drv # commented for stylecheck
import neon.backends.nervanagpu as ng
# RAND_POOL_SIZE set to 65536 == 2048 * 32
_ew_template = r"""
#define FLT_MAX 3.402823466E+38F
#define RAND_POOL_SIZE 65536
%(common)s
#define THREADS %(threads)s
__global__ void %(name)s (
unsigned* rand_state,
%(arguments)s)
{
const int tid = threadIdx.x;
const int bid = blockIdx.x;
extern __shared__ float sPartials[];
%(inits)s
"""
_stage_template = {
"loop": r"""
for (int i = tid; i < n{0}; i += THREADS)
{{
%(loads{0})s
%(ops{0})s
}}
""",
"red32": r"""
#pragma unroll
for (int i = 16; i > 0; i >>= 1)
{{
%(shfl_red{0})s
}}
""",
"red": r"""
sPartials[tid] = %(var_red{0})s;
__syncthreads();
#pragma unroll
for (int a = THREADS >> 1; a > 32; a >>= 1)
{{
if ( tid < a )
%(share1_red{0})s
__syncthreads();
}}
if ( tid < 32 )
{{
%(share2_red{0})s
#pragma unroll
for (int i = 16; i > 0; i >>= 1)
%(shfl_red{0})s
sPartials[tid] = %(var_red{0})s;
}}
__syncthreads();
%(var_red{0})s = sPartials[0];
""",
"red_ops": r"""
%(ops{0})s
""",
"red_out": r"""
if ( tid == 0 )
{{
%(ops{0})s
}}
"""
}
_fin_template = r"""
%(finish)s
}
"""
_init_rand_func = r"""
unsigned lfsr0, lfsr1, lfsr2;
unsigned idx = bid * THREADS + tid;
rand_state += idx % RAND_POOL_SIZE;
lfsr0 = *(rand_state + 0*RAND_POOL_SIZE);
lfsr1 = *(rand_state + 1*RAND_POOL_SIZE);
lfsr2 = *(rand_state + 2*RAND_POOL_SIZE);
"""
_init_rand_round_func = r"""
int i_rand_scale = (127 - 32 - mantissa_bits) << 23;
float rand_scale = *(float*)&i_rand_scale;
unsigned rand_mask = 0xffffffff << (23 - mantissa_bits);
"""
_finish_rand_func = r"""
*(rand_state + 0*RAND_POOL_SIZE) = lfsr0;
*(rand_state + 1*RAND_POOL_SIZE) = lfsr1;
*(rand_state + 2*RAND_POOL_SIZE) = lfsr2;
"""
_common_urand_gen = r"""
__device__ unsigned urand_gen(unsigned& lfsr0, unsigned& lfsr1, unsigned& lfsr2)
{
lfsr0 = ((lfsr0 & 0xfffffffe) << 12) ^ (((lfsr0 << 13) ^ lfsr0) >> 19);
lfsr1 = ((lfsr1 & 0xfffffff8) << 4) ^ (((lfsr1 << 2) ^ lfsr1) >> 25);
lfsr2 = ((lfsr2 & 0xfffffff0) << 11) ^ (((lfsr2 << 3) ^ lfsr2) >> 11);
return lfsr0 ^ lfsr1 ^ lfsr2;
}
"""
_common_frand = r"""
__device__ __forceinline__ float frand(unsigned& lfsr0, unsigned& lfsr1, unsigned& lfsr2)
{
unsigned urand = urand_gen(lfsr0, lfsr1, lfsr2);
float val;
asm("cvt.rn.f32.u32 %0, %1;\n\t"
"mul.f32 %0, %0, 0F2f800000;"
: "=f"(val) : "r"(urand));
return val;
}
"""
_common_round = {
"random": {
"f4": r"""
__device__ float fp32_to_fp32_rand(
float val, unsigned& lfsr0, unsigned& lfsr1, unsigned& lfsr2, float rand_scale,
unsigned rand_mask)
{
unsigned urand = urand_gen(lfsr0, lfsr1, lfsr2);
float ret;
asm("{\n\t"
".reg .f32 exponent, frand, result;\n\t"
"and.b32 exponent, %1, 0xff800000;\n\t"
"mul.f32 exponent, exponent, %2;\n\t"
"cvt.rz.f32.u32 frand, %3;\n\t"
"fma.rz.f32 result, exponent, frand, %1;\n\t"
"and.b32 %0, result, %4;\n\t"
"}" : "=f"(ret) : "f"(val), "f"(rand_scale), "r"(urand), "r"(rand_mask));
return ret;
}
""",
"f2": r"""
__device__ unsigned short fp32_to_fp16_rand(
float val, unsigned& lfsr0, unsigned& lfsr1, unsigned& lfsr2, float rand_scale,
unsigned rand_mask)
{
unsigned urand = urand_gen(lfsr0, lfsr1, lfsr2);
unsigned short half;
asm("{\n\t"
".reg .f16 result16;\n\t"
".reg .f32 exponent, frand, result32;\n\t"
"and.b32 exponent, %1, 0xff800000;\n\t"
"mul.f32 exponent, exponent, %2;\n\t"
"cvt.rz.f32.u32 frand, %3;\n\t"
"fma.rz.f32 result32, exponent, frand, %1;\n\t"
"and.b32 result32, result32, %4;\n\t"
"cvt.rz.f16.f32 result16, result32;\n\t"
"mov.b16 %0, result16;\n\t"
"}" : "=h"(half) : "f"(val), "f"(rand_scale), "r"(urand), "r"(rand_mask));
return half;
}
""",
"i4": r"""
__device__ __forceinline__ int fp32_to_int32_rand(
float val, unsigned& lfsr0, unsigned& lfsr1, unsigned& lfsr2)
{
unsigned urand = urand_gen(lfsr0, lfsr1, lfsr2);
int ret;
asm("{\n\t"
".reg .f32 frand, result32;\n\t"
"cvt.rz.f32.u32 frand, %2;\n\t"
"copysign.f32 frand, %1, frand;\n\t"
"mul.rz.f32 frand, frand, 0F2f800000;\n\t"
"add.rz.f32 result32, frand, %1;\n\t"
"cvt.rzi.s32.f32 %0, result32;\n\t"
"}" : "=r"(ret) : "f"(val), "r"(urand));
return ret;
}
""",
"i2": r"""
__device__ __forceinline__ short fp32_to_int16_rand(
float val, unsigned& lfsr0, unsigned& lfsr1, unsigned& lfsr2)
{
unsigned urand = urand_gen(lfsr0, lfsr1, lfsr2);
short half;
asm("{\n\t"
".reg .f32 frand, result32;\n\t"
"cvt.rz.f32.u32 frand, %2;\n\t"
"copysign.f32 frand, %1, frand;\n\t"
"mul.rz.f32 frand, frand, 0F2f800000;\n\t"
"add.rz.f32 result32, frand, %1;\n\t"
"cvt.rzi.s16.f32 %0, result32;\n\t"
"}" : "=h"(half) : "f"(val), "r"(urand));
return half;
}
""",
"i1": r"""
__device__ __forceinline__ char fp32_to_int8_rand(
float val, unsigned& lfsr0, unsigned& lfsr1, unsigned& lfsr2)
{
unsigned urand = urand_gen(lfsr0, lfsr1, lfsr2);
int ret;
asm("{\n\t"
".reg .f32 frand, result32;\n\t"
"cvt.rz.f32.u32 frand, %2;\n\t"
"copysign.f32 frand, %1, frand;\n\t"
"mul.rz.f32 frand, frand, 0F2f800000;\n\t"
"add.rz.f32 result32, frand, %1;\n\t"
"cvt.rzi.s8.f32 %0, result32;\n\t"
"}" : "=r"(ret) : "f"(val), "r"(urand));
return ret;
}
""",
},
"nearest": {
"f2": r"""
__device__ __forceinline__ unsigned short fp32_to_fp16(float val)
{
unsigned short ret;
asm("{\n\t"
".reg .f16 f16;\n\t"
"cvt.rn.f16.f32 f16, %1;"
"mov.b16 %0, f16;\n\t"
"}" : "=h"(ret) : "f"(val));
return ret;
}
""",
"i4": r"""
__device__ __forceinline__ int fp32_to_int32(float val)
{
int ret;
asm("cvt.rni.s32.f32 %0, %1;" : "=r"(ret) : "f"(val));
return ret;
}
""",
"u4": r"""
__device__ __forceinline__ unsigned fp32_to_uint32(float val)
{
unsigned ret;
asm("cvt.rni.u32.f32 %0, %1;" : "=r"(ret) : "f"(val));
return ret;
}
""",
"i2": r"""
__device__ __forceinline__ short fp32_to_int16(float val)
{
short ret;
asm("cvt.rni.s16.f32 %0, %1;" : "=h"(ret) : "f"(val));
return ret;
}
""",
"u2": r"""
__device__ __forceinline__ unsigned short fp32_to_uint16(float val)
{
unsigned short;
asm("cvt.rni.u16.f32 %0, %1;" : "=h"(ret) : "f"(val));
return ret;
}
""",
"i1": r"""
__device__ __forceinline__ char fp32_to_int8(float val)
{
int ret;
asm("cvt.rni.s8.f32 %0, %1;" : "=r"(ret) : "f"(val));
return ret;
}
""",
"u1": r"""
__device__ __forceinline__ unsigned char fp32_to_uint8(float val)
{
unsigned ret;
asm("cvt.rni.u8.f32 %0, %1;" : "=r"(ret) : "f"(val));
return ret;
}
""",
},
}
# random rounding not yet used for these types
for dtype in ("u4", "u2", "u1"):
_common_round["random"][dtype] = _common_round["nearest"][dtype]
_common_fp16_to_fp32 = r"""
__device__ __forceinline__ float fp16_to_fp32(unsigned short val)
{
float ret;
asm("{\n\t"
".reg .f16 f16;\n\t"
"mov.b16 f16, %1;\n\t"
"cvt.f32.f16 %0, f16;"
"}" : "=f"(ret) : "h"(val));
return ret;
}
"""
_ew_types = {
"f4": {
"type": "float",
"cvt": "",
},
"f2": {
"type": "unsigned short",
"cvt": "fp16_to_fp32",
},
"i4": {
"type": "int",
"cvt": "(float)",
},
"u4": {
"type": "unsigned int",
"cvt": "(float)",
},
"i2": {
"type": "short",
"cvt": "(float)",
},
"u2": {
"type": "unsigned short",
"cvt": "(float)",
},
"i1": {
"type": "char",
"cvt": "(float)",
},
"u1": {
"type": "unsigned char",
"cvt": "(float)",
},
}
_ew_strings = {
# 0: arg_id, 1: stage, 2: type, 3: cvt
"in0": {
"arguments": "const {2}* a{0}_in, int row_strd{0}, int col_strd{0}",
"inits": "const {2}* a{0}_in{1} = a{0}_in + bid * row_strd{0} + tid * col_strd{0};\n"
" int a{0}_inc{1} = THREADS * col_strd{0};",
"loads": "float a{0} = {3}(__ldg(a{0}_in{1}));\n"
" a{0}_in{1} += a{0}_inc{1};",
},
"in1": {
"arguments": "const {2}* a{0}_in, int row_strd{0}, int col_strd{0}, const int* take{0}_in",
"inits": """const {2}* a{0}_in{1} = a{0}_in + __ldg(take{0}_in + bid) * row_strd{0}
+ tid * col_strd{0};\n"""
" int a{0}_inc{1} = THREADS * col_strd{0};",
"loads": "float a{0} = {3}(__ldg(a{0}_in{1}));\n"
" a{0}_in{1} += a{0}_inc{1};",
},
"in2": {
"arguments": "const {2}* a{0}_in, int row_strd{0}, int col_strd{0}, const int* take{0}_in",
"inits": "const {2}* a{0}_in{1} = a{0}_in + bid * row_strd{0};\n"
" const int* take{0}_in{1} = take{0}_in + tid;",
"loads": "float a{0} = {3}(__ldg(a{0}_in{1} + __ldg(take{0}_in{1})));\n"
" take{0}_in{1} += THREADS;",
},
"out0": {
"arguments": "{2}* a_out, int row_strd, int col_strd",
"inits": "a_out += bid * row_strd + tid * col_strd;\n"
" int out_inc = THREADS * col_strd;",
"output": "*a_out = {0};\n a_out += out_inc;",
},
"out1": {
"arguments": "{2}* a_out, int row_strd, int col_strd, const int* take_out",
"inits": "a_out += __ldg(take_out + bid) * row_strd + tid * col_strd;\n"
" int out_inc = THREADS * col_strd;",
"output": "*a_out = {0};\n a_out += out_inc;",
},
"out2": {
"arguments": "{2}* a_out, int row_strd, int col_strd, const int* take_out",
"inits": "a_out += bid * row_strd;\n"
" take_out += tid;",
"output": "*(a_out + __ldg(take_out)) = {0};\n take_out += THREADS;",
},
"onehot0": {
"arguments": "const int* onehot{0}_in",
"inits": "onehot{0}_in += tid;",
"loads": "int onehot{0} = __ldg(onehot{0}_in);\n"
" onehot{0}_in += THREADS;",
},
"onehot1": {
"arguments": "const int* onehot{0}_in",
"inits": "int onehot{0} = __ldg(onehot{0}_in + bid);\n",
"loads": "",
},
"const": {
"arguments": "float c{0}",
},
"round": {
"random": {
"f4": """float {0} = fp32_to_fp32_rand({1}, lfsr0, lfsr1,
lfsr2, rand_scale, rand_mask);""",
"f2": """unsigned short {0} = fp32_to_fp16_rand({1}, lfsr0, lfsr1,
lfsr2, rand_scale, rand_mask);""",
"u4": "unsigned int {0} = fp32_to_uint32({1});",
"u2": "unsigned short {0} = fp32_to_uint16({1});",
"u1": "unsigned char {0} = fp32_to_uint8({1});",
"i4": "int {0} = fp32_to_int32_rand({1});",
"i2": "short {0} = fp32_to_int16_rand({1});",
"i1": "char {0} = fp32_to_int8_rand({1});",
},
"nearest": {
"f2": "unsigned short {0} = fp32_to_fp16({1});",
"u4": "unsignedint {0} = fp32_to_uint32({1});",
"u2": "unsigned short {0} = fp32_to_uint16({1});",
"u1": "unsigned char {0} = fp32_to_uint8({1});",
"i4": "int {0} = fp32_to_int32({1});",
"i2": "short {0} = fp32_to_int16({1});",
"i1": "char {0} = fp32_to_int8({1});",
},
},
}
_is_finite = r"""
float {0};
asm("{{\n\t"
".reg .pred is_finite;\n\t"
"testp.finite.f32 is_finite, %1;\n\t"
"selp.f32 %0, 0F3f800000, 0F00000000, is_finite;\n\t"
"}}" : "=f"({0}) : "f"({1}));
"""
# Note: binary operands come off the stack in reverse order
_float_ops = {
"assign": (2, "unused"),
"add": (2, 'float {0} = {2} + {1};'),
"sub": (2, 'float {0} = {2} - {1};'),
"mul": (2, 'float {0} = {2} * {1};'),
"div": (2, 'float {0} = {2} / {1};'),
"eq": (2, "float {0} = {2} == {1};"),
"ne": (2, "float {0} = {2} != {1};"),
"lt": (2, "float {0} = {2} < {1};"),
"le": (2, "float {0} = {2} <= {1};"),
"gt": (2, "float {0} = {2} > {1};"),
"ge": (2, "float {0} = {2} >= {1};"),
"minimum": (2, "float {0} = fminf({2},{1});"),
"maximum": (2, "float {0} = fmaxf({2},{1});"),
"pow": (2, "float {0} = powf({2},{1});"),
"finite": (1, _is_finite),
"neg": (1, "float {0} = -{1};"),
"abs": (1, "float {0} = abs({1});"),
"sgn": (1, "float {0} = ({1} == 0.0f) ? (0.0f) : (copysignf(1.0f, {1}));"),
"sqrt": (1, "float {0} = sqrtf({1});"),
"sqr": (1, "float {0} = {1} * {1};"),
"exp": (1, "float {0} = expf({1});"),
"log": (1, "float {0} = logf({1});"),
"exp2": (1, "float {0} = exp2f({1});"),
"log2": (1, "float {0} = log2f({1});"),
"sig": (1, "float {0} = 1.0f/(1.0f + expf(-{1}));"),
"sig2": (1, "float {0} = 1.0f/(1.0f + exp2f(-{1}));"),
"tanh": (1, "float {0} = tanhf({1});"),
"tanh2": (1, "float {0} = (exp2f(2.0f*{1}) - 1.0f) / (exp2f(2.0f*{1}) + 1.0f);"),
"rand": (0, "float {0} = frand(lfsr0, lfsr1, lfsr2);"),
"onehot": (0, "float {0} = {1} == {2};"),
}
_reduction_ops = {
"sum": {
"inits": "float {0} = 0.0f;",
"ops": "{0} += {1};",
"shfl_red": "{0} += __shfl_xor({0}, i);",
"share1_red": "sPartials[tid] += sPartials[tid + a];",
"share2_red": "{0} = sPartials[tid] + sPartials[tid + 32];",
},
"max": {
"inits": "float {0} = -FLT_MAX;",
"ops": "{0} = fmaxf({0}, {1});",
"shfl_red": "{0} = fmaxf({0}, __shfl_xor({0}, i));",
"share1_red": "sPartials[tid] = fmaxf(sPartials[tid], sPartials[tid + a]);",
"share2_red": "{0} = fmaxf(sPartials[tid], sPartials[tid + 32]);",
},
"min": {
"inits": "float {0} = FLT_MAX;",
"ops": "{0} = fminf({0}, {1});",
"shfl_red": "{0} = fminf({0}, __shfl_xor({0}, i));",
"share1_red": "sPartials[tid] = fminf(sPartials[tid], sPartials[tid + a]);",
"share2_red": "{0} = fminf(sPartials[tid], sPartials[tid + 32]);",
},
"argmax": {
"inits": "int {0} = -1; float max = -FLT_MAX;",
"ops": "if ({1} > max) {{ max = {1}; {0} = i; }}",
"shfl_red": "float max2 = __shfl_xor(max, i); int argMax2 = __shfl_xor({0}, i);\n"
" if (max2 > max) {{ max = max2; {0} = argMax2; }}"
" else if (max2 == max && argMax2 < {0}) {{ {0} = argMax2; }}",
},
"argmin": {
"inits": "int {0} = -1; float min = FLT_MAX;",
"ops": "if ({1} < min) {{ min = {1}; {0} = i; }}",
"shfl_red": "float min2 = __shfl_xor(min, i); int argMin2 = __shfl_xor({0}, i);\n"
" if (min2 < min) {{ min = min2; {0} = argMin2; }}"
" else if (min2 == min && argMin2 < {0}) {{ {0} = argMin2; }}",
},
}
def _build_tree(type_args):
"""
rebuild a mutable tree from the stack
flag each op node with whether it is scalar or not
also include a count of reductions under this node:
node: [ arg(op, tensor or const), is_scalar, red_count, left_child,
right_child ]
"""
stack = list()
for arg in type_args:
arg_type = arg[0]
if arg_type in _float_ops:
numops = _float_ops[arg_type][0]
# ops with zero args default to non-scalar
node = [arg, numops > 0, 0]
for i in range(numops):
operand = stack.pop()
# if child is another node in the tree:
if type(operand) is list:
# accumulate reduction count
node[2] += operand[2]
# if a child is not scalar, then neither is this node
if operand[1] == 0:
node[1] = False
# if child is an input tensor (an output tensor has id=0) then
# this node is not scalar
elif operand[0] is ng.GPUTensor and operand[1] > 0:
node[1] = False
# children start at position 3 and are added in reverse order
node.insert(3, operand)
stack.append(node)
elif arg_type in _reduction_ops:
operand = stack.pop()
reds = 1
# if child is another node accumulate reduction count
if type(operand) is list:
reds += operand[2]
# reductions are scalar by definition
stack.append([arg, True, reds, operand])
else:
# tensors and scalars just get added to the stack
# for later processing with operators
stack.append(arg)
# the stack should now contain just a single node which is the complete
# tree
return stack[0]
# for debugging
def _print_tree(node, level=0):
"""
print tree with indentation
"""
if type(node) is list:
print (" " * level) + ", ".join(str(s) for s in node[0:3])
if len(node) > 3:
_print_tree(node[3], level + 1)
if len(node) > 4:
_print_tree(node[4], level + 1)
else:
print (" " * level) + str(node)
def _post_order(node, stack=None):
"""
generate a stack from a portion of the tree
"""
if stack is None:
stack = list()
if type(node) is list:
if len(node) > 3:
_post_order(node[3], stack)
if len(node) > 4:
_post_order(node[4], stack)
stack.append(node[0])
else:
stack.append(node)
return stack
def _process_node(node, aliases, duplicates):
"""
Takes a node from the tree and searchs for any previously processed
duplicates.
If not a duplicate, returns a stage based from that node.
If a duplicate, the node is replaced with an alias to the dup stage.
In both cases the tree is removed below this node (and the alias remains).
"""
# generate a unique key from the stack of everything below this reduction
stack = _post_order(node)
key = list()
for item in stack:
# for operations, just append the name
# aliases require the id as well since they encapsulate specific
# tensors and constants
if type(item[0]) is str and item not in aliases:
key.append(item[0])
# For tensor or constant or alias, append type and id.
else:
key.append(item[0:2])
key = tuple(key)
# use the generated key to look for duplicates
dup_node = duplicates.get(key, False)
if dup_node:
# if this is a duplicate, replace the stack with the op node of the
# original reduction
node[0] = dup_node
# no new stage is returned in this case, the node is just converted
# into an alias
stack = None
else:
# first time seeing this reduction, record it in the dict
# the last item in the stack will be the reduction op
duplicates[key] = stack[-1]
# record which nodes can be aliased
aliases.add(stack[-1])
# drop any children (children start at position 3)
while len(node) > 3:
node.pop()
return stack
def _split_stages(node, duplicates=None, aliases=None, stages=None, parents=None):
"""
Split out all reductions and post reduction scalar operations into seperate
stacks (stages)
This leaves remaining in the tree anything not in these categories.
"""
# init data structures
if duplicates is None:
duplicates = dict()
aliases = set()
stages = list()
parents = list()
if type(node) is list:
# don't count assignment node as a parent,
# it will always exist in the final stage which is processed outside of
# this function
if node[0][0] != "assign":
parents.append(node)
# post order traversal (pulls the stages deepest in the tree first)
if len(node) > 3:
_split_stages(node[3], duplicates, aliases, stages, parents)
if len(node) > 4:
_split_stages(node[4], duplicates, aliases, stages, parents)
if len(parents) > 0:
parents.pop()
if node[0][0] in _reduction_ops:
red_stack = _process_node(node, aliases, duplicates)
if red_stack:
# add this reduction stack to the stages
stages.append(("reduction", red_stack))
# decrement reduction count for all parents
for parent in parents:
parent[2] -= 1
# walk up the parent list
# TODO: potentially do this iteratively to find longest common set
# of operations
scalar_parent = None
for parent in parents[::-1]:
# find the highest parent that is both scalar and has no other
# child reductions
if parent[1] and parent[2] == 0:
scalar_parent = parent
else:
break
# if there are any scalar operations over this reduction, remove
# them from the tree as well
if scalar_parent is not None:
scalar_stack = _process_node(
scalar_parent, aliases, duplicates)
if scalar_stack:
# add this scalar stack to the stages
stages.append(("scalar", scalar_stack))
return stages
def _init_rand(template_vals):
template_vals["common"].append(_common_urand_gen)
template_vals["inits"].append(_init_rand_func)
template_vals["finish"].append(_finish_rand_func)
return True
@context_dependent_memoize
def _get_compound_kernel(type_args):
"""
generate compound kernel for the optree from type_args
"""
# from the stack, rebuild a mutable tree
tree = _build_tree(type_args)
# _print_tree(tree)
# exit()
# split all reductions and post reduction scalar operations out of the tree
# sub-trees are converted to stacks and pushed onto stages list
stages = _split_stages(tree)
# _print_tree(tree)
# exit()
# set the final stage type to type of output (scalar or elementwise)
last_stage = "red_out" if tree[1] == 1 else "ew_out"
# convert the remainder of tree to stack
stages.append((last_stage, _post_order(tree)))
# for stage, stage_data in enumerate(stages):
# print stage_data[0], stage
# for s in stage_data[1]: print s
# print
# exit()
stack = list()
placeholders = list()
stage_out_reg = dict()
arg_dict = dict()
array_ids = set()
fp16In = False
rand_init = False
rand_func = False
threads = type_args[-1][3]
template = _ew_template
template_vals = {
"threads": threads,
"name": _get_kernel_name(),
"common": list(),
"inits": list(),
"finish": list(),
}
for stage, stage_data in enumerate(stages):
stage_type, stage_stack = stage_data
new_placeholders = list()
# build out the template as we process stages
if stage_type == "reduction":
new_placeholders.append("loads%d" % stage)
new_placeholders.append("ops%d" % stage)
new_placeholders.append("shfl_red%d" % stage)
template += _stage_template["loop"].format(stage)
if threads > 32:
new_placeholders.append("var_red%d" % stage)
new_placeholders.append("share1_red%d" % stage)
new_placeholders.append("share2_red%d" % stage)
template += _stage_template["red"].format(stage)
else:
template += _stage_template["red32"].format(stage)
elif stage_type == "scalar":
new_placeholders.append("ops%d" % stage)
template += _stage_template["red_ops"].format(stage)
elif stage_type == "red_out":
new_placeholders.append("ops%d" % stage)
template += _stage_template["red_out"].format(stage)
else: # ew_out
new_placeholders.append("loads%d" % stage)
new_placeholders.append("ops%d" % stage)
template += _stage_template["loop"].format(stage)
for key in new_placeholders:
template_vals[key] = []
placeholders.extend(new_placeholders)
for arg_i, arg in enumerate(stage_stack):
arg_type, arg_id = arg[0:2]
# Array operands
if arg_type is ng.GPUTensor:
dtype, take_axis = arg[2:4]
is_out_tensor = True if stage == len(
stages) - 1 and arg_i == 0 else False
# first arg is output array, don't put on stack
if is_out_tensor:
out_dtype = dtype
out_take = take_axis
else:
stack.append("a%d" % arg_id)
# 0: arg_id, 1: stage, 2: type, 3: cvt
ew_dtype = _ew_types[dtype]
fmt = (arg_id, stage, ew_dtype["type"], ew_dtype["cvt"])
# First time we see a tensor initialize everything
if arg_id not in array_ids:
array_ids.add(arg_id)
array_ids.add((arg_id, stage))
sig = "Pii"
if take_axis > 0:
sig += "P"
# output tensor
if is_out_tensor:
ew_out = _ew_strings["out%d" % take_axis]
arguments = ew_out["arguments"].format(*fmt)
template_vals["inits"].append(
ew_out["inits"].format(*fmt))
# input tensors
else:
ew_in = _ew_strings["in%d" % take_axis]
loads = "loads%d" % stage
arguments = ew_in["arguments"].format(*fmt)
template_vals["inits"].append(
ew_in["inits"].format(*fmt))
template_vals[loads].append(
ew_in["loads"].format(*fmt))
if dtype == 'f2' and not fp16In:
template_vals["common"].append(_common_fp16_to_fp32)
fp16In = True
arg_dict[arg] = (sig, arguments)
# Subsequent times we see a tensor just initialize inits and
# loads
elif (arg_id, stage) not in array_ids:
array_ids.add((arg_id, stage))
ew_in = _ew_strings["in%d" % take_axis]
loads = "loads%d" % stage
template_vals["inits"].append(ew_in["inits"].format(*fmt))
template_vals[loads].append(ew_in["loads"].format(*fmt))
# Constant operands
elif arg_type is float:
stack.append("c%d" % arg_id)
if arg not in arg_dict:
arg_dict[arg] = (
"f", _ew_strings["const"]["arguments"].format(arg_id))
# Operations (arg_type = op_name)
else:
if arg_type == "assign":
ops = "ops%d" % stage
# loop end condition for last stage
sig = "i"
arguments = ["const int n%d" % stage]
# rounding mode
if arg[2]:
mode = "random"
sig += "i"
arguments.append("const int mantissa_bits")
if not rand_init:
rand_init = _init_rand(template_vals)
template_vals["inits"].append(_init_rand_round_func)
else:
mode = "nearest"
arg_dict[arg] = (sig, ", ".join(arguments))
out_val = stack.pop()
# if the last stack value came from an argmax/min just do
# implicit type conversion
if out_val[0] == "i" and out_dtype[0] in "iu":
ew_round = None
else:
ew_round = _ew_strings["round"][
mode].get(out_dtype, None)
ew_common = _common_round[mode].get(out_dtype, None)
if ew_common:
template_vals["common"].append(ew_common)
if ew_round:
round_val = "r%d" % arg_id
template_vals[ops].append(
ew_round.format(round_val, out_val))
else:
round_val = out_val
template_vals[ops].append(
_ew_strings["out%d" % out_take]["output"].format(round_val))
elif arg in stage_out_reg:
stack.append(stage_out_reg[arg])
elif arg_type in _float_ops:
if len(template_vals["name"]) < 16:
template_vals["name"].append(arg_type)
ops = "ops%d" % stage
(num_ops, op_code) = _float_ops[arg_type]
if arg_type == "rand":
if not rand_init:
rand_init = _init_rand(template_vals)
if not rand_func:
template_vals["common"].append(_common_frand)
rand_func = True
op_list = ["r%d" % arg_id]
# build the operands from the stack
for i in range(num_ops):
op_list.append(stack.pop())
if arg_type == "onehot":
hot_axis = arg[2]
test_val = "i" if hot_axis else "bid"
ew_in = _ew_strings[arg_type + str(hot_axis)]
loads = "loads%d" % stage
template_vals["inits"].append(
ew_in["inits"].format(arg_id))
template_vals[loads].append(
ew_in["loads"].format(arg_id))
op_list.append("onehot%d" % arg_id)
op_list.append(test_val)
arg_dict[arg] = (
"P", ew_in["arguments"].format(arg_id))
template_vals[ops].append(op_code.format(*op_list))
# if this is the last op on the current stack, store its register stage
# in the stage output dict
if arg_i == len(stage_stack) - 1:
stage_out_reg[arg] = op_list[0]
# otherwise push the reg onto the stack as normal
else:
stack.append(op_list[0])
elif arg_type in _reduction_ops:
if len(template_vals["name"]) < 16:
template_vals["name"].append(arg_type)
# loop end condition for current stage
# add regardless of duplicate reduction stage
arg_dict[arg] = ("i", "const int n%d" % stage)
# avoid float conversion for argmax/min
reg = "i" if "arg" == arg_type[0:3] else "r"
ops = "ops%d" % stage
shfl_red = "shfl_red%d" % stage
red_arg = "%s%d" % (reg, arg_id)
red_strings = _reduction_ops[arg_type]
stack_arg = stack.pop()
template_vals["inits"].append(
red_strings["inits"].format(red_arg))
template_vals[ops].append(
red_strings["ops"].format(red_arg, stack_arg))
template_vals[shfl_red].append(
red_strings["shfl_red"].format(red_arg))
if threads > 32:
var_red = "var_red%d" % stage
shr1_red = "share1_red%d" % stage
shr2_red = "share2_red%d" % stage
template_vals[var_red].append(red_arg)
template_vals[shr1_red].append(
red_strings["share1_red"].format(red_arg))
template_vals[shr2_red].append(
red_strings["share2_red"].format(red_arg))
# reduction ops are always the last on the stack
# just store the register state in the stage output dict
stage_out_reg[arg] = red_arg
else:
raise ValueError("Bad op type.")
template += _fin_template
# since we reorderd the operations we need to generate the argument list
# in the original order
sig = "P"
arguments = list()
unused = 1
for arg in type_args:
params = arg_dict.get(arg, False)
if params:
sig += params[0]
arguments.append(params[1])
del arg_dict[arg]
# fill in the loop counter for the duplicate reductions that were
# removed
elif arg[0] in _reduction_ops:
sig += "i"
arguments.append("const int unused%d" % unused)
unused += 1
# convert lists to strings
template_vals["name"] = "_".join(template_vals["name"])
template_vals["common"] = "\n".join(template_vals["common"])
template_vals["arguments"] = ",\n ".join(arguments)
template_vals["inits"] = "\n ".join(template_vals["inits"])
template_vals["finish"] = "\n".join(template_vals["finish"])
# add the dynamic placeholders: loads#, ops#, reduction#
for key in placeholders:
template_vals[key] = "\n ".join(template_vals[key])
# populate the template
code = template % template_vals
# debugging:
# print "Compiling %s" % template_vals["name"]
# f = open("%s.cu" % template_vals["name"], "w")
# f = open("kernel.cu", "w")
# print >>f, code
# f.close()
# ,"-G" , keep=False
# module = SourceModule(code, options=["--use_fast_math"])
module = SourceModule(code, options=[])
kernel = module.get_function(template_vals["name"])
kernel.name = template_vals["name"]
kernel.prepare(sig)
return kernel
@memoize
def _get_fast_ew_dims(size):
# TODO: I can probably do much better than this code below,
# but I think most tensors are evenly divisable by 256 off the bat.
ew_size = 256
while ew_size > 0:
if size % ew_size == 0:
break
ew_size -= 32
if ew_size == 0:
ew_size = 255
while ew_size > 0:
if size % ew_size == 0:
break
ew_size -= 1
shape = (size // ew_size, ew_size)
return (shape, ng._contiguous_strides(shape))
# TODO: build a program wide DAG and only call this once at startup per
# assignment.
def call_compound_kernel(rand_state, *args):
"""
Pass in a list of GPUTensor objects, constants and operators in postfix notation..
C += 2.5 * A * B + 1
call_compound_ew_kernel(C, 2.5, A, "mul", B, "mul", 1, "add", C, "add", "assign")
"""
out = None
arg_cnt = 0
op_cnt = 0
array_ids = {}
const_ids = {}
kernel_args = [rand_state, ]
type_args = []
shape_stack = []
threads = 32
red_depth = 0
# Apply reduction constraints and determine thread axis
# Blocks will be allocated counter to this axis
# Also detect if this is a broadcast or transpose op.
contiguous = True
reduction = False
broadcast = False
transpose = False
argminmax = False
takeop = False
axis = 1
for arg in args:
if type(arg) is dict:
op_name = arg["op"]
if op_name in _reduction_ops:
if op_name[0:3] == "arg":
argminmax = True
# To reduce a whole tensor (axis=None) reduce along each axis
# in succession.
if arg.get("axis", None) not in (0, 1):
raise ValueError(
"Only reduction along an axis currently supported")
# Keep axis values consistent within the same kernel
if reduction is True:
if arg["axis"] != axis:
raise ValueError(
"Reduction only allowed along one axis per kernel.")
else:
reduction = True
axis = arg["axis"]
elif op_name == "onehot":
takeop = True
elif isinstance(arg, ng.GPUTensor):
if len(arg.shape) < 2:
broadcast = True
elif (len(arg.shape) == 2 and (arg.shape[0] == 1 or arg.shape[1] == 1)):
broadcast = True
elif arg.is_trans:
transpose = True
elif arg.take_array:
takeop = True
elif not arg.is_contiguous:
contiguous = False
# If reducing along axis 0 we need to reverse all stridess.
# Each block gets a column and the threads work down the columns.
strides_order = 1 if axis == 1 else -1
for arg in args:
# Array operand
if isinstance(arg, ng.GPUTensor):
# for complex operations, use the native dimensions
if broadcast or reduction or transpose or takeop or not contiguous:
if len(arg.shape) == 2:
shape = arg.shape
strides = list(arg.strides[::strides_order])
else:
raise ValueError(
"Operations that are not simple elementwise are only "
"currently supported in 2 dimensions.")
# use more efficient 2d dimensions if this is a plain ew op.
else:
shape, strides = _get_fast_ew_dims(arg.size)
strides = list(strides[::strides_order])
# If same array is passed in multiple times to expression,
# consolidate them into one kernel argument.
if arg in array_ids:
indx = array_ids[arg]
else:
# The first array passed in should be the output.
# It's ok if this array is duplicated as the first instance
# needs to be a mutable pointer.
# A subsequent instance of out (if present) will be a const
# pointer.
if out is None:
out = arg
indx = arg_cnt
else:
indx = array_ids[arg] = arg_cnt
arg_cnt += 1
# support broadcast
if shape[0] == 1:
strides[1 - axis] = 0
if shape[1] == 1:
strides[axis] = 0
kernel_args.extend((arg.gpudata, strides[0], strides[1]))
# fancy indexing/take
if arg.take_array:
kernel_args.append(arg.take_array[0].gpudata)
# swap the take axis when reducing axis=0
# also add 1 to distinguish between no take operations
if arg.take_array:
if axis != 1:
take_axis = 2 - arg.take_array[1]
else:
take_axis = arg.take_array[1] + 1
# no take operation
else:
take_axis = 0
type_args.append(
(ng.GPUTensor, indx, arg.dtype.str[1:], take_axis))
shape_stack.append(shape)
# Constant operand
elif type(arg) in (int, float):
arg = float(arg)
if arg in const_ids:
indx = const_ids[arg]
else:
indx = const_ids[arg] = arg_cnt
arg_cnt += 1
kernel_args.append(arg)
type_args.append((float, indx))
shape_stack.append((1, 1))
# Operation
elif type(arg) is dict:
op_name = arg["op"]
if op_name in _float_ops:
# we need to do the shape arithemtic for the current operation
max_shape = [1, 1]
for op_num in range(_float_ops[op_name][0]):
shape = shape_stack.pop()
for i in range(2):
if shape[i] != max_shape[i]:
# support broadcast
# TODO: don't allow output tensor itself to be broadcastable.
# The final output is fine as a broadcast, for example
# assigning a constant.
# You just dont want a tensor being assigned to a
# smaller shape.
if shape[i] == 1 or max_shape[i] == 1:
max_shape[i] = max(max_shape[i], shape[i])
else:
raise TypeError(
"Input shape:%s not compatible" % (shape,))
if op_name == "assign":
# the axis dim is the thread loop stop condition
kernel_args.append(max_shape[axis])
rounding = out.rounding
# support rounding to arbitrary mantissa size
if rounding:
# convert bool to some default mantissa
if rounding is True:
rounding = 10
elif out.dtype.type is np.float32:
rounding = min(rounding, 15)
elif out.dtype.type is np.float16:
rounding = min(rounding, 10)
kernel_args.append(max(rounding, 1))
# speed up deep reduction by using more than 32 threads
if reduction and not argminmax:
if red_depth >= 4096:
threads = 1024
elif red_depth >= 2048:
threads = 512
elif red_depth >= 1024:
threads = 256
elif red_depth >= 512:
threads = 128
elif red_depth >= 256:
threads = 64
# speed up deep broadcast by using more than 32 threads
elif not (reduction or transpose) and max_shape[1] >= 512:
threads = 256
type_args.append((op_name, op_cnt, rounding > 0, threads))
elif op_name == "onehot":
# flip the one hot axis if reducing axis=0
hot_axis = arg["axis"] if axis else 1 - arg["axis"]
type_args.append((op_name, op_cnt, hot_axis))
shape_stack.append(max_shape)
kernel_args.append(arg["idx"].gpudata)
else:
type_args.append((op_name, op_cnt))
shape_stack.append(max_shape)
elif op_name in _reduction_ops:
shape = list(shape_stack.pop())
red_depth = max(red_depth, shape[axis])
# Allow a new axis size if doing post reduction broadcast.
# So we need to know the axis size prior to reduction.
kernel_args.append(shape[axis])
type_args.append((op_name, op_cnt))
# reduce the current shape
shape[axis] = 1
# udpate the current shape state
shape_stack.append(shape)
else:
raise TypeError("%s is not a valid operation" % op_name)
op_cnt += 1
else:
raise TypeError(
"args must be instance of GPUTensor, int, float, or dict (for operators)")
# for s in argsprint: print s
# for s in kernel_args: print s
# for s in type_args: print s
# import ipdb; ipdb.set_trace()
# get or create the kernel in the memoize cache
kernel = _get_compound_kernel(tuple(type_args))
shared = threads * 4 if reduction and threads > 32 else 0
if out.backend.bench > 1:
repeat = out.backend.bench
start, end = ng._get_events()
start.record(out.backend.stream)
else:
repeat = 1
for r in range(repeat):
# call the kernel with the number of blocks set as the size of the off-axis
# Maxwell does well with 32 thread sized blocks, no need to autotune.
# for a in kernel_args: print a
kernel.prepared_async_call((max_shape[1 - axis], 1, 1),
(threads, 1, 1), out.backend.stream,
*kernel_args, shared_size=shared)
if out.backend.bench > 1:
end.record(out.backend.stream)
end.synchronize()
msecs = end.time_since(start) / repeat
print("%7.3f msecs shape(%d,%d) blk,thd(%d,%d) %s" % (
msecs, max_shape[0], max_shape[1], max_shape[1 - axis], threads, kernel.name))
return out
# quick wrapper to convert raw fp32 scratch data to a destination tensor
def _fp_convert(src_data, src_type, dest_tensor):
shape, strides = _get_fast_ew_dims(dest_tensor.size)
kernel_args = [0,
dest_tensor.gpudata, strides[0], strides[1],
src_data, strides[0], strides[1],
shape[1]]
kernel = _get_compound_kernel((
(ng.GPUTensor, 0, dest_tensor.dtype.str[1:], 0),
(ng.GPUTensor, 1, src_type, 0),
('assign', 0, False, 32)))
kernel.prepared_async_call((shape[0], 1, 1),
(32, 1, 1),
dest_tensor.backend.stream,
*kernel_args)
_transpose_kernel = r"""
__global__ void transpose(%(type)s* out, const %(type)s* in, int rows, int cols)
{
__shared__ %(type)s tile[32][33];
int tx = threadIdx.x;
int ty = threadIdx.y;
int bx = blockIdx.x;
int by = blockIdx.y;
int gx = bx * 32 + tx;
int gy = by * 32 + ty;
for (int j = 0; j < 32; j += 8)
{
int gy8 = gy + j;
if (gy8 < rows && gx < cols)
tile[ty + j][tx] = in[gy8*cols + gx];
}
__syncthreads();
gx = by * 32 + tx;
gy = bx * 32 + ty;
for (int j = 0; j < 32; j += 8)
{
int gy8 = gy + j;
if (gy8 < cols && gx < rows)
out[gy8*rows + gx] = tile[tx][ty + j];
}
}
"""
@context_dependent_memoize
def _get_transpose_kernel(dtype):
code = _transpose_kernel % _ew_types[dtype]
module = SourceModule(code)
kernel = module.get_function("transpose")
kernel.prepare("PPII")
return kernel
_shuffle_kernel = r"""
__global__ void dimShuffle(
%(type)s* out, const %(type)s* in,
int TRSK, int RSK, int SK, int K,
int TRSC, int RSC, int SC, int C,
int RS, int magic_RS, int shift_RS,
int S, int magic_S, int shift_S)
{
__shared__ %(type)s tile[32][33];
int tx = threadIdx.x;
int ty = threadIdx.y;
int bk = blockIdx.x;
int bc = blockIdx.y;
int trs = blockIdx.z;
int k = bk * 32 + tx;
int c = bc * 32 + ty;
int t = magic_RS * trs; t >>= shift_RS;
int rs = trs - t*RS;
int r = magic_S * rs; r >>= shift_S;
int s = rs - r*S;
for (int j = 0; j < 32; j += 8)
{
int cj = c + j;
if (cj < C && k < K)
tile[ty + j][tx] = in[ cj*TRSK + t*RSK + r*SK + s*K + k ];
}
__syncthreads();
k = bk * 32 + ty;
c = bc * 32 + tx;
for (int i = 0; i < 32; i += 8)
{
int ki = k + i;
if (ki < K && c < C)
out[ ki*TRSC + t*RSC + r*SC + s*C + c ] = tile[tx][ty + i];
}
}
"""
@context_dependent_memoize
def _get_shuffle_kernel(dtype):
code = _shuffle_kernel % _ew_types[dtype]
module = SourceModule(code)
kernel = module.get_function("dimShuffle")
kernel.prepare("PPIIIIIIIIIIIIII")
return kernel
_compensated_sum = r"""
%(common)s
__global__ void compensated_sum(unsigned* rand_state,
%(type)s* a_sum,
%(type)s* a_cmp,
const %(type)s* a_add,
float cmp_scale, float add_scale,
int row_strd, int col_strd, int n, int mantissa_bits)
{
const int tid = threadIdx.x;
const int bid = blockIdx.x;
int offset = bid * row_strd + tid * col_strd;
int inc = 32 * col_strd;
a_sum += offset;
a_cmp += offset;
a_add += offset;
%(inits)s
for (int i = tid; i < n; i += 32)
{
float s32 = %(cvt)s(__ldg((const %(type)s*)a_sum));
float c32 = %(cvt)s(__ldg((const %(type)s*)a_cmp));
float a32 = %(cvt)s(__ldg(a_add));
// Adjust amount to add by previous compensation
float y32 = a32 * add_scale - c32 * cmp_scale;
// Do the accumulation and truncate to the storage type
float rnd_sum = s32 + y32;
%(rnd_sum)s
// Convert accumulation back to fp32 so we can do more math on it
float t32 = %(cvt)s(t16);
// recover the low order bits that were lost in the truncation
float rnd_cmp = (t32 - s32) - y32;
%(rnd_cmp)s
*a_sum = t16;
*a_cmp = c16;
a_sum += inc;
a_cmp += inc;
a_add += inc;
}
%(finish)s
}
"""
@context_dependent_memoize
def _get_compensated_sum_kernel(dtype, rounding):
template_vals = dict()
for key in ("common", "inits", "finish"):
template_vals[key] = ""
if dtype == "f2":
template_vals["common"] += _common_fp16_to_fp32
if rounding:
template_vals["common"] += _common_urand_gen
template_vals["common"] += _common_round["nearest"].get(dtype, "")
template_vals["inits"] += _init_rand_func + _init_rand_round_func
template_vals["finish"] += _finish_rand_func
mode = "random"
else:
mode = "nearest"
template_vals["common"] += _common_round[mode].get(dtype, "")
template_vals["type"] = _ew_types[dtype]["type"]
template_vals["cvt"] = _ew_types[dtype]["cvt"]
no_op = "float {0} = {1};"
rnd_sum = _ew_strings["round"][mode].get(dtype, no_op)
rnd_cmp = _ew_strings["round"]["nearest"].get(dtype, no_op)
template_vals["rnd_sum"] = rnd_sum.format("t16", "rnd_sum")
template_vals["rnd_cmp"] = rnd_cmp.format("c16", "rnd_cmp")
code = _compensated_sum % template_vals
# f = open("compensated_sum.cu", "w")
# print >>f, code
# f.close()
module = SourceModule(code)
kernel = module.get_function("compensated_sum")
kernel.prepare("PPPPffiiii")
return kernel
nrv_re = re.compile(r'nervanagpu\.py$')
name_re = re.compile(r'\W')
def _get_kernel_name():
"""
Returns the path of the kernel
"""
names = ["kernel", ]
if "NVPROF_ID" in os.environ:
for frame in tb.extract_stack():
if nrv_re.search(frame[0]):
break
caller = frame[0:2]
file_path, file_name = os.path.split(caller[0])
path1, path2 = os.path.split(file_path)
file_base, ext = os.path.splitext(file_name)
for name in (path2, file_base, ext):
name = name_re.sub("", name)
if name:
names.append(name)
names.append(str(caller[1]))
return names
@context_dependent_memoize
def _get_hist_kernel(dtype_str, nbins, offset):
"""
Build a kernel to compute a 64 bin histogram.
Use templating to generate a customized kernel depending on the input data type.
Memoized to avoid compiling the same kernel twice.
"""
type_str = _ew_types[dtype_str[1:]]
from string import Template
code = Template(_common_fp16_to_fp32 + r"""
#define MAX(a,b) (a > b ? a : b)
#define MIN(a,b) (a < b ? a : b)
__global__ void kernel_histo (
int* d_hist, const $in_type* a1_in,
int strides, int size)
{
const int tid = threadIdx.x;
const int bid = blockIdx.x;
__shared__ int s[$nbins];
if(tid < $nbins){
s[tid] = 0;
}
if(bid == 0 && tid < $nbins){
d_hist[tid] = 0;
}
for (int i = tid + blockDim.x*bid; i < size; i += strides)
{
float a1 = $convert_to_float(__ldg(a1_in + i));
float absval = fabs(a1);
float logabs = round(log2f(absval));
int bin = MIN($nbins-1, MAX(0, logabs-($offset)));
atomicAdd(&s[bin], 1);
}
__syncthreads();
if(tid < $nbins){
atomicAdd(&d_hist[tid], s[tid]);
}
}
""")
module = SourceModule(code.substitute(in_type=type_str['type'],
convert_to_float=type_str['cvt'],
nbins=nbins,
offset=offset),
options=[])
kernel = module.get_function("kernel_histo")
kernel.prepare("PPII")
return kernel
def _compute_hist(tensor, hist, nbins=64, offset=-48):
"""
Helper function to compute the histogram of a tensor.
Arguments:
tensor (GPUTensor): the tensor to compute the histogram over
hist (gpu pointer): the gpu memory region to store the 64 bin hist in.
nbins (int, optional): number of histogram bins, each representing a power of 2
(default 64)
offset (int, optional): offset the value of a bin from its idx as a power of two
(default offset=-48 means bin 0 represents 2**-48)
"""
threads = 128
assert nbins < threads and nbins > 0
size = tensor.size
strides = np.floor(np.sqrt(size) / threads) * threads
if strides < threads:
strides = max(size / threads * threads, threads)
blocks = max(1, int(strides) // threads)
kernel_args = [hist, tensor.gpudata, strides, size]
hist_kern = _get_hist_kernel(tensor.dtype.str, nbins, offset)
hist_kern.prepared_call((blocks, 1, 1), (threads, 1, 1), *kernel_args)
|
phantomas1234/inspyred | refs/heads/master | recipes/micro_ec.py | 3 | import collections
import inspyred
class MicroEC(inspyred.ec.EvolutionaryComputation):
def __init__(self, random):
inspyred.ec.EvolutionaryComputation.__init__(self, random)
def evolve(self, generator, evaluator, pop_size=10, seeds=None, maximize=True, bounder=None, **args):
self._kwargs = args
self._kwargs['_ec'] = self
if seeds is None:
seeds = []
if bounder is None:
bounder = inspyred.ec.Bounder()
self.termination_cause = None
self.generator = generator
self.evaluator = evaluator
self.bounder = bounder
self.maximize = maximize
self.population = []
self.archive = []
microseeds = seeds
while not self._should_terminate(list(self.population), self.num_generations, self.num_evaluations):
microec = inspyred.ec.EvolutionaryComputation(self._random)
microec.selector = self.selector
microec.variator = self.variator
microec.replacer = self.replacer
microec.observer = self.observer
microec.terminator = inspyred.ec.terminators.evaluation_termination
maxevals = args['max_evaluations']
args['max_evaluations'] = args['micro_evaluations']
result = microec.evolve(generator=generator, evaluator=evaluator,
pop_size=pop_size, seeds=microseeds,
maximize=maximize, **args)
self.population = list(result)
args['max_evaluations'] = maxevals
result.sort(reverse=True)
microseeds = [result[0].candidate]
self.num_evaluations += microec.num_evaluations
# Migrate individuals.
self.population = self.migrator(random=self._random,
population=self.population,
args=self._kwargs)
# Archive individuals.
self.archive = self.archiver(random=self._random, archive=self.archive,
population=list(self.population), args=self._kwargs)
self.num_generations += microec.num_generations
if isinstance(self.observer, collections.Iterable):
for obs in self.observer:
obs(population=list(self.population), num_generations=self.num_generations,
num_evaluations=self.num_evaluations, args=self._kwargs)
else:
self.observer(population=list(self.population), num_generations=self.num_generations,
num_evaluations=self.num_evaluations, args=self._kwargs)
return self.population
if __name__ == '__main__':
import random
import math
import time
def rastrigin_generator(random, args):
return [random.uniform(-5.12, 5.12) for _ in range(2)]
def rastrigin_evaluator(candidates, args):
fitness = []
for cand in candidates:
fitness.append(10 * len(cand) + sum([x**2 - 10 * (math.cos(2*math.pi*x)) for x in cand]))
return fitness
prng = random.Random()
prng.seed(time.time())
micro = MicroEC(prng)
micro.selector = inspyred.ec.selectors.tournament_selection
micro.replacer = inspyred.ec.replacers.steady_state_replacement
micro.variator = [inspyred.ec.variators.uniform_crossover, inspyred.ec.variators.gaussian_mutation]
micro.archiver = inspyred.ec.archivers.best_archiver
micro.observer = inspyred.ec.observers.stats_observer
micro.terminator = inspyred.ec.terminators.evaluation_termination
final_pop = micro.evolve(rastrigin_generator,
rastrigin_evaluator,
pop_size=10,
maximize=False,
bounder=inspyred.ec.Bounder(-5.12, 5.12),
max_evaluations=3000,
micro_evaluations=300,
num_selected=2,
gaussian_stdev=0.1)
print('Actual evaluations: {0}'.format(micro.num_evaluations))
for p in micro.archive:
print p
|
JackDandy/SickGear | refs/heads/master | lib/hachoir_py2/parser/common/win32.py | 2 | from hachoir_py2.field import (FieldSet,
UInt16, UInt32, Enum, String, Bytes, Bits, TimestampUUID60)
from hachoir_py2.parser.video.fourcc import video_fourcc_name
from hachoir_py2.core.bits import str2hex
from hachoir_py2.core.text_handler import textHandler, hexadecimal
from hachoir_py2.parser.network.common import MAC48_Address
# Dictionary: Windows codepage => Python charset name
CODEPAGE_CHARSET = {
874: "CP874",
# 932: Japanese Shift-JIS
# 936: Simplified Chinese GBK
# 949: Korean
# 950: Traditional Chinese Big5
1250: "WINDOWS-1250",
1251: "WINDOWS-1251",
1252: "WINDOWS-1252",
1253: "WINDOWS-1253",
1254: "WINDOWS-1254",
1255: "WINDOWS-1255",
1256: "WINDOWS-1256",
1257: "WINDOWS-1257",
1258: "WINDOWS-1258",
10000: "MacRoman",
65001: "UTF-8",
}
class PascalStringWin16(FieldSet):
def __init__(self, parent, name, description=None, strip=None, charset="UTF-16-LE"):
FieldSet.__init__(self, parent, name, description)
length = self["length"].value
self._size = 16 + length * 16
self.strip = strip
self.charset = charset
def createFields(self):
yield UInt16(self, "length", "Length in widechar characters")
size = self["length"].value
if size:
yield String(self, "text", size * 2, charset=self.charset, strip=self.strip)
def createValue(self):
if "text" in self:
return self["text"].value
else:
return None
class PascalStringWin32(FieldSet):
def __init__(self, parent, name, description=None, strip=None, charset="UTF-16-LE"):
FieldSet.__init__(self, parent, name, description)
length = self["length"].value
self._size = 32 + length * 16
self.strip = strip
self.charset = charset
def createFields(self):
yield UInt32(self, "length", "Length in widechar characters")
size = self["length"].value
if size:
yield String(self, "text", size * 2, charset=self.charset, strip=self.strip)
def createValue(self):
if "text" in self:
return self["text"].value
else:
return None
class GUID(FieldSet):
"""
Windows 128 bits Globally Unique Identifier (GUID)
See RFC 4122
"""
static_size = 128
NULL = "00000000-0000-0000-0000-000000000000"
FIELD_NAMES = {
3: ("sha1_high", "sha1_low"),
4: ("random_high", "random_low"),
5: ("md5_high", "md5_low"),
}
VERSION_NAME = {
1: "Timestamp & MAC-48",
2: "DCE Security version",
3: "Name SHA-1 hash",
4: "Randomly generated",
5: "Name MD5 hash",
}
VARIANT_NAME = {
0: "NCS",
2: "Leach-Salz",
# 5: Microsoft Corporation?
6: "Microsoft Corporation",
7: "Reserved Future",
}
def __init__(self, *args):
FieldSet.__init__(self, *args)
self.version = self.stream.readBits(
self.absolute_address + 32 + 16 + 12, 4, self.endian)
def createFields(self):
if self.version == 1:
yield TimestampUUID60(self, "time")
yield Enum(Bits(self, "version", 4), self.VERSION_NAME)
yield Enum(Bits(self, "variant", 3), self.VARIANT_NAME)
yield textHandler(Bits(self, "clock", 13), hexadecimal)
# yield textHandler(Bits(self, "clock", 16), hexadecimal)
if self.version == 1:
yield MAC48_Address(self, "mac", "IEEE 802 MAC address")
else:
yield Bytes(self, "node", 6)
else:
namea, nameb = self.FIELD_NAMES.get(
self.version, ("data_a", "data_b"))
yield textHandler(Bits(self, namea, 60), hexadecimal)
yield Enum(Bits(self, "version", 4), self.VERSION_NAME)
yield Enum(Bits(self, "variant", 3), self.VARIANT_NAME)
yield textHandler(Bits(self, nameb, 61), hexadecimal)
def createValue(self):
addr = self.absolute_address
a = self.stream.readBits(addr, 32, self.endian)
b = self.stream.readBits(addr + 32, 16, self.endian)
c = self.stream.readBits(addr + 48, 16, self.endian)
d = self.stream.readBytes(addr + 64, 2)
e = self.stream.readBytes(addr + 80, 6)
return "%08X-%04X-%04X-%s-%s" % (a, b, c, str2hex(d), str2hex(e))
def createDisplay(self):
value = self.value
if value == self.NULL:
name = "Null GUID: "
else:
name = "GUID v%u (%s): " % (self.version, self["version"].display)
return name + value
def createRawDisplay(self):
value = self.stream.readBytes(self.absolute_address, 16)
return str2hex(value, format=r"\x%02x")
class BitmapInfoHeader(FieldSet):
""" Win32 BITMAPINFOHEADER structure from GDI """
static_size = 40 * 8
COMPRESSION_NAME = {
0: u"Uncompressed (RGB)",
1: u"RLE (8 bits)",
2: u"RLE (4 bits)",
3: u"Bitfields",
4: u"JPEG",
5: u"PNG"
}
def __init__(self, parent, name, use_fourcc=False):
FieldSet.__init__(self, parent, name)
self._use_fourcc = use_fourcc
def createFields(self):
yield UInt32(self, "hdr_size", "Header size (in bytes) (=40)")
yield UInt32(self, "width", "Width")
yield UInt32(self, "height", "Height")
yield UInt16(self, "nb_planes", "Color planes")
yield UInt16(self, "bpp", "Bits/pixel")
if self._use_fourcc:
yield Enum(String(self, "codec", 4, charset="ASCII"), video_fourcc_name)
else:
yield Enum(UInt32(self, "codec", "Compression"), self.COMPRESSION_NAME)
yield UInt32(self, "size", "Image size (in bytes)")
yield UInt32(self, "xres", "X pixels per meter")
yield UInt32(self, "yres", "Y pixels per meter")
yield UInt32(self, "color_used", "Number of used colors")
yield UInt32(self, "color_important", "Number of important colors")
def createDescription(self):
return "Bitmap info header: %ux%u pixels, %u bits/pixel" % \
(self["width"].value, self["height"].value, self["bpp"].value)
|
Conedy/Conedy | refs/heads/master | testing/global/expected/sum_set.py | 1 | 00000 0 output/set.py.err
00000 0 output/set.py.out
|
asrie/phantomjs | refs/heads/master | src/breakpad/src/tools/gyp/test/generator-output/actions/subdir2/make-file.py | 973 | #!/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.
import sys
contents = "Hello from make-file.py\n"
open(sys.argv[1], 'wb').write(contents)
|
VitalPet/c2c-rd-addons | refs/heads/8.0 | c2c_stock_accounting/wizard/stock_fill_inventory.py | 4 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2012-2012 ChriCar Beteiligungs- und Beratungs- GmbH (<http://www.camptocamp.at>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
import logging
from openerp.tools.translate import _
class stock_fill_inventory(osv.osv_memory):
_inherit = "stock.fill.inventory"
_logger = logging.getLogger(__name__)
def fill_inventory(self, cr, uid, ids, context=None):
if not context:
context = {}
if ids and len(ids):
ids_1 = ids[0]
inventory_id = context['active_ids'] and context['active_ids'][0]
if ids_1 and inventory_id:
self._logger.debug('FGF inventory %s %s '% (ids_1,inventory_id))
fill_inventory = self.browse(cr, uid, ids_1, context=context)
if fill_inventory.location_id:
inv_obj = self.pool.get('stock.inventory')
inv_date = inv_obj.read(cr, uid, inventory_id,['date'],context)['date']
self._logger.debug('FGF fill location %s'% (fill_inventory.location_id.id))
self._logger.debug('FGF fill date %s'% (inv_date))
context['inv_date'] = inv_date
res = self.fill_inventory_modified(cr, uid, ids, context)
self._logger.debug('FGF fille inventory res %s'% (res))
inventory_obj = self.pool.get('stock.inventory')
inventory_obj.write(cr, uid, inventory_id , {'recursive' : fill_inventory.recursive, 'location_id': fill_inventory.location_id.id})
self._logger.debug('FGF fill inventory write ')
inventory_line_obj = self.pool.get('stock.inventory.line')
if not fill_inventory.display_with_zero_qty:
ids_zero = inventory_line_obj.search(cr, uid, [('inventory_id','=', inventory_id), ('product_qty','=', '0')])
self._logger.debug('FGF fill zero ids %s' % (ids_zero))
inventory_line_obj.unlink(cr, uid, ids_zero)
ids_update = inventory_line_obj.search(cr, uid, [('inventory_id','=', inventory_id)])
ids2 = ','.join([str(id) for id in ids_update])
if ids_update:
cr.execute("""update stock_inventory_line
set product_qty_calc = product_qty
where id in (%s)""" % ids2)
#return res
return {'type': 'ir.actions.act_window_close'}
def fill_inventory_modified(self, cr, uid, ids, context=None):
""" To Import stock inventory according to products available in the selected locations.
this is a FULL compy of the stock/wizard/fill_inventory.py
except that the search is modified to reflect the inventory date
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: the ID or list of IDs if we want more than one
@param context: A standard dictionary
@return:
"""
if context is None:
context = {}
inventory_line_obj = self.pool.get('stock.inventory.line')
location_obj = self.pool.get('stock.location')
product_obj = self.pool.get('product.product')
stock_location_obj = self.pool.get('stock.location')
move_obj = self.pool.get('stock.move')
uom_obj = self.pool.get('product.uom')
if ids and len(ids):
ids = ids[0]
else:
return {'type': 'ir.actions.act_window_close'}
fill_inventory = self.browse(cr, uid, ids, context=context)
res = {}
res_location = {}
if fill_inventory.recursive:
location_ids = location_obj.search(cr, uid, [('location_id',
'child_of', [fill_inventory.location_id.id])], order="id",
context=context)
else:
location_ids = [fill_inventory.location_id.id]
res = {}
flag = False
for location in location_ids:
datas = {}
res[location] = {}
if context.get('inv_date') and context['inv_date']:
move_ids = move_obj.search(cr, uid, ['|',('location_dest_id','=',location),('location_id','=',location),('state','=','done'),('date','<=',context['inv_date'])], context=context)
else:
move_ids = move_obj.search(cr, uid, ['|',('location_dest_id','=',location),('location_id','=',location),('state','=','done')], context=context)
for move in move_obj.browse(cr, uid, move_ids, context=context):
lot_id = move.prodlot_id.id
prod_id = move.product_id.id
if move.location_dest_id.id == move.location_id.id :
qty = 0.0
elif move.location_dest_id.id == location:
qty = uom_obj._compute_qty(cr, uid, move.product_uom.id,move.product_qty, move.product_id.uom_id.id)
else:
qty = -uom_obj._compute_qty(cr, uid, move.product_uom.id,move.product_qty, move.product_id.uom_id.id)
if datas.get((prod_id, lot_id)):
qty += datas[(prod_id, lot_id)]['product_qty']
datas[(prod_id, lot_id)] = {'product_id': prod_id, 'location_id': location, 'product_qty': qty, 'product_uom': move.product_id.uom_id.id, 'prod_lot_id': lot_id}
if datas:
flag = True
res[location] = datas
if not flag:
raise osv.except_osv(_('Warning !'), _('No product in this location.'))
for stock_move in res.values():
for stock_move_details in stock_move.values():
stock_move_details.update({'inventory_id': context['active_ids'][0]})
domain = []
if fill_inventory.set_stock_zero:
stock_move_details.update({'product_qty': 0})
for field, value in stock_move_details.items():
domain.append((field, '=', value))
line_ids = inventory_line_obj.search(cr, uid, domain, context=context)
if not line_ids:
inventory_line_obj.create(cr, uid, stock_move_details, context=context)
inventory_line_obj = self.pool.get('stock.inventory.line')
# return {'type': 'ir.actions.act_window_close'}
return res
stock_fill_inventory()
|
CSGreater-Developers/HMC-Grader | refs/heads/master | app/scripts/helpers.py | 1 | from app.structures.models.user import *
from app.structures.models.course import *
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
print question + prompt
choice = raw_input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
print "Please respond with 'yes' or 'no' (or 'y' or 'n').\n"
def createUsername(firstName, lastName):
firstName = firstName.lower()
lastName = lastName.lower()
#Try increasing the length of the first name to remove conflicts
for i in range(1,len(firstName)+1):
try:
tryName = firstName[:i]+lastName
u = User.objects.get(username=tryName)
except User.DoesNotExist:
return firstName[:i]+lastName
#If we didn't get a successful name here append numbers
conflictNumber = 1
while True:
try:
tryName = firstName+lastName+str(conflictNumber)
u = User.objects.get(username=tryName)
conflictNumber += 1
except:
return firstName+lastName+str(conflictNumber)
def addUser(firstName, lastName, email=None, password="asdf"):
'''Creates a user with a distinct username'''
#create the user
u = User()
u.username = email#createUsername(firstName, lastName)
u.firstName = firstName
u.lastName = lastName
u.email = email
u.setPassword(password)
u.save()
#return the user when we are done
return u
def addOrGetUser(firstName, lastName, email=None, password="asdf"):
'''If we are given an email try to get an existing user otherwise create
a new user'''
if email != None:
try:
u = User.objects.filter(email=email)
if len(u) > 0:
return u[0]
except User.DoesNotExist:
pass
return addUser(firstName, lastName, email, password)
def addOrGetByUsername(username, firstName, lastName, email=None, password="asdf"):
try:
u = User.objects.get(username=email)#username)
return u
except User.DoesNotExist:
u = User()
u.username = email#username
u.firstName = firstName
u.lastName = lastName
u.email = email
u.setPassword(password)
u.save()
return u
def courseInList(course, courseList):
try:
if course in courseList:
return True
else:
return False
except:
return None
def getCourse(semester, name):
try:
c = Course.objects.get(semester=semester, name=name)
return c
except Course.DoesNotExist:
return None
def getUser(username):
try:
u = User.objects.get(username=username)
return u
except User.DoesNotExist:
return None
|
Dev-Cloud-Platform/Dev-Cloud | refs/heads/master | dev_cloud/virtual_controller/juju_core/juju_instance.py | 1 | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2015] Michał Szczygieł, M4GiK Software
#
# 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.
#
# @COPYRIGHT_end
class JujuInstance(object):
"""
http://dirtsimple.org/2004/12/python-is-not-java.html
~Trying break my mind.
"""
def __init__(self):
self._name = None
self._units = None
self._unit_machines = None
self._num_of_units = None
self._open_ports = None
self._machine = None
self._agent_state = None
self._public_address = None
self._instance_id = None
self._machine_number = None
self._exposed = None
self._unit_plural = None
self._relations = None
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def units(self):
return self._units
@units.setter
def units(self, units):
self._units = units
@property
def unit_machines(self):
return self._unit_machines
@unit_machines.setter
def unit_machines(self, unit_machines):
self._unit_machines = unit_machines
@property
def num_of_units(self):
return self._num_of_units
@num_of_units.setter
def num_of_units(self, num_of_units):
self._num_of_units = num_of_units
@property
def open_ports(self):
return self._open_ports
@open_ports.setter
def open_ports(self, open_ports):
self._open_ports = open_ports
@property
def machine(self):
return self._machine
@machine.setter
def machine(self, machine):
self._machine = machine
@property
def agent_state(self):
return self._agent_state
@agent_state.setter
def agent_state(self, agent_state):
self._agent_state = agent_state
@property
def public_address(self):
return self._public_address
@public_address.setter
def public_address(self, public_address):
self._public_address = public_address
@property
def instance_id(self):
return self._instance_id
@instance_id.setter
def instance_id(self, instance_id):
self._instance_id = instance_id
@property
def machine_number(self):
return self._machine_number
@machine_number.setter
def machine_number(self, machine_number):
self._machine_number = machine_number
@property
def exposed(self):
return self._exposed
@exposed.setter
def exposed(self, exposed):
self._exposed = exposed
@property
def unit_plural(self):
return self._unit_plural
@unit_plural.setter
def unit_plural(self, unit_plural):
self._unit_plural = unit_plural
@property
def relations(self):
return self._relations
@relations.setter
def relations(self, relations):
self._relations = relations
|
jagguli/intellij-community | refs/heads/master | python/lib/Lib/distutils/command/install_lib.py | 82 | # This module should be kept compatible with Python 2.1.
__revision__ = "$Id: install_lib.py 37946 2004-12-02 20:14:16Z lemburg $"
import sys, os, string
from types import IntType
from distutils.core import Command
from distutils.errors import DistutilsOptionError
# Extension for Python source files.
if hasattr(os, 'extsep'):
PYTHON_SOURCE_EXTENSION = os.extsep + "py"
else:
PYTHON_SOURCE_EXTENSION = ".py"
class install_lib (Command):
description = "install all Python modules (extensions and pure Python)"
# The byte-compilation options are a tad confusing. Here are the
# possible scenarios:
# 1) no compilation at all (--no-compile --no-optimize)
# 2) compile .pyc only (--compile --no-optimize; default)
# 3) compile .pyc and "level 1" .pyo (--compile --optimize)
# 4) compile "level 1" .pyo only (--no-compile --optimize)
# 5) compile .pyc and "level 2" .pyo (--compile --optimize-more)
# 6) compile "level 2" .pyo only (--no-compile --optimize-more)
#
# The UI for this is two option, 'compile' and 'optimize'.
# 'compile' is strictly boolean, and only decides whether to
# generate .pyc files. 'optimize' is three-way (0, 1, or 2), and
# decides both whether to generate .pyo files and what level of
# optimization to use.
user_options = [
('install-dir=', 'd', "directory to install to"),
('build-dir=','b', "build directory (where to install from)"),
('force', 'f', "force installation (overwrite existing files)"),
('compile', 'c', "compile .py to .pyc [default]"),
('no-compile', None, "don't compile .py files"),
('optimize=', 'O',
"also compile with optimization: -O1 for \"python -O\", "
"-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
('skip-build', None, "skip the build steps"),
]
boolean_options = ['force', 'compile', 'skip-build']
negative_opt = {'no-compile' : 'compile'}
def initialize_options (self):
# let the 'install' command dictate our installation directory
self.install_dir = None
self.build_dir = None
self.force = 0
self.compile = None
self.optimize = None
self.skip_build = None
def finalize_options (self):
# Get all the information we need to install pure Python modules
# from the umbrella 'install' command -- build (source) directory,
# install (target) directory, and whether to compile .py files.
self.set_undefined_options('install',
('build_lib', 'build_dir'),
('install_lib', 'install_dir'),
('force', 'force'),
('compile', 'compile'),
('optimize', 'optimize'),
('skip_build', 'skip_build'),
)
if self.compile is None:
self.compile = 1
if self.optimize is None:
self.optimize = 0
if type(self.optimize) is not IntType:
try:
self.optimize = int(self.optimize)
assert 0 <= self.optimize <= 2
except (ValueError, AssertionError):
raise DistutilsOptionError, "optimize must be 0, 1, or 2"
def run (self):
# Make sure we have built everything we need first
self.build()
# Install everything: simply dump the entire contents of the build
# directory to the installation directory (that's the beauty of
# having a build directory!)
outfiles = self.install()
# (Optionally) compile .py to .pyc
if outfiles is not None and self.distribution.has_pure_modules():
self.byte_compile(outfiles)
# run ()
# -- Top-level worker functions ------------------------------------
# (called from 'run()')
def build (self):
if not self.skip_build:
if self.distribution.has_pure_modules():
self.run_command('build_py')
if self.distribution.has_ext_modules():
self.run_command('build_ext')
def install (self):
if os.path.isdir(self.build_dir):
outfiles = self.copy_tree(self.build_dir, self.install_dir)
else:
self.warn("'%s' does not exist -- no Python modules to install" %
self.build_dir)
return
return outfiles
def byte_compile (self, files):
from distutils.util import byte_compile
# Get the "--root" directory supplied to the "install" command,
# and use it as a prefix to strip off the purported filename
# encoded in bytecode files. This is far from complete, but it
# should at least generate usable bytecode in RPM distributions.
install_root = self.get_finalized_command('install').root
if self.compile:
byte_compile(files, optimize=0,
force=self.force, prefix=install_root,
dry_run=self.dry_run)
if self.optimize > 0:
byte_compile(files, optimize=self.optimize,
force=self.force, prefix=install_root,
verbose=self.verbose, dry_run=self.dry_run)
# -- Utility methods -----------------------------------------------
def _mutate_outputs (self, has_any, build_cmd, cmd_option, output_dir):
if not has_any:
return []
build_cmd = self.get_finalized_command(build_cmd)
build_files = build_cmd.get_outputs()
build_dir = getattr(build_cmd, cmd_option)
prefix_len = len(build_dir) + len(os.sep)
outputs = []
for file in build_files:
outputs.append(os.path.join(output_dir, file[prefix_len:]))
return outputs
# _mutate_outputs ()
def _bytecode_filenames (self, py_filenames):
bytecode_files = []
for py_file in py_filenames:
# Since build_py handles package data installation, the
# list of outputs can contain more than just .py files.
# Make sure we only report bytecode for the .py files.
ext = os.path.splitext(os.path.normcase(py_file))[1]
if ext != PYTHON_SOURCE_EXTENSION:
continue
if self.compile:
bytecode_files.append(py_file + "c")
if self.optimize > 0:
bytecode_files.append(py_file + "o")
return bytecode_files
# -- External interface --------------------------------------------
# (called by outsiders)
def get_outputs (self):
"""Return the list of files that would be installed if this command
were actually run. Not affected by the "dry-run" flag or whether
modules have actually been built yet.
"""
pure_outputs = \
self._mutate_outputs(self.distribution.has_pure_modules(),
'build_py', 'build_lib',
self.install_dir)
if self.compile:
bytecode_outputs = self._bytecode_filenames(pure_outputs)
else:
bytecode_outputs = []
ext_outputs = \
self._mutate_outputs(self.distribution.has_ext_modules(),
'build_ext', 'build_lib',
self.install_dir)
return pure_outputs + bytecode_outputs + ext_outputs
# get_outputs ()
def get_inputs (self):
"""Get the list of files that are input to this command, ie. the
files that get installed as they are named in the build tree.
The files in this list correspond one-to-one to the output
filenames returned by 'get_outputs()'.
"""
inputs = []
if self.distribution.has_pure_modules():
build_py = self.get_finalized_command('build_py')
inputs.extend(build_py.get_outputs())
if self.distribution.has_ext_modules():
build_ext = self.get_finalized_command('build_ext')
inputs.extend(build_ext.get_outputs())
return inputs
# class install_lib
|
atantet/transferPlasim | refs/heads/master | runPlasim/postprocessor/indices/get_index_area.py | 1 | import os, sys
import numpy as np
from netCDF4 import Dataset
# Index calculation functions definition
def getAreaRange(srcVar, lat, lon, WEIGHTS, rng, win):
""" Calculate the Mean Surface Temperature. """
nt = srcVar.shape[0]
index = np.empty((nt,))
ilat = (lat >= win[1]) & (lat <= win[3])
ilon = (lon >= win[0]) & (lon <= win[2])
WEIGHTS = WEIGHTS[ilat][:, ilon]
for k in np.arange(nt):
srcVarWin = srcVar[k][ilat][:, ilon]
irng = (srcVarWin >= rng[0]) & (srcVarWin <= rng[1])
index[k] = WEIGHTS[irng].sum()
return index
S = float(sys.argv[1])
restartState = sys.argv[2]
indexChoice = sys.argv[3]
firstYear = int(sys.argv[4])
lastYear = int(sys.argv[5])
yearsPerFile = int(sys.argv[6])
daysPerYear = int(sys.argv[7])
srcDir = '../w2sb/'
# Ranges definition
Tf = 271.25 # Freezing temperature in Kelvin
rngTf20 = [Tf - 20, Tf]
rngTf10 = [Tf - 10, Tf]
rngTf = [0., Tf]
# Windows definitions [xll, yll, xur, yur]
winGlobal = [0., -90., 360., 90.]
winNHemi = [0., 0., 360., 90.]
winNPole = [0., 60., 360., 90.]
winNTrop = [0., 0., 360., 30.]
winEq = [0., -15., 360., 15.]
# Indices definitions
areaBelowTf20Glob = ('tsa', 'tsa', getAreaRange, 'areabelowtf20glob', rngTf20, winGlobal)
areaBelowTf20NHemi = ('tsa', 'tsa', getAreaRange, 'areabelowtf20nhemi', rngTf20, winNHemi)
areaBelowTf10NHemi = ('tsa', 'tsa', getAreaRange, 'areabelowtf10nhemi', rngTf10, winNHemi)
areaBelowTfNHemi = ('tsa', 'tsa', getAreaRange, 'areabelowtfnhemi', rngTf, winNHemi)
# Index choice
if indexChoice == 'areabelowtf20glob':
indexDef = areaBelowTf20Glob
elif indexChoice == 'areabelowtf20nhemi':
indexDef = areaBelowTf20NHemi
elif indexChoice == 'areabelowtf10nhemi':
indexDef = areaBelowTf10NHemi
elif indexChoice == 'areabelowtfnhemi':
indexDef = areaBelowTfNHemi
else:
sys.exit('Unknown index choice: %s!' % indexChoice)
# Grid definition
# Spherical harmonics = Legendre, Fourier
nlat = 32
nlon = nlat*2
(lat, latWeights) = np.polynomial.legendre.leggauss(nlat)
lat = -np.arcsin(lat) * 180 / np.pi
lon = np.linspace(0., 360., nlon, endpoint=False)
latWeights /= 2
lonWeights = np.ones((nlon,)) / nlon
(LONWEIGHTS, LATWEIGHTS) = np.meshgrid(lonWeights, latWeights)
WEIGHTS = LONWEIGHTS * LATWEIGHTS
# Allocate
nt = (lastYear - firstYear + 1) * daysPerYear
index = np.empty((nt,))
firstYearOfFile = np.arange(firstYear, lastYear, yearsPerFile)
for k in np.arange(firstYearOfFile.shape[0]):
# Read netCDF dataset
ncFilePath = '%s/%s_%s_%d_%05d_%05d.nc' \
% (srcDir, indexDef[0], restartState, S,
firstYearOfFile[k],
firstYearOfFile[k] + yearsPerFile - 1)
print 'Reading %s...' % ncFilePath
dset = Dataset(ncFilePath, 'r')
srcVar = dset.variables[indexDef[1]][:]
# Process variable
indexFile = indexDef[2](srcVar, lat, lon, WEIGHTS, indexDef[4], indexDef[5])
index[k*yearsPerFile*daysPerYear:(k+1)*yearsPerFile*daysPerYear] \
= indexFile
# Close netCDF dataset
dset.close()
# Save index
dstDir = '%s_%d/' % (restartState, S)
os.system('mkdir %s 2> /dev/null' % dstDir)
np.savetxt('%s/%s_%s_%d_%05d_%05d.txt' \
% (dstDir, indexDef[3], restartState, S,
firstYear, lastYear), index)
|
Split-Screen/android_kernel_huawei_msm8928 | refs/heads/pac-5.1 | tools/perf/scripts/python/net_dropmonitor.py | 4235 | # Monitor the system for dropped packets and proudce a report of drop locations and counts
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
drop_log = {}
kallsyms = []
def get_kallsyms_table():
global kallsyms
try:
f = open("/proc/kallsyms", "r")
linecount = 0
for line in f:
linecount = linecount+1
f.seek(0)
except:
return
j = 0
for line in f:
loc = int(line.split()[0], 16)
name = line.split()[2]
j = j +1
if ((j % 100) == 0):
print "\r" + str(j) + "/" + str(linecount),
kallsyms.append({ 'loc': loc, 'name' : name})
print "\r" + str(j) + "/" + str(linecount)
kallsyms.sort()
return
def get_sym(sloc):
loc = int(sloc)
for i in kallsyms:
if (i['loc'] >= loc):
return (i['name'], i['loc']-loc)
return (None, 0)
def print_drop_table():
print "%25s %25s %25s" % ("LOCATION", "OFFSET", "COUNT")
for i in drop_log.keys():
(sym, off) = get_sym(i)
if sym == None:
sym = i
print "%25s %25s %25s" % (sym, off, drop_log[i])
def trace_begin():
print "Starting trace (Ctrl-C to dump results)"
def trace_end():
print "Gathering kallsyms data"
get_kallsyms_table()
print_drop_table()
# called from perf, when it finds a correspoinding event
def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm,
skbaddr, protocol, location):
slocation = str(location)
try:
drop_log[slocation] = drop_log[slocation] + 1
except:
drop_log[slocation] = 1
|
mzhr/snakepig_engine | refs/heads/master | src/game.py | 1 | import pyglet
from pyglet.window import key
from src import world
class GameStates:
MAIN_MENU = 0
GAME_LOAD = 1
GAME_PLAY = 2
GAME_MENU = 3
class Window(pyglet.window.Window):
def __init__(self, *args, **kwargs):
# Initialize window.
super(Window, self).__init__(800, 600, *args, **kwargs)
# Initilize window icon.
self.icon = pyglet.image.load("data/icon.png")
self.set_icon(self.icon)
# Initialize initial game state.
# Currently set to GAME_PLAY for testing purposes.
# Should exist on MAIN_MENU later on.
self.current_state = GameStates.GAME_LOAD
# Initilize batch for image drawing.
self.batch = pyglet.graphics.Batch()
self.group_background = pyglet.graphics.OrderedGroup(0)
self.group_tile = pyglet.graphics.OrderedGroup(1)
self.group_character = pyglet.graphics.OrderedGroup(2)
self.group_text = pyglet.graphics.OrderedGroup(3)
self.backgrounds = []
self.tiles = []
self.characters = []
self.texts = []
# Initlize input buffer.
self.keys = pyglet.window.key.KeyStateHandler()
self.push_handlers(self.keys)
# Initilize fps and update functions.
self.fps_display = pyglet.clock.ClockDisplay()
pyglet.clock.schedule_interval(self.update, 1/60.0)
def on_draw(self):
self.clear()
self.batch.draw()
self.fps_display.draw()
def update(self, dt):
if self.current_state == GameStates.GAME_LOAD:
self.game_world = world.World(self, "data/world.txt")
self.current_state = GameStates.GAME_PLAY
if self.current_state == GameStates.GAME_PLAY:
self.game_world.update()
|
eltonsantos/django | refs/heads/master | tests/queries/__init__.py | 12133432 | |
lumig242/Hue-Integration-with-CDAP | refs/heads/pull3 | desktop/core/ext-py/django-extensions-1.5.0/django_extensions/templatetags/__init__.py | 12133432 | |
Tamriel/wagtail_room_booking | refs/heads/master | account/management/__init__.py | 12133432 | |
gangadhar-kadam/helpdesk-frappe | refs/heads/develop | frappe/print/doctype/__init__.py | 12133432 | |
camptocamp/QGIS | refs/heads/master | python/plugins/processing/algs/PointsDisplacement.py | 1 | # -*- coding: utf-8 -*-
"""
***************************************************************************
PointsDisplacement.py
---------------------
Date : July 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot 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. *
* *
***************************************************************************
"""
__author__ = 'Alexander Bruy'
__date__ = 'July 2013'
__copyright__ = '(C) 2013, Alexander Bruy'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import math
from PyQt4.QtCore import *
from qgis.core import *
from processing.tools import dataobjects, vector
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.parameters.ParameterVector import ParameterVector
from processing.parameters.ParameterNumber import ParameterNumber
from processing.parameters.ParameterBoolean import ParameterBoolean
from processing.outputs.OutputVector import OutputVector
class PointsDisplacement(GeoAlgorithm):
INPUT_LAYER = "INPUT_LAYER"
DISTANCE = "DISTANCE"
HORIZONTAL = "HORIZONTAL"
OUTPUT_LAYER = "OUTPUT_LAYER"
def defineCharacteristics(self):
self.name = "Points displacement"
self.group = "Vector geometry tools"
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", [ParameterVector.VECTOR_TYPE_POINT]))
self.addParameter(ParameterNumber(self.DISTANCE, "Displacement distance", 0.00001, 999999999.999990, 0.00015))
self.addParameter(ParameterBoolean(self.HORIZONTAL, "Horizontal distribution for two point case"))
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer"))
def processAlgorithm(self, progress):
radius = self.getParameterValue(self.DISTANCE)
horizontal = self.getParameterValue(self.HORIZONTAL)
output = self.getOutputFromName(self.OUTPUT_LAYER)
layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
provider = layer.dataProvider()
writer = output.getVectorWriter(provider.fields(), provider.geometryType(), provider.crs())
features = vector.features(layer)
current = 0
total = 100.0 / len(features)
duplicates = dict()
for f in features:
wkt = f.geometry().exportToWkt()
if wkt not in duplicates:
duplicates[wkt] = [f.id()]
else:
duplicates[wkt].extend([f.id()])
current += 1
progress.setPercentage(int(current * total))
current = 0
total = 100.0 / len(duplicates)
progress.setPercentage(0)
fullPerimeter = 2 * math.pi
request = QgsFeatureRequest()
for geom, fids in duplicates.iteritems():
count = len(fids)
if count == 1:
f = layer.getFeatures(request.setFilterFid(fids[0])).next()
writer.addFeature(f)
else:
angleStep = fullPerimeter / count
if count == 2 and horizontal:
currentAngle = math.pi / 2
else:
currentAngle = 0
old_point = QgsGeometry.fromWkt(geom).asPoint()
for fid in fids:
sinusCurrentAngle = math.sin(currentAngle)
cosinusCurrentAngle = math.cos(currentAngle)
dx = radius * sinusCurrentAngle
dy = radius * cosinusCurrentAngle
f = layer.getFeatures(request.setFilterFid(fid)).next()
new_point = QgsPoint(old_point.x() + dx, old_point.y() + dy)
out_feature = QgsFeature()
out_feature.setGeometry(QgsGeometry.fromPoint(new_point))
out_feature.setAttributes(f.attributes())
writer.addFeature(out_feature)
currentAngle += angleStep
current += 1
progress.setPercentage(int(current * total))
del writer
|
MarkTseng/django-farmersale | refs/heads/master | farmersale-env/lib/python2.7/site-packages/pip/_vendor/__init__.py | 360 | """
pip._vendor is for vendoring dependencies of pip to prevent needing pip to
depend on something external.
Files inside of pip._vendor should be considered immutable and should only be
updated to versions from upstream.
"""
from __future__ import absolute_import
|
plushvoxel/RIOT | refs/heads/master | dist/tools/pyterm/pytermcontroller/__init__.py | 138 | __all__ = ["pytermcontroller"]
|
cloudcache/zstack-utility | refs/heads/master | apibinding/test/__init__.py | 12133432 | |
adnanh/zulip | refs/heads/master | confirmation/management/commands/__init__.py | 12133432 | |
pkug/intelmq | refs/heads/master | intelmq/bots/parsers/fraunhofer/__init__.py | 12133432 | |
memnonila/django-cms | refs/heads/develop | cms/test_utils/project/fakemlng/south_migrations/__init__.py | 12133432 | |
gapan/functionplot | refs/heads/master | functionplot/img/__init__.py | 12133432 | |
qilicun/python | refs/heads/master | python3/src/input/bisection_plot.py | 1 | """
Graphical illustration of the bisection algorithm for solving nonlinear
algebraic equations of the form f(x)=0.
Usage:
python bisection_plot.py f_formula a b [epsilon]
Note that f(x) must change sign in the interval [a,b].
"""
from bisection import bisection_evolution
import sys, time
usage = '%s f-formula a b [epsilon]' % sys.argv[0]
try:
# f_formula = sys.argv[1]
a = float(sys.argv[1])
b = float(sys.argv[2])
except IndexError:
print usage; sys.exit(1)
try: # is epsilon given on the command-line?
epsilon = float(sys.argv[3])
except IndexError:
epsilon = 1E-6 # default value
# Clean up all plot files
import glob, os
for filename in glob.glob('tmp_*.eps'): os.remove(filename)
#from scitools.StringFunction import StringFunction
#from scitools.std import * # might be needed for f_formula
#f = StringFunction(f_formula)
#f.vectorize(globals())
def f(x):
return x**2 -4
results = bisection_evolution(f, a, b, epsilon)
if results is None:
print 'f does not change sign in [%g, %g]' % (a, b)
sys.exit(1)
# Visualize
import numpy as np
import pylab as pl
x = np.linspace(a, b, 501)
y = f(x)
ymin = min(y); ymax = max(y)
itcount = 1
for interval, m in results:
a, b = interval
pl.plot(x, y, 'r-',
[a, a], [ymin, ymax], 'g-',
[b, b], [ymin, ymax], 'g-',
[m, m], [ymin, ymax], 'b-',
[x[0], x[-1]], [0, 0], 'y-',
legend=('f(x)', 'a', 'b', 'm', 'y=0'),
title='The Bisection method, iteration %d: [%.2g, %.2g]' % \
(itcount, a, b), hardcopy='tmp_%02d.eps' % itcount)
itcount += 1
time.sleep(2)
#raw_input('Type CR: ')
movie('tmp_*.eps', encoder='convert', fps=2,
output_file='tmpmovie.gif')
|
JBonsink/GSOC-2013 | refs/heads/master | tools/ns-allinone-3.14.1/ns-3.14.1/src/mesh/test/examples-to-run.py | 196 | #! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
("mesh", "True", "True"),
]
# A list of Python examples to run in order to ensure that they remain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = []
|
joshbohde/scikit-learn | refs/heads/master | sklearn/cross_val.py | 1 | import warnings
warnings.warn('sklearn.cross_val namespace is deprecated in version 0.9'
' and will be removed in version 0.11.'
' Please use sklearn.cross_validation instead.')
from .cross_validation import *
|
NullSoldier/django | refs/heads/master | tests/messages_tests/test_middleware.py | 498 | import unittest
from django import http
from django.contrib.messages.middleware import MessageMiddleware
class MiddlewareTest(unittest.TestCase):
def setUp(self):
self.middleware = MessageMiddleware()
def test_response_without_messages(self):
"""
Makes sure that the response middleware is tolerant of messages not
existing on request.
"""
request = http.HttpRequest()
response = http.HttpResponse()
self.middleware.process_response(request, response)
|
jagguli/intellij-community | refs/heads/master | python/testData/refactoring/pullup/moveInstanceAttributesSimple.py | 80 | class Parent:
def __init__(self):
pass
class Child(Parent):
def __init__(self):
Parent2.__init__(self)
self.instance_field = "eggs"
|
hmronline/home-assistant | refs/heads/dev | homeassistant/components/switch/template.py | 7 | """
Support for switches which integrates with other components.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.template/
"""
import logging
from homeassistant.components.switch import ENTITY_ID_FORMAT, SwitchDevice
from homeassistant.const import (
ATTR_FRIENDLY_NAME, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON,
ATTR_ENTITY_ID, MATCH_ALL)
from homeassistant.exceptions import TemplateError
from homeassistant.helpers.entity import generate_entity_id
from homeassistant.helpers.script import Script
from homeassistant.helpers import template
from homeassistant.helpers.event import track_state_change
from homeassistant.util import slugify
CONF_SWITCHES = 'switches'
ON_ACTION = 'turn_on'
OFF_ACTION = 'turn_off'
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, 'true', 'false']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Template switch."""
switches = []
if config.get(CONF_SWITCHES) is None:
_LOGGER.error("Missing configuration data for switch platform")
return False
for device, device_config in config[CONF_SWITCHES].items():
if device != slugify(device):
_LOGGER.error("Found invalid key for switch.template: %s. "
"Use %s instead", device, slugify(device))
continue
if not isinstance(device_config, dict):
_LOGGER.error("Missing configuration data for switch %s", device)
continue
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
on_action = device_config.get(ON_ACTION)
off_action = device_config.get(OFF_ACTION)
if state_template is None:
_LOGGER.error(
"Missing %s for switch %s", CONF_VALUE_TEMPLATE, device)
continue
if on_action is None or off_action is None:
_LOGGER.error(
"Missing action for switch %s", device)
continue
entity_ids = device_config.get(ATTR_ENTITY_ID, MATCH_ALL)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
on_action,
off_action,
entity_ids)
)
if not switches:
_LOGGER.error("No switches added")
return False
add_devices(switches)
return True
class SwitchTemplate(SwitchDevice):
"""Representation of a Template switch."""
# pylint: disable=too-many-arguments
def __init__(self, hass, device_id, friendly_name, state_template,
on_action, off_action, entity_ids):
"""Initialize the Template switch."""
self.hass = hass
self.entity_id = generate_entity_id(ENTITY_ID_FORMAT, device_id,
hass=hass)
self._name = friendly_name
self._template = state_template
self._on_script = Script(hass, on_action)
self._off_script = Script(hass, off_action)
self._state = False
self.update()
def template_switch_state_listener(entity, old_state, new_state):
"""Called when the target device changes state."""
self.update_ha_state(True)
track_state_change(hass, entity_ids,
template_switch_state_listener)
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def available(self):
"""If switch is available."""
return self._state is not None
def turn_on(self, **kwargs):
"""Fire the on action."""
self._on_script.run()
def turn_off(self, **kwargs):
"""Fire the off action."""
self._off_script.run()
def update(self):
"""Update the state from the template."""
try:
state = template.render(self.hass, self._template).lower()
if state in _VALID_STATES:
self._state = state in ('true', STATE_ON)
else:
_LOGGER.error(
'Received invalid switch is_on state: %s. Expected: %s',
state, ', '.join(_VALID_STATES))
self._state = None
except TemplateError as ex:
_LOGGER.error(ex)
self._state = None
|
gdooper/scipy | refs/heads/master | scipy/special/_precompute/gammainc_asy.py | 32 | """
Precompute coefficients of Temme's asymptotic expansion for gammainc.
This takes about 8 hours to run on a 2.3 GHz Macbook Pro with 4GB ram.
Sources:
[1] NIST, "Digital Library of Mathematical Functions",
http://dlmf.nist.gov/
"""
from __future__ import division, print_function, absolute_import
import os
from scipy.special._precompute.utils import lagrange_inversion
try:
import mpmath as mp
except ImportError:
pass
def compute_a(n):
"""a_k from DLMF 5.11.6"""
a = [mp.sqrt(2)/2]
for k in range(1, n):
ak = a[-1]/k
for j in range(1, len(a)):
ak -= a[j]*a[-j]/(j + 1)
ak /= a[0]*(1 + mp.mpf(1)/(k + 1))
a.append(ak)
return a
def compute_g(n):
"""g_k from DLMF 5.11.3/5.11.5"""
a = compute_a(2*n)
g = []
for k in range(n):
g.append(mp.sqrt(2)*mp.rf(0.5, k)*a[2*k])
return g
def eta(lam):
"""Function from DLMF 8.12.1 shifted to be centered at 0."""
if lam > 0:
return mp.sqrt(2*(lam - mp.log(lam + 1)))
elif lam < 0:
return -mp.sqrt(2*(lam - mp.log(lam + 1)))
else:
return 0
def compute_alpha(n):
"""alpha_n from DLMF 8.12.13"""
coeffs = mp.taylor(eta, 0, n - 1)
return lagrange_inversion(coeffs)
def compute_d(K, N):
"""d_{k, n} from DLMF 8.12.12"""
M = N + 2*K
d0 = [-mp.mpf(1)/3]
alpha = compute_alpha(M + 2)
for n in range(1, M):
d0.append((n + 2)*alpha[n+2])
d = [d0]
g = compute_g(K)
for k in range(1, K):
dk = []
for n in range(M - 2*k):
dk.append((-1)**k*g[k]*d[0][n] + (n + 2)*d[k-1][n+2])
d.append(dk)
for k in range(K):
d[k] = d[k][:N]
return d
header = \
r"""/* This file was automatically generated by _precomp/gammainc.py.
* Do not edit it manually!
*/
#ifndef IGAM_H
#define IGAM_H
#define K {}
#define N {}
double d[K][N] =
{{"""
footer = \
r"""
#endif
"""
def main():
print(__doc__)
K = 25
N = 25
with mp.workdps(50):
d = compute_d(K, N)
fn = os.path.join(os.path.dirname(__file__), '..', 'cephes', 'igam.h')
with open(fn + '.new', 'w') as f:
f.write(header.format(K, N))
for k, row in enumerate(d):
row = map(lambda x: mp.nstr(x, 17, min_fixed=0, max_fixed=0), row)
f.write('{')
f.write(", ".join(row))
if k < K - 1:
f.write('},\n')
else:
f.write('}};\n')
f.write(footer)
os.rename(fn + '.new', fn)
if __name__ == "__main__":
main()
|
iurisilvio/flask-admin | refs/heads/master | flask_admin/model/base.py | 1 | import warnings
import re
import csv
import mimetypes
import time
from math import ceil
from werkzeug import secure_filename
from flask import (request, redirect, flash, abort, json, Response,
get_flashed_messages, stream_with_context)
from jinja2 import contextfunction
try:
import tablib
except ImportError:
tablib = None
from wtforms.fields import HiddenField
from wtforms.fields.core import UnboundField
from wtforms.validators import ValidationError, InputRequired
from flask_admin.babel import gettext
from flask_admin.base import BaseView, expose
from flask_admin.form import BaseForm, FormOpts, rules
from flask_admin.model import filters, typefmt, template
from flask_admin.actions import ActionsMixin
from flask_admin.helpers import (get_form_data, validate_form_on_submit,
get_redirect_target, flash_errors)
from flask_admin.tools import rec_getattr
from flask_admin._backwards import ObsoleteAttr
from flask_admin._compat import (iteritems, itervalues, OrderedDict,
as_unicode, csv_encode, text_type)
from .helpers import prettify_name, get_mdict_item_or_list
from .ajax import AjaxModelLoader
# Used to generate filter query string name
filter_char_re = re.compile('[^a-z0-9 ]')
filter_compact_re = re.compile(' +')
class ViewArgs(object):
"""
List view arguments.
"""
def __init__(self, page=None, sort=None, sort_desc=None, search=None, filters=None, extra_args=None):
self.page = page
self.sort = sort
self.sort_desc = bool(sort_desc)
self.search = search
self.filters = filters
if not self.search:
self.search = None
self.extra_args = extra_args or dict()
def clone(self, **kwargs):
if self.filters:
flt = list(self.filters)
else:
flt = None
kwargs.setdefault('page', self.page)
kwargs.setdefault('sort', self.sort)
kwargs.setdefault('sort_desc', self.sort_desc)
kwargs.setdefault('search', self.search)
kwargs.setdefault('filters', flt)
kwargs.setdefault('extra_args', dict(self.extra_args))
return ViewArgs(**kwargs)
class FilterGroup(object):
def __init__(self, label):
self.label = label
self.filters = []
def append(self, filter):
self.filters.append(filter)
def non_lazy(self):
filters = []
for item in self.filters:
copy = dict(item)
copy['operation'] = as_unicode(copy['operation'])
options = copy['options']
if options:
copy['options'] = [(k, text_type(v)) for k, v in options]
filters.append(copy)
return as_unicode(self.label), filters
def __iter__(self):
return iter(self.filters)
class BaseModelView(BaseView, ActionsMixin):
"""
Base model view.
This view does not make any assumptions on how models are stored or managed, but expects the following:
1. The provided model is an object
2. The model contains properties
3. Each model contains an attribute which uniquely identifies it (i.e. a primary key for a database model)
4. It is possible to retrieve a list of sorted models with pagination applied from a data source
5. You can get one model by its identifier from the data source
Essentially, if you want to support a new data store, all you have to do is:
1. Derive from the `BaseModelView` class
2. Implement various data-related methods (`get_list`, `get_one`, `create_model`, etc)
3. Implement automatic form generation from the model representation (`scaffold_form`)
"""
# Permissions
can_create = True
"""Is model creation allowed"""
can_edit = True
"""Is model editing allowed"""
can_delete = True
"""Is model deletion allowed"""
can_view_details = False
"""
Setting this to true will enable the details view. This is recommended
when there are too many columns to display in the list_view.
"""
can_export = False
"""Is model list export allowed"""
# Templates
list_template = 'admin/model/list.html'
"""Default list view template"""
edit_template = 'admin/model/edit.html'
"""Default edit template"""
create_template = 'admin/model/create.html'
"""Default create template"""
details_template = 'admin/model/details.html'
"""Default details view template"""
# Modal Templates
edit_modal_template = 'admin/model/modals/edit.html'
"""Default edit modal template"""
create_modal_template = 'admin/model/modals/create.html'
"""Default create modal template"""
details_modal_template = 'admin/model/modals/details.html'
"""Default details modal view template"""
# Modals
edit_modal = False
"""Setting this to true will display the edit_view as a modal dialog."""
create_modal = False
"""Setting this to true will display the create_view as a modal dialog."""
details_modal = False
"""Setting this to true will display the details_view as a modal dialog."""
# Customizations
column_list = ObsoleteAttr('column_list', 'list_columns', None)
"""
Collection of the model field names for the list view.
If set to `None`, will get them from the model.
For example::
class MyModelView(BaseModelView):
column_list = ('name', 'last_name', 'email')
(Added in 1.4.0) SQLAlchemy model attributes can be used instead of strings::
class MyModelView(BaseModelView):
column_list = ('name', User.last_name)
When using SQLAlchemy models, you can reference related columns like this::
class MyModelView(BaseModelView):
column_list = ('<relationship>.<related column name>',)
"""
column_exclude_list = ObsoleteAttr('column_exclude_list',
'excluded_list_columns', None)
"""
Collection of excluded list column names.
For example::
class MyModelView(BaseModelView):
column_exclude_list = ('last_name', 'email')
"""
column_details_list = None
"""
Collection of the field names included in the details view.
If set to `None`, will get them from the model.
"""
column_details_exclude_list = None
"""
Collection of fields excluded from the details view.
"""
column_export_list = None
"""
Collection of the field names included in the export.
If set to `None`, will get them from the model.
"""
column_export_exclude_list = None
"""
Collection of fields excluded from the export.
"""
column_formatters = ObsoleteAttr('column_formatters', 'list_formatters', dict())
"""
Dictionary of list view column formatters.
For example, if you want to show price multiplied by
two, you can do something like this::
class MyModelView(BaseModelView):
column_formatters = dict(price=lambda v, c, m, p: m.price*2)
or using Jinja2 `macro` in template::
from flask_admin.model.template import macro
class MyModelView(BaseModelView):
column_formatters = dict(price=macro('render_price'))
# in template
{% macro render_price(model, column) %}
{{ model.price * 2 }}
{% endmacro %}
The Callback function has the prototype::
def formatter(view, context, model, name):
# `view` is current administrative view
# `context` is instance of jinja2.runtime.Context
# `model` is model instance
# `name` is property name
pass
"""
column_formatters_export = None
"""
Dictionary of list view column formatters to be used for export.
Defaults to column_formatters when set to None.
Functions the same way as column_formatters except
that macros are not supported.
"""
column_type_formatters = ObsoleteAttr('column_type_formatters', 'list_type_formatters', None)
"""
Dictionary of value type formatters to be used in the list view.
By default, three types are formatted:
1. ``None`` will be displayed as an empty string
2. ``bool`` will be displayed as a checkmark if it is ``True``
3. ``list`` will be joined using ', '
If you don't like the default behavior and don't want any type formatters
applied, just override this property with an empty dictionary::
class MyModelView(BaseModelView):
column_type_formatters = dict()
If you want to display `NULL` instead of an empty string, you can do
something like this. Also comes with bonus `date` formatter::
from datetime import date
from flask_admin.model import typefmt
def date_format(view, value):
return value.strftime('%d.%m.%Y')
MY_DEFAULT_FORMATTERS = dict(typefmt.BASE_FORMATTERS)
MY_DEFAULT_FORMATTERS.update({
type(None): typefmt.null_formatter,
date: date_format
})
class MyModelView(BaseModelView):
column_type_formatters = MY_DEFAULT_FORMATTERS
Type formatters have lower priority than list column formatters.
The callback function has following prototype::
def type_formatter(view, value):
# `view` is current administrative view
# `value` value to format
pass
"""
column_type_formatters_export = None
"""
Dictionary of value type formatters to be used in the export.
By default, two types are formatted:
1. ``None`` will be displayed as an empty string
2. ``list`` will be joined using ', '
Functions the same way as column_type_formatters.
"""
column_labels = ObsoleteAttr('column_labels', 'rename_columns', None)
"""
Dictionary where key is column name and value is string to display.
For example::
class MyModelView(BaseModelView):
column_labels = dict(name='Name', last_name='Last Name')
"""
column_descriptions = None
"""
Dictionary where key is column name and
value is description for `list view` column or add/edit form field.
For example::
class MyModelView(BaseModelView):
column_descriptions = dict(
full_name='First and Last name'
)
"""
column_sortable_list = ObsoleteAttr('column_sortable_list',
'sortable_columns',
None)
"""
Collection of the sortable columns for the list view.
If set to `None`, will get them from the model.
For example::
class MyModelView(BaseModelView):
column_sortable_list = ('name', 'last_name')
If you want to explicitly specify field/column to be used while
sorting, you can use a tuple::
class MyModelView(BaseModelView):
column_sortable_list = ('name', ('user', 'user.username'))
When using SQLAlchemy models, model attributes can be used instead
of strings::
class MyModelView(BaseModelView):
column_sortable_list = ('name', ('user', User.username))
"""
column_default_sort = None
"""
Default sort column if no sorting is applied.
Example::
class MyModelView(BaseModelView):
column_default_sort = 'user'
You can use tuple to control ascending descending order. In following example, items
will be sorted in descending order::
class MyModelView(BaseModelView):
column_default_sort = ('user', True)
"""
column_searchable_list = ObsoleteAttr('column_searchable_list',
'searchable_columns',
None)
"""
A collection of the searchable columns. It is assumed that only
text-only fields are searchable, but it is up to the model
implementation to decide.
Example::
class MyModelView(BaseModelView):
column_searchable_list = ('name', 'email')
"""
column_editable_list = None
"""
Collection of the columns which can be edited from the list view.
For example::
class MyModelView(BaseModelView):
column_editable_list = ('name', 'last_name')
"""
column_choices = None
"""
Map choices to columns in list view
Example::
class MyModelView(BaseModelView):
column_choices = {
'my_column': [
('db_value', 'display_value'),
]
}
"""
column_filters = None
"""
Collection of the column filters.
Can contain either field names or instances of :class:`~flask_admin.model.filters.BaseFilter` classes.
Example::
class MyModelView(BaseModelView):
column_filters = ('user', 'email')
"""
named_filter_urls = False
"""
Set to True to use human-readable names for filters in URL parameters.
False by default so as to be robust across translations.
Changing this parameter will break any existing URLs that have filters.
"""
column_display_pk = ObsoleteAttr('column_display_pk',
'list_display_pk',
False)
"""
Controls if the primary key should be displayed in the list view.
"""
column_display_actions = True
"""
Controls the display of the row actions (edit, delete, details, etc.)
column in the list view.
Useful for preventing a blank column from displaying if your view does
not use any build-in or custom row actions.
This column is not hidden automatically due to backwards compatibility.
Note: This only affects display and does not control whether the row
actions endpoints are accessible.
"""
column_extra_row_actions = None
"""
List of row actions (instances of :class:`~flask_admin.model.template.BaseListRowAction`).
Flask-Admin will generate standard per-row actions (edit, delete, etc)
and will append custom actions from this list right after them.
For example::
from flask_admin.model.template import EndpointLinkRowAction, LinkRowAction
class MyModelView(BaseModelView):
column_extra_row_actions = [
LinkRowAction('glyphicon glyphicon-off', 'http://direct.link/?id={row_id}'),
EndpointLinkRowAction('glyphicon glyphicon-test', 'my_view.index_view')
]
"""
simple_list_pager = False
"""
Enable or disable simple list pager.
If enabled, model interface would not run count query and will only show prev/next pager buttons.
"""
form = None
"""
Form class. Override if you want to use custom form for your model.
Will completely disable form scaffolding functionality.
For example::
class MyForm(Form):
name = StringField('Name')
class MyModelView(BaseModelView):
form = MyForm
"""
form_base_class = BaseForm
"""
Base form class. Will be used by form scaffolding function when creating model form.
Useful if you want to have custom constructor or override some fields.
Example::
class MyBaseForm(Form):
def do_something(self):
pass
class MyModelView(BaseModelView):
form_base_class = MyBaseForm
"""
form_args = None
"""
Dictionary of form field arguments. Refer to WTForms documentation for
list of possible options.
Example::
from wtforms.validators import DataRequired
class MyModelView(BaseModelView):
form_args = dict(
name=dict(label='First Name', validators=[DataRequired()])
)
"""
form_columns = None
"""
Collection of the model field names for the form. If set to `None` will
get them from the model.
Example::
class MyModelView(BaseModelView):
form_columns = ('name', 'email')
(Added in 1.4.0) SQLAlchemy model attributes can be used instead of
strings::
class MyModelView(BaseModelView):
form_columns = ('name', User.last_name)
SQLA Note: Model attributes must be on the same model as your ModelView
or you will need to use `inline_models`.
"""
form_excluded_columns = ObsoleteAttr('form_excluded_columns',
'excluded_form_columns',
None)
"""
Collection of excluded form field names.
For example::
class MyModelView(BaseModelView):
form_excluded_columns = ('last_name', 'email')
"""
form_overrides = None
"""
Dictionary of form column overrides.
Example::
class MyModelView(BaseModelView):
form_overrides = dict(name=wtf.FileField)
"""
form_widget_args = None
"""
Dictionary of form widget rendering arguments.
Use this to customize how widget is rendered without using custom template.
Example::
class MyModelView(BaseModelView):
form_widget_args = {
'description': {
'rows': 10,
'style': 'color: black'
},
'other_field': {
'disabled': True
}
}
Changing the format of a DateTimeField will require changes to both form_widget_args and form_args.
Example::
form_args = dict(
start=dict(format='%Y-%m-%d %I:%M %p') # changes how the input is parsed by strptime (12 hour time)
)
form_widget_args = dict(
start={'data-date-format': u'yyyy-mm-dd HH:ii P', 'data-show-meridian': 'True'} # changes how the DateTimeField displays the time
)
"""
form_extra_fields = None
"""
Dictionary of additional fields.
Example::
class MyModelView(BaseModelView):
form_extra_fields = {
'password': PasswordField('Password')
}
You can control order of form fields using ``form_columns`` property. For example::
class MyModelView(BaseModelView):
form_columns = ('name', 'email', 'password', 'secret')
form_extra_fields = {
'password': PasswordField('Password')
}
In this case, password field will be put between email and secret fields that are autogenerated.
"""
form_ajax_refs = None
"""
Use AJAX for foreign key model loading.
Should contain dictionary, where key is field name and value is either a dictionary which
configures AJAX lookups or backend-specific `AjaxModelLoader` class instance.
For example, it can look like::
class MyModelView(BaseModelView):
form_ajax_refs = {
'user': {
'fields': ('first_name', 'last_name', 'email'),
'page_size': 10
}
}
Or with SQLAlchemy backend like this::
class MyModelView(BaseModelView):
form_ajax_refs = {
'user': QueryAjaxModelLoader('user', db.session, User, fields=['email'], page_size=10)
}
If you need custom loading functionality, you can implement your custom loading behavior
in your `AjaxModelLoader` class.
"""
form_rules = None
"""
List of rendering rules for model creation form.
This property changed default form rendering behavior and makes possible to rearrange order
of rendered fields, add some text between fields, group them, etc. If not set, will use
default Flask-Admin form rendering logic.
Here's simple example which illustrates how to use::
from flask_admin.form import rules
class MyModelView(ModelView):
form_rules = [
# Define field set with header text and four fields
rules.FieldSet(('first_name', 'last_name', 'email', 'phone'), 'User'),
# ... and it is just shortcut for:
rules.Header('User'),
rules.Field('first_name'),
rules.Field('last_name'),
# ...
# It is possible to create custom rule blocks:
MyBlock('Hello World'),
# It is possible to call macros from current context
rules.Macro('my_macro', foobar='baz')
]
"""
form_edit_rules = None
"""
Customized rules for the edit form. Override `form_rules` if present.
"""
form_create_rules = None
"""
Customized rules for the create form. Override `form_rules` if present.
"""
# Actions
action_disallowed_list = ObsoleteAttr('action_disallowed_list',
'disallowed_actions',
[])
"""
Set of disallowed action names. For example, if you want to disable
mass model deletion, do something like this:
class MyModelView(BaseModelView):
action_disallowed_list = ['delete']
"""
# Export settings
export_max_rows = 0
"""
Maximum number of rows allowed for export.
Unlimited by default. Uses `page_size` if set to `None`.
"""
export_types = ['csv']
"""
A list of available export filetypes. `csv` only is default, but any
filetypes supported by tablib can be used.
Check tablib for https://github.com/kennethreitz/tablib/blob/master/README.rst
for supported types.
"""
# Various settings
page_size = 20
"""
Default page size for pagination.
"""
def __init__(self, model,
name=None, category=None, endpoint=None, url=None, static_folder=None,
menu_class_name=None, menu_icon_type=None, menu_icon_value=None):
"""
Constructor.
:param model:
Model class
:param name:
View name. If not provided, will use the model class name
:param category:
View category
:param endpoint:
Base endpoint. If not provided, will use the model name.
:param url:
Base URL. If not provided, will use endpoint as a URL.
:param menu_class_name:
Optional class name for the menu item.
:param menu_icon_type:
Optional icon. Possible icon types:
- `flask_admin.consts.ICON_TYPE_GLYPH` - Bootstrap glyph icon
- `flask_admin.consts.ICON_TYPE_FONT_AWESOME` - Font Awesome icon
- `flask_admin.consts.ICON_TYPE_IMAGE` - Image relative to Flask static directory
- `flask_admin.consts.ICON_TYPE_IMAGE_URL` - Image with full URL
:param menu_icon_value:
Icon glyph name or URL, depending on `menu_icon_type` setting
"""
self.model = model
# If name not provided, it is model name
if name is None:
name = '%s' % self._prettify_class_name(model.__name__)
super(BaseModelView, self).__init__(name, category, endpoint, url, static_folder,
menu_class_name=menu_class_name,
menu_icon_type=menu_icon_type,
menu_icon_value=menu_icon_value)
# Actions
self.init_actions()
# Scaffolding
self._refresh_cache()
# Endpoint
def _get_endpoint(self, endpoint):
if endpoint:
return super(BaseModelView, self)._get_endpoint(endpoint)
return self.model.__name__.lower()
# Caching
def _refresh_forms_cache(self):
# Forms
self._form_ajax_refs = self._process_ajax_references()
if self.form_widget_args is None:
self.form_widget_args = {}
self._create_form_class = self.get_create_form()
self._edit_form_class = self.get_edit_form()
self._delete_form_class = self.get_delete_form()
# List View In-Line Editing
if self.column_editable_list:
self._list_form_class = self.get_list_form()
else:
self.column_editable_list = {}
def _refresh_filters_cache(self):
self._filters = self.get_filters()
if self._filters:
self._filter_groups = OrderedDict()
self._filter_args = {}
for i, flt in enumerate(self._filters):
key = as_unicode(flt.name)
if key not in self._filter_groups:
self._filter_groups[key] = FilterGroup(flt.name)
self._filter_groups[key].append({
'index': i,
'arg': self.get_filter_arg(i, flt),
'operation': flt.operation(),
'options': flt.get_options(self) or None,
'type': flt.data_type
})
self._filter_args[self.get_filter_arg(i, flt)] = (i, flt)
else:
self._filter_groups = None
self._filter_args = None
def _refresh_form_rules_cache(self):
if self.form_create_rules:
self._form_create_rules = rules.RuleSet(self, self.form_create_rules)
else:
self._form_create_rules = None
if self.form_edit_rules:
self._form_edit_rules = rules.RuleSet(self, self.form_edit_rules)
else:
self._form_edit_rules = None
if self.form_rules:
form_rules = rules.RuleSet(self, self.form_rules)
if not self._form_create_rules:
self._form_create_rules = form_rules
if not self._form_edit_rules:
self._form_edit_rules = form_rules
def _refresh_cache(self):
"""
Refresh various cached variables.
"""
# List view
self._list_columns = self.get_list_columns()
self._sortable_columns = self.get_sortable_columns()
# Details view
self._details_columns = self.get_details_columns()
# Export view
self._export_columns = self.get_export_columns()
# Labels
if self.column_labels is None:
self.column_labels = {}
# Forms
self._refresh_forms_cache()
# Search
self._search_supported = self.init_search()
# Choices
if self.column_choices:
self._column_choices_map = dict([
(column, dict(choices))
for column, choices in self.column_choices.items()
])
else:
self.column_choices = self._column_choices_map = dict()
# Column formatters
if self.column_formatters_export is None:
self.column_formatters_export = self.column_formatters
# Type formatters
if self.column_type_formatters is None:
self.column_type_formatters = dict(typefmt.BASE_FORMATTERS)
if self.column_type_formatters_export is None:
self.column_type_formatters_export = dict(typefmt.EXPORT_FORMATTERS)
if self.column_descriptions is None:
self.column_descriptions = dict()
# Filters
self._refresh_filters_cache()
# Form rendering rules
self._refresh_form_rules_cache()
# Process form rules
self._validate_form_class(self._form_edit_rules, self._edit_form_class)
self._validate_form_class(self._form_create_rules, self._create_form_class)
# Primary key
def get_pk_value(self, model):
"""
Return PK value from a model object.
"""
raise NotImplementedError()
# List view
def scaffold_list_columns(self):
"""
Return list of the model field names. Must be implemented in
the child class.
Expected return format is list of tuples with field name and
display text. For example::
['name', 'first_name', 'last_name']
"""
raise NotImplementedError('Please implement scaffold_list_columns method')
def get_column_name(self, field):
"""
Return a human-readable column name.
:param field:
Model field name.
"""
if self.column_labels and field in self.column_labels:
return self.column_labels[field]
else:
return self._prettify_name(field)
def get_list_row_actions(self):
"""
Return list of row action objects, each is instance of :class:`~flask_admin.model.template.BaseListRowAction`
"""
actions = []
if self.can_view_details:
if self.details_modal:
actions.append(template.ViewPopupRowAction())
else:
actions.append(template.ViewRowAction())
if self.can_edit:
if self.edit_modal:
actions.append(template.EditPopupRowAction())
else:
actions.append(template.EditRowAction())
if self.can_delete:
actions.append(template.DeleteRowAction())
return actions + (self.column_extra_row_actions or [])
def get_column_names(self, only_columns, excluded_columns):
"""
Returns a list of tuples with the model field name and formatted
field name.
:param only_columns:
List of columns to include in the results. If not set,
`scaffold_list_columns` will generate the list from the model.
:param excluded_columns:
List of columns to exclude from the results if `only_columns`
is not set.
"""
if excluded_columns:
only_columns = [c for c in only_columns if c not in excluded_columns]
return [(c, self.get_column_name(c)) for c in only_columns]
def get_list_columns(self):
"""
Uses `get_column_names` to get a list of tuples with the model
field name and formatted name for the columns in `column_list`
and not in `column_exclude_list`. If `column_list` is not set,
the columns from `scaffold_list_columns` will be used.
"""
return self.get_column_names(
only_columns=self.column_list or self.scaffold_list_columns(),
excluded_columns=self.column_exclude_list,
)
def get_details_columns(self):
"""
Uses `get_column_names` to get a list of tuples with the model
field name and formatted name for the columns in `column_details_list`
and not in `column_details_exclude_list`. If `column_details_list`
is not set, it will attempt to use the columns from `column_list`
or finally the columns from `scaffold_list_columns` will be used.
"""
only_columns = (self.column_details_list or self.column_list or
self.scaffold_list_columns())
return self.get_column_names(
only_columns=only_columns,
excluded_columns=self.column_details_exclude_list,
)
def get_export_columns(self):
"""
Uses `get_column_names` to get a list of tuples with the model
field name and formatted name for the columns in `column_export_list`
and not in `column_export_exclude_list`. If `column_export_list` is
not set, it will attempt to use the columns from `column_list`
or finally the columns from `scaffold_list_columns` will be used.
"""
only_columns = (self.column_export_list or self.column_list or
self.scaffold_list_columns())
return self.get_column_names(
only_columns=only_columns,
excluded_columns=self.column_export_exclude_list,
)
def scaffold_sortable_columns(self):
"""
Returns dictionary of sortable columns. Must be implemented in
the child class.
Expected return format is a dictionary, where keys are field names and
values are property names.
"""
raise NotImplementedError('Please implement scaffold_sortable_columns method')
def get_sortable_columns(self):
"""
Returns a dictionary of the sortable columns. Key is a model
field name and value is sort column (for example - attribute).
If `column_sortable_list` is set, will use it. Otherwise, will call
`scaffold_sortable_columns` to get them from the model.
"""
if self.column_sortable_list is None:
return self.scaffold_sortable_columns() or dict()
else:
result = dict()
for c in self.column_sortable_list:
if isinstance(c, tuple):
result[c[0]] = c[1]
else:
result[c] = c
return result
def init_search(self):
"""
Initialize search. If data provider does not support search,
`init_search` will return `False`.
"""
return False
# Filter helpers
def scaffold_filters(self, name):
"""
Generate filter object for the given name
:param name:
Name of the field
"""
return None
def is_valid_filter(self, filter):
"""
Verify that the provided filter object is valid.
Override in model backend implementation to verify if
the provided filter type is allowed.
:param filter:
Filter object to verify.
"""
return isinstance(filter, filters.BaseFilter)
def handle_filter(self, filter):
"""
Postprocess (add joins, etc) for a filter.
:param filter:
Filter object to postprocess
"""
return filter
def get_filters(self):
"""
Return a list of filter objects.
If your model backend implementation does not support filters,
override this method and return `None`.
"""
if self.column_filters:
collection = []
for n in self.column_filters:
if self.is_valid_filter(n):
collection.append(self.handle_filter(n))
else:
flt = self.scaffold_filters(n)
if flt:
collection.extend(flt)
else:
raise Exception('Unsupported filter type %s' % n)
return collection
else:
return None
def get_filter_arg(self, index, flt):
"""
Given a filter `flt`, return a unique name for that filter in
this view.
Does not include the `flt[n]_` portion of the filter name.
:param index:
Filter index in _filters array
:param flt:
Filter instance
"""
if self.named_filter_urls:
name = ('%s %s' % (flt.name, as_unicode(flt.operation()))).lower()
name = filter_char_re.sub('', name)
name = filter_compact_re.sub('_', name)
return name
else:
return str(index)
def _get_filter_groups(self):
"""
Returns non-lazy version of filter strings
"""
if self._filter_groups:
results = OrderedDict()
for group in itervalues(self._filter_groups):
key, items = group.non_lazy()
results[key] = items
return results
return None
# Form helpers
def scaffold_form(self):
"""
Create `form.BaseForm` inherited class from the model. Must be
implemented in the child class.
"""
raise NotImplementedError('Please implement scaffold_form method')
def scaffold_list_form(self, widget=None, validators=None):
"""
Create form for the `index_view` using only the columns from
`self.column_editable_list`.
:param widget:
WTForms widget class. Defaults to `XEditableWidget`.
:param validators:
`form_args` dict with only validators
{'name': {'validators': [DataRequired()]}}
Must be implemented in the child class.
"""
raise NotImplementedError('Please implement scaffold_list_form method')
def get_form(self):
"""
Get form class.
If ``self.form`` is set, will return it and will call
``self.scaffold_form`` otherwise.
Override to implement customized behavior.
"""
if self.form is not None:
return self.form
return self.scaffold_form()
def get_list_form(self):
"""
Get form class for the editable list view.
Uses only validators from `form_args` to build the form class.
Allows overriding the editable list view field/widget. For example::
from flask_admin.model.widgets import XEditableWidget
class CustomWidget(XEditableWidget):
def get_kwargs(self, subfield, kwargs):
if subfield.type == 'TextAreaField':
kwargs['data-type'] = 'textarea'
kwargs['data-rows'] = '20'
# elif: kwargs for other fields
return kwargs
class MyModelView(BaseModelView):
def get_list_form(self):
return self.scaffold_list_form(widget=CustomWidget)
"""
if self.form_args:
# get only validators, other form_args can break FieldList wrapper
validators = dict(
(key, {'validators': value["validators"]})
for key, value in iteritems(self.form_args)
if value.get("validators")
)
else:
validators = None
return self.scaffold_list_form(validators=validators)
def get_create_form(self):
"""
Create form class for model creation view.
Override to implement customized behavior.
"""
return self.get_form()
def get_edit_form(self):
"""
Create form class for model editing view.
Override to implement customized behavior.
"""
return self.get_form()
def get_delete_form(self):
"""
Create form class for model delete view.
Override to implement customized behavior.
"""
class DeleteForm(self.form_base_class):
id = HiddenField(validators=[InputRequired()])
url = HiddenField()
return DeleteForm
def create_form(self, obj=None):
"""
Instantiate model creation form and return it.
Override to implement custom behavior.
"""
return self._create_form_class(get_form_data(), obj=obj)
def edit_form(self, obj=None):
"""
Instantiate model editing form and return it.
Override to implement custom behavior.
"""
return self._edit_form_class(get_form_data(), obj=obj)
def delete_form(self):
"""
Instantiate model delete form and return it.
Override to implement custom behavior.
The delete form originally used a GET request, so delete_form
accepts both GET and POST request for backwards compatibility.
"""
if request.form:
return self._delete_form_class(request.form)
elif request.args:
# allow request.args for backward compatibility
return self._delete_form_class(request.args)
else:
return self._delete_form_class()
def list_form(self, obj=None):
"""
Instantiate model editing form for list view and return it.
Override to implement custom behavior.
"""
return self._list_form_class(get_form_data(), obj=obj)
def validate_form(self, form):
"""
Validate the form on submit.
:param form:
Form to validate
"""
return validate_form_on_submit(form)
def get_save_return_url(self, model, is_created=False):
"""
Return url where user is redirected after successful form save.
:param model:
Saved object
:param is_created:
Whether new object was created or existing one was updated
For example, redirect use to object details view after form save::
class MyModelView(ModelView):
can_view_details = True
def get_save_return_url(self, model, is_created):
return self.get_url('.details_view', id=model.id)
"""
return get_redirect_target() or self.get_url('.index_view')
def _get_ruleset_missing_fields(self, ruleset, form):
missing_fields = []
if ruleset:
visible_fields = ruleset.visible_fields
for field in form:
if field.name not in visible_fields:
missing_fields.append(field.name)
return missing_fields
def _show_missing_fields_warning(self, text):
warnings.warn(text)
def _validate_form_class(self, ruleset, form_class, remove_missing=True):
form_fields = []
for name, obj in iteritems(form_class.__dict__):
if isinstance(obj, UnboundField):
form_fields.append(name)
missing_fields = []
if ruleset:
visible_fields = ruleset.visible_fields
for field_name in form_fields:
if field_name not in visible_fields:
missing_fields.append(field_name)
if missing_fields:
self._show_missing_fields_warning('Fields missing from ruleset: %s' % (','.join(missing_fields)))
if remove_missing:
self._remove_fields_from_form_class(missing_fields, form_class)
def _validate_form_instance(self, ruleset, form, remove_missing=True):
missing_fields = self._get_ruleset_missing_fields(ruleset=ruleset, form=form)
if missing_fields:
self._show_missing_fields_warning('Fields missing from ruleset: %s' % (','.join(missing_fields)))
if remove_missing:
self._remove_fields_from_form_instance(missing_fields, form)
def _remove_fields_from_form_instance(self, field_names, form):
for field_name in field_names:
form.__delitem__(field_name)
def _remove_fields_from_form_class(self, field_names, form_class):
for field_name in field_names:
delattr(form_class, field_name)
# Helpers
def is_sortable(self, name):
"""
Verify if column is sortable.
Not case-sensitive.
:param name:
Column name.
"""
return name.lower() in (x.lower() for x in self._sortable_columns)
def is_editable(self, name):
"""
Verify if column is editable.
:param name:
Column name.
"""
return name in self.column_editable_list
def _get_column_by_idx(self, idx):
"""
Return column index by
"""
if idx is None or idx < 0 or idx >= len(self._list_columns):
return None
return self._list_columns[idx]
def _get_default_order(self):
"""
Return default sort order
"""
if self.column_default_sort:
if isinstance(self.column_default_sort, tuple):
return self.column_default_sort
else:
return self.column_default_sort, False
return None
# Database-related API
def get_list(self, page, sort_field, sort_desc, search, filters,
page_size=None):
"""
Return a paginated and sorted list of models from the data source.
Must be implemented in the child class.
:param page:
Page number, 0 based. Can be set to None if it is first page.
:param sort_field:
Sort column name or None.
:param sort_desc:
If set to True, sorting is in descending order.
:param search:
Search query
:param filters:
List of filter tuples. First value in a tuple is a search
index, second value is a search value.
:param page_size:
Number of results. Defaults to ModelView's page_size. Can be
overriden to change the page_size limit. Removing the page_size
limit requires setting page_size to 0 or False.
"""
raise NotImplementedError('Please implement get_list method')
def get_one(self, id):
"""
Return one model by its id.
Must be implemented in the child class.
:param id:
Model id
"""
raise NotImplementedError('Please implement get_one method')
# Exception handler
def handle_view_exception(self, exc):
if isinstance(exc, ValidationError):
flash(as_unicode(exc))
return True
if self._debug:
raise
return False
# Model event handlers
def on_model_change(self, form, model, is_created):
"""
Perform some actions before a model is created or updated.
Called from create_model and update_model in the same transaction
(if it has any meaning for a store backend).
By default does nothing.
:param form:
Form used to create/update model
:param model:
Model that will be created/updated
:param is_created:
Will be set to True if model was created and to False if edited
"""
pass
def _on_model_change(self, form, model, is_created):
"""
Compatibility helper.
"""
try:
self.on_model_change(form, model, is_created)
except TypeError:
msg = ('%s.on_model_change() now accepts third ' +
'parameter is_created. Please update your code') % self.model
warnings.warn(msg)
self.on_model_change(form, model)
def after_model_change(self, form, model, is_created):
"""
Perform some actions after a model was created or updated and
committed to the database.
Called from create_model after successful database commit.
By default does nothing.
:param form:
Form used to create/update model
:param model:
Model that was created/updated
:param is_created:
True if model was created, False if model was updated
"""
pass
def on_model_delete(self, model):
"""
Perform some actions before a model is deleted.
Called from delete_model in the same transaction
(if it has any meaning for a store backend).
By default do nothing.
"""
pass
def after_model_delete(self, model):
"""
Perform some actions after a model was deleted and
committed to the database.
Called from delete_model after successful database commit
(if it has any meaning for a store backend).
By default does nothing.
:param model:
Model that was deleted
"""
pass
def on_form_prefill (self, form, id):
"""
Perform additional actions to pre-fill the edit form.
Called from edit_view, if the current action is rendering
the form rather than receiving client side input, after
default pre-filling has been performed.
By default does nothing.
You only need to override this if you have added custom
fields that depend on the database contents in a way that
Flask-admin can't figure out by itself. Fields that were
added by name of a normal column or relationship should
work out of the box.
:param form:
Form instance
:param id:
id of the object that is going to be edited
"""
pass
def create_model(self, form):
"""
Create model from the form.
Returns the model instance if operation succeeded.
Must be implemented in the child class.
:param form:
Form instance
"""
raise NotImplementedError()
def update_model(self, form, model):
"""
Update model from the form.
Returns `True` if operation succeeded.
Must be implemented in the child class.
:param form:
Form instance
:param model:
Model instance
"""
raise NotImplementedError()
def delete_model(self, model):
"""
Delete model.
Returns `True` if operation succeeded.
Must be implemented in the child class.
:param model:
Model instance
"""
raise NotImplementedError()
# Various helpers
def _prettify_name(self, name):
"""
Prettify pythonic variable name.
For example, 'hello_world' will be converted to 'Hello World'
:param name:
Name to prettify
"""
return prettify_name(name)
def get_empty_list_message(self):
return gettext('There are no items in the table.')
# URL generation helpers
def _get_list_filter_args(self):
if self._filters:
filters = []
for n in request.args:
if not n.startswith('flt'):
continue
if '_' not in n:
continue
pos, key = n[3:].split('_', 1)
if key in self._filter_args:
idx, flt = self._filter_args[key]
value = request.args[n]
if flt.validate(value):
filters.append((pos, (idx, as_unicode(flt.name), value)))
else:
flash(gettext('Invalid Filter Value: %(value)s', value=value))
# Sort filters
return [v[1] for v in sorted(filters, key=lambda n: n[0])]
return None
def _get_list_extra_args(self):
"""
Return arguments from query string.
"""
return ViewArgs(page=request.args.get('page', 0, type=int),
sort=request.args.get('sort', None, type=int),
sort_desc=request.args.get('desc', None, type=int),
search=request.args.get('search', None),
filters=self._get_list_filter_args())
# URL generation helpers
def _get_list_url(self, view_args):
"""
Generate page URL with current page, sort column and
other parameters.
:param view:
View name
:param view_args:
ViewArgs object with page number, filters, etc.
"""
page = view_args.page or None
desc = 1 if view_args.sort_desc else None
kwargs = dict(page=page, sort=view_args.sort, desc=desc, search=view_args.search)
kwargs.update(view_args.extra_args)
if view_args.filters:
for i, pair in enumerate(view_args.filters):
idx, flt_name, value = pair
key = 'flt%d_%s' % (i, self.get_filter_arg(idx, self._filters[idx]))
kwargs[key] = value
return self.get_url('.index_view', **kwargs)
# Actions
def is_action_allowed(self, name):
"""
Override this method to allow or disallow actions based
on some condition.
The default implementation only checks if the particular action
is not in `action_disallowed_list`.
"""
return name not in self.action_disallowed_list
def _get_field_value(self, model, name):
"""
Get unformatted field value from the model
"""
return rec_getattr(model, name)
def _get_list_value(self, context, model, name, column_formatters,
column_type_formatters):
"""
Returns the value to be displayed.
:param context:
:py:class:`jinja2.runtime.Context` if available
:param model:
Model instance
:param name:
Field name
:param column_formatters:
column_formatters to be used.
:param column_type_formatters:
column_type_formatters to be used.
"""
column_fmt = column_formatters.get(name)
if column_fmt is not None:
value = column_fmt(self, context, model, name)
else:
value = self._get_field_value(model, name)
choices_map = self._column_choices_map.get(name, {})
if choices_map:
return choices_map.get(value) or value
type_fmt = None
for typeobj, formatter in column_type_formatters.items():
if isinstance(value, typeobj):
type_fmt = formatter
break
if type_fmt is not None:
value = type_fmt(self, value)
return value
@contextfunction
def get_list_value(self, context, model, name):
"""
Returns the value to be displayed in the list view
:param context:
:py:class:`jinja2.runtime.Context`
:param model:
Model instance
:param name:
Field name
"""
return self._get_list_value(
context,
model,
name,
self.column_formatters,
self.column_type_formatters,
)
def get_export_value(self, model, name):
"""
Returns the value to be displayed in export.
Allows export to use different (non HTML) formatters.
:param model:
Model instance
:param name:
Field name
"""
return self._get_list_value(
None,
model,
name,
self.column_formatters_export,
self.column_type_formatters_export,
)
def get_export_name(self, export_type='csv'):
"""
:return: The exported csv file name.
"""
filename = '%s_%s.%s' % (self.name,
time.strftime("%Y-%m-%d_%H-%M-%S"),
export_type)
return filename
# AJAX references
def _process_ajax_references(self):
"""
Process `form_ajax_refs` and generate model loaders that
will be used by the `ajax_lookup` view.
"""
result = {}
if self.form_ajax_refs:
for name, options in iteritems(self.form_ajax_refs):
if isinstance(options, dict):
result[name] = self._create_ajax_loader(name, options)
elif isinstance(options, AjaxModelLoader):
result[name] = options
else:
raise ValueError('%s.form_ajax_refs can not handle %s types' % (self, type(options)))
return result
def _create_ajax_loader(self, name, options):
"""
Model backend will override this to implement AJAX model loading.
"""
raise NotImplementedError()
# Views
@expose('/')
def index_view(self):
"""
List view
"""
if self.can_delete:
delete_form = self.delete_form()
else:
delete_form = None
# Grab parameters from URL
view_args = self._get_list_extra_args()
# Map column index to column name
sort_column = self._get_column_by_idx(view_args.sort)
if sort_column is not None:
sort_column = sort_column[0]
# Get count and data
count, data = self.get_list(view_args.page, sort_column, view_args.sort_desc,
view_args.search, view_args.filters)
list_forms = {}
if self.column_editable_list:
for row in data:
list_forms[self.get_pk_value(row)] = self.list_form(obj=row)
# Calculate number of pages
if count is not None and self.page_size:
num_pages = int(ceil(count / float(self.page_size)))
elif not self.page_size:
num_pages = 0 # hide pager for unlimited page_size
else:
num_pages = None # use simple pager
# Various URL generation helpers
def pager_url(p):
# Do not add page number if it is first page
if p == 0:
p = None
return self._get_list_url(view_args.clone(page=p))
def sort_url(column, invert=False):
desc = None
if invert and not view_args.sort_desc:
desc = 1
return self._get_list_url(view_args.clone(sort=column, sort_desc=desc))
# Actions
actions, actions_confirmation = self.get_actions_list()
clear_search_url = self._get_list_url(view_args.clone(page=0,
sort=view_args.sort,
sort_desc=view_args.sort_desc,
search=None,
filters=None))
return self.render(
self.list_template,
data=data,
list_forms=list_forms,
delete_form=delete_form,
# List
list_columns=self._list_columns,
sortable_columns=self._sortable_columns,
editable_columns=self.column_editable_list,
list_row_actions=self.get_list_row_actions(),
# Pagination
count=count,
pager_url=pager_url,
num_pages=num_pages,
page=view_args.page,
page_size=self.page_size,
# Sorting
sort_column=view_args.sort,
sort_desc=view_args.sort_desc,
sort_url=sort_url,
# Search
search_supported=self._search_supported,
clear_search_url=clear_search_url,
search=view_args.search,
# Filters
filters=self._filters,
filter_groups=self._get_filter_groups(),
active_filters=view_args.filters,
# Actions
actions=actions,
actions_confirmation=actions_confirmation,
# Misc
enumerate=enumerate,
get_pk_value=self.get_pk_value,
get_value=self.get_list_value,
return_url=self._get_list_url(view_args),
)
@expose('/new/', methods=('GET', 'POST'))
def create_view(self):
"""
Create model view
"""
return_url = get_redirect_target() or self.get_url('.index_view')
if not self.can_create:
return redirect(return_url)
form = self.create_form()
if not hasattr(form, '_validated_ruleset') or not form._validated_ruleset:
self._validate_form_instance(ruleset=self._form_create_rules, form=form)
if self.validate_form(form):
# in versions 1.1.0 and before, this returns a boolean
# in later versions, this is the model itself
model = self.create_model(form)
if model:
flash(gettext('Record was successfully created.'))
if '_add_another' in request.form:
return redirect(request.url)
elif '_continue_editing' in request.form:
# if we have a valid model, try to go to the edit view
if model is not True:
url = self.get_url('.edit_view', id=self.get_pk_value(model), url=return_url)
else:
url = return_url
return redirect(url)
else:
# save button
return redirect(self.get_save_return_url(model, is_created=True))
form_opts = FormOpts(widget_args=self.form_widget_args,
form_rules=self._form_create_rules)
if self.create_modal and request.args.get('modal'):
template = self.create_modal_template
else:
template = self.create_template
return self.render(template,
form=form,
form_opts=form_opts,
return_url=return_url)
@expose('/edit/', methods=('GET', 'POST'))
def edit_view(self):
"""
Edit model view
"""
return_url = get_redirect_target() or self.get_url('.index_view')
if not self.can_edit:
return redirect(return_url)
id = get_mdict_item_or_list(request.args, 'id')
if id is None:
return redirect(return_url)
model = self.get_one(id)
if model is None:
flash(gettext('Record does not exist.'))
return redirect(return_url)
form = self.edit_form(obj=model)
if not hasattr(form, '_validated_ruleset') or not form._validated_ruleset:
self._validate_form_instance(ruleset=self._form_edit_rules, form=form)
if self.validate_form(form):
if self.update_model(form, model):
flash(gettext('Record was successfully saved.'))
if '_add_another' in request.form:
return redirect(self.get_url('.create_view', url=return_url))
elif '_continue_editing' in request.form:
return redirect(request.url)
else:
# save button
return redirect(self.get_save_return_url(model, is_created=False))
if request.method == 'GET':
self.on_form_prefill(form, id)
form_opts = FormOpts(widget_args=self.form_widget_args,
form_rules=self._form_edit_rules)
if self.edit_modal and request.args.get('modal'):
template = self.edit_modal_template
else:
template = self.edit_template
return self.render(template,
model=model,
form=form,
form_opts=form_opts,
return_url=return_url)
@expose('/details/')
def details_view(self):
"""
Details model view
"""
return_url = get_redirect_target() or self.get_url('.index_view')
if not self.can_view_details:
return redirect(return_url)
id = get_mdict_item_or_list(request.args, 'id')
if id is None:
return redirect(return_url)
model = self.get_one(id)
if model is None:
flash(gettext('Record does not exist.'))
return redirect(return_url)
if self.details_modal and request.args.get('modal'):
template = self.details_modal_template
else:
template = self.details_template
return self.render(template,
model=model,
details_columns=self._details_columns,
get_value=self.get_list_value,
return_url=return_url)
@expose('/delete/', methods=('POST',))
def delete_view(self):
"""
Delete model view. Only POST method is allowed.
"""
return_url = get_redirect_target() or self.get_url('.index_view')
if not self.can_delete:
return redirect(return_url)
form = self.delete_form()
if self.validate_form(form):
# id is InputRequired()
id = form.id.data
model = self.get_one(id)
if model is None:
flash(gettext('Record does not exist.'))
return redirect(return_url)
# message is flashed from within delete_model if it fails
if self.delete_model(model):
flash(gettext('Record was successfully deleted.'))
return redirect(return_url)
else:
flash_errors(form, message='Failed to delete record. %(error)s')
return redirect(return_url)
@expose('/action/', methods=('POST',))
def action_view(self):
"""
Mass-model action view.
"""
return self.handle_action()
def _export_data(self):
# Macros in column_formatters are not supported.
# Macros will have a function name 'inner'
# This causes non-macro functions named 'inner' not work.
for col, func in iteritems(self.column_formatters_export):
# skip checking columns not being exported
if col not in [col for col, _ in self._export_columns]:
continue
if func.__name__ == 'inner':
raise NotImplementedError(
'Macros are not implemented in export. Exclude column in'
' column_formatters_export, column_export_list, or '
' column_export_exclude_list. Column: %s' % (col,)
)
# Grab parameters from URL
view_args = self._get_list_extra_args()
# Map column index to column name
sort_column = self._get_column_by_idx(view_args.sort)
if sort_column is not None:
sort_column = sort_column[0]
# Get count and data
count, data = self.get_list(0, sort_column, view_args.sort_desc,
view_args.search, view_args.filters,
page_size=self.export_max_rows)
return count, data
@expose('/export/<export_type>/')
def export(self, export_type):
return_url = get_redirect_target() or self.get_url('.index_view')
if not self.can_export or (export_type not in self.export_types):
flash(gettext('Permission denied.'))
return redirect(return_url)
if export_type == 'csv':
return self._export_csv(return_url)
else:
return self._export_tablib(export_type, return_url)
def _export_csv(self, return_url):
"""
Export a CSV of records as a stream.
"""
count, data = self._export_data()
# https://docs.djangoproject.com/en/1.8/howto/outputting-csv/
class Echo(object):
"""
An object that implements just the write method of the file-like
interface.
"""
def write(self, value):
"""
Write the value by returning it, instead of storing
in a buffer.
"""
return value
writer = csv.writer(Echo())
def generate():
# Append the column titles at the beginning
titles = [csv_encode(c[1]) for c in self._export_columns]
yield writer.writerow(titles)
for row in data:
vals = [csv_encode(self.get_export_value(row, c[0]))
for c in self._export_columns]
yield writer.writerow(vals)
filename = self.get_export_name(export_type='csv')
disposition = 'attachment;filename=%s' % (secure_filename(filename),)
return Response(
stream_with_context(generate()),
headers={'Content-Disposition': disposition},
mimetype='text/csv'
)
def _export_tablib(self, export_type, return_url):
"""
Exports a variety of formats using the tablib library.
"""
if tablib is None:
flash(gettext('Tablib dependency not installed.'))
return redirect(return_url)
filename = self.get_export_name(export_type)
disposition = 'attachment;filename=%s' % (secure_filename(filename),)
mimetype, encoding = mimetypes.guess_type(filename)
if not mimetype:
mimetype = 'application/octet-stream'
if encoding:
mimetype = '%s; charset=%s' % (mimetype, encoding)
ds = tablib.Dataset(headers=[c[1] for c in self._export_columns])
count, data = self._export_data()
for row in data:
vals = [self.get_export_value(row, c[0]) for c in self._export_columns]
ds.append(vals)
try:
try:
response_data = ds.export(format=export_type)
except AttributeError:
response_data = getattr(ds, export_type)
except (AttributeError, tablib.UnsupportedFormat):
flash(gettext('Export type "%(type)s not supported.',
type=export_type))
return redirect(return_url)
return Response(
response_data,
headers={'Content-Disposition': disposition},
mimetype=mimetype,
)
@expose('/ajax/lookup/')
def ajax_lookup(self):
name = request.args.get('name')
query = request.args.get('query')
offset = request.args.get('offset', type=int)
limit = request.args.get('limit', 10, type=int)
loader = self._form_ajax_refs.get(name)
if not loader:
abort(404)
data = [loader.format(m) for m in loader.get_list(query, offset, limit)]
return Response(json.dumps(data), mimetype='application/json')
@expose('/ajax/update/', methods=('POST',))
def ajax_update(self):
"""
Edits a single column of a record in list view.
"""
if not self.column_editable_list:
abort(404)
form = self.list_form()
# prevent validation issues due to submitting a single field
# delete all fields except the submitted fields and csrf token
for field in list(form):
if (field.name in request.form) or (field.name == 'csrf_token'):
pass
else:
form.__delitem__(field.name)
if self.validate_form(form):
pk = form.list_form_pk.data
record = self.get_one(pk)
if record is None:
return gettext('Record does not exist.'), 500
if self.update_model(form, record):
# Success
return gettext('Record was successfully saved.')
else:
# Error: No records changed, or problem saving to database.
msgs = ", ".join([msg for msg in get_flashed_messages()])
return gettext('Failed to update record. %(error)s',
error=msgs), 500
else:
for field in form:
for error in field.errors:
# return validation error to x-editable
if isinstance(error, list):
return gettext('Failed to update record. %(error)s',
error=", ".join(error)), 500
else:
return gettext('Failed to update record. %(error)s',
error=error), 500
|
lombritz/odoo | refs/heads/8.0 | addons/analytic_user_function/analytic_user_function.py | 163 | # -*- 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/>.
#
##############################################################################
from openerp.osv import fields,osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
class analytic_user_funct_grid(osv.osv):
_name="analytic.user.funct.grid"
_description= "Price per User"
_rec_name="user_id"
_columns={
'user_id': fields.many2one("res.users", "User", required=True,),
'product_id': fields.many2one("product.product", "Service", required=True,),
'account_id': fields.many2one("account.analytic.account", "Analytic Account", required=True,),
'uom_id': fields.related("product_id", "uom_id", relation="product.uom", string="Unit of Measure", type="many2one", readonly=True),
'price': fields.float('Price', digits_compute=dp.get_precision('Product Price'), help="Price per hour for this user.", required=True),
}
def onchange_user_product_id(self, cr, uid, ids, user_id, product_id, context=None):
if not user_id:
return {}
emp_obj = self.pool.get('hr.employee')
emp_id = emp_obj.search(cr, uid, [('user_id', '=', user_id)], context=context)
if not emp_id:
return {}
value = {}
prod = False
if product_id:
prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
emp = emp_obj.browse(cr, uid, emp_id[0], context=context)
if emp.product_id and not product_id:
value['product_id'] = emp.product_id.id
prod = emp.product_id
if prod:
value['price'] = prod.list_price
value['uom_id'] = prod.uom_id.id
return {'value': value}
class account_analytic_account(osv.osv):
_inherit = "account.analytic.account"
_columns = {
'user_product_ids': fields.one2many('analytic.user.funct.grid', 'account_id', 'Users/Products Rel.', copy=True),
}
class hr_analytic_timesheet(osv.osv):
_inherit = "hr.analytic.timesheet"
# Look in account, if no value for the user => look in parent until there is no more parent to look
# Take the first found... if nothing found => return False
def _get_related_user_account_recursiv(self, cr, uid, user_id, account_id):
temp=self.pool.get('analytic.user.funct.grid').search(cr, uid, [('user_id', '=', user_id),('account_id', '=', account_id) ])
account=self.pool.get('account.analytic.account').browse(cr, uid, account_id)
if temp:
return temp
else:
if account.parent_id:
return self._get_related_user_account_recursiv(cr, uid, user_id, account.parent_id.id)
else:
return False
def on_change_account_id(self, cr, uid, ids, account_id, user_id=False, unit_amount=0):
res = {}
if not (account_id):
#avoid a useless call to super
return res
if not (user_id):
return super(hr_analytic_timesheet, self).on_change_account_id(cr, uid, ids, account_id)
#get the browse record related to user_id and account_id
temp = self._get_related_user_account_recursiv(cr, uid, user_id, account_id)
if not temp:
#if there isn't any record for this user_id and account_id
return super(hr_analytic_timesheet, self).on_change_account_id(cr, uid, ids, account_id)
else:
#get the old values from super and add the value from the new relation analytic_user_funct_grid
r = self.pool.get('analytic.user.funct.grid').browse(cr, uid, temp)[0]
res.setdefault('value',{})
res['value']= super(hr_analytic_timesheet, self).on_change_account_id(cr, uid, ids, account_id)['value']
res['value']['product_id'] = r.product_id.id
res['value']['product_uom_id'] = r.product_id.uom_id.id
#the change of product has to impact the amount, uom and general_account_id
a = r.product_id.property_account_expense.id
if not a:
a = r.product_id.categ_id.property_account_expense_categ.id
if not a:
raise osv.except_osv(_('Error!'),
_('There is no expense account defined ' \
'for this product: "%s" (id:%d)') % \
(r.product_id.name, r.product_id.id,))
# Compute based on pricetype
if unit_amount:
amount_unit = self.on_change_unit_amount(cr, uid, ids,
r.product_id.id, unit_amount, False, r.product_id.uom_id.id)['value']['amount']
amount = unit_amount * amount_unit
res ['value']['amount']= - round(amount, 2)
res ['value']['general_account_id']= a
return res
def on_change_user_id(self, cr, uid, ids, user_id, account_id, unit_amount=0):
res = super(hr_analytic_timesheet, self).on_change_user_id(cr, uid, ids, user_id)
if account_id:
#get the browse record related to user_id and account_id
temp = self._get_related_user_account_recursiv(cr, uid, user_id, account_id)
if temp:
#add the value from the new relation analytic_user_funct_grid
r = self.pool.get('analytic.user.funct.grid').browse(cr, uid, temp)[0]
res['value']['product_id'] = r.product_id.id
#the change of product has to impact the amount, uom and general_account_id
a = r.product_id.property_account_expense.id
if not a:
a = r.product_id.categ_id.property_account_expense_categ.id
if not a:
raise osv.except_osv(_('Error!'),
_('There is no expense account defined ' \
'for this product: "%s" (id:%d)') % \
(r.product_id.name, r.product_id.id,))
# Compute based on pricetype
if unit_amount:
amount_unit = self.on_change_unit_amount(cr, uid, ids,
r.product_id.id, unit_amount, False, r.product_id.uom_id.id)['value']['amount']
amount = unit_amount * amount_unit
res ['value']['amount']= - round(amount, 2)
res ['value']['general_account_id']= a
return res
class account_analytic_line(osv.osv):
_inherit = "account.analytic.line"
def _get_invoice_price(self, cr, uid, account, product_id, user_id, qty, context = {}):
for grid in account.user_product_ids:
if grid.user_id.id==user_id:
return grid.price
return super(account_analytic_line, self)._get_invoice_price(cr, uid, account, product_id, user_id, qty, context)
|
raviqqe/tensorflow-extenteten | refs/heads/master | extenteten/embedding/__init__.py | 1 | from .unidirectional import embeddings_to_embedding, id_vector_to_embedding
from .bidirectional import (bidirectional_embeddings_to_embedding,
bidirectional_id_vector_to_embedding,
bidirectional_id_vector_to_embeddings)
from .embeddings import embeddings
|
markherringer/waywayd | refs/heads/master | apps/flatpages/urls.py | 376 | from django.conf.urls.defaults import *
urlpatterns = patterns('django.contrib.flatpages.views',
(r'^(?P<url>.*)$', 'flatpage'),
)
|
Glasgow2015/team-10 | refs/heads/master | env/lib/python2.7/site-packages/setuptools/sandbox.py | 259 | import os
import sys
import tempfile
import operator
import functools
import itertools
import re
import contextlib
import pickle
import pkg_resources
if sys.platform.startswith('java'):
import org.python.modules.posix.PosixModule as _os
else:
_os = sys.modules[os.name]
try:
_file = file
except NameError:
_file = None
_open = open
from distutils.errors import DistutilsError
from pkg_resources import working_set
from setuptools import compat
from setuptools.compat import builtins
__all__ = [
"AbstractSandbox", "DirectorySandbox", "SandboxViolation", "run_setup",
]
def _execfile(filename, globals, locals=None):
"""
Python 3 implementation of execfile.
"""
mode = 'rb'
with open(filename, mode) as stream:
script = stream.read()
# compile() function in Python 2.6 and 3.1 requires LF line endings.
if sys.version_info[:2] < (2, 7) or sys.version_info[:2] >= (3, 0) and sys.version_info[:2] < (3, 2):
script = script.replace(b'\r\n', b'\n')
script = script.replace(b'\r', b'\n')
if locals is None:
locals = globals
code = compile(script, filename, 'exec')
exec(code, globals, locals)
@contextlib.contextmanager
def save_argv(repl=None):
saved = sys.argv[:]
if repl is not None:
sys.argv[:] = repl
try:
yield saved
finally:
sys.argv[:] = saved
@contextlib.contextmanager
def save_path():
saved = sys.path[:]
try:
yield saved
finally:
sys.path[:] = saved
@contextlib.contextmanager
def override_temp(replacement):
"""
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
"""
if not os.path.isdir(replacement):
os.makedirs(replacement)
saved = tempfile.tempdir
tempfile.tempdir = replacement
try:
yield
finally:
tempfile.tempdir = saved
@contextlib.contextmanager
def pushd(target):
saved = os.getcwd()
os.chdir(target)
try:
yield saved
finally:
os.chdir(saved)
class UnpickleableException(Exception):
"""
An exception representing another Exception that could not be pickled.
"""
@classmethod
def dump(cls, type, exc):
"""
Always return a dumped (pickled) type and exc. If exc can't be pickled,
wrap it in UnpickleableException first.
"""
try:
return pickle.dumps(type), pickle.dumps(exc)
except Exception:
return cls.dump(cls, cls(repr(exc)))
class ExceptionSaver:
"""
A Context Manager that will save an exception, serialized, and restore it
later.
"""
def __enter__(self):
return self
def __exit__(self, type, exc, tb):
if not exc:
return
# dump the exception
self._saved = UnpickleableException.dump(type, exc)
self._tb = tb
# suppress the exception
return True
def resume(self):
"restore and re-raise any exception"
if '_saved' not in vars(self):
return
type, exc = map(pickle.loads, self._saved)
compat.reraise(type, exc, self._tb)
@contextlib.contextmanager
def save_modules():
"""
Context in which imported modules are saved.
Translates exceptions internal to the context into the equivalent exception
outside the context.
"""
saved = sys.modules.copy()
with ExceptionSaver() as saved_exc:
yield saved
sys.modules.update(saved)
# remove any modules imported since
del_modules = (
mod_name for mod_name in sys.modules
if mod_name not in saved
# exclude any encodings modules. See #285
and not mod_name.startswith('encodings.')
)
_clear_modules(del_modules)
saved_exc.resume()
def _clear_modules(module_names):
for mod_name in list(module_names):
del sys.modules[mod_name]
@contextlib.contextmanager
def save_pkg_resources_state():
saved = pkg_resources.__getstate__()
try:
yield saved
finally:
pkg_resources.__setstate__(saved)
@contextlib.contextmanager
def setup_context(setup_dir):
temp_dir = os.path.join(setup_dir, 'temp')
with save_pkg_resources_state():
with save_modules():
hide_setuptools()
with save_path():
with save_argv():
with override_temp(temp_dir):
with pushd(setup_dir):
# ensure setuptools commands are available
__import__('setuptools')
yield
def _needs_hiding(mod_name):
"""
>>> _needs_hiding('setuptools')
True
>>> _needs_hiding('pkg_resources')
True
>>> _needs_hiding('setuptools_plugin')
False
>>> _needs_hiding('setuptools.__init__')
True
>>> _needs_hiding('distutils')
True
"""
pattern = re.compile('(setuptools|pkg_resources|distutils)(\.|$)')
return bool(pattern.match(mod_name))
def hide_setuptools():
"""
Remove references to setuptools' modules from sys.modules to allow the
invocation to import the most appropriate setuptools. This technique is
necessary to avoid issues such as #315 where setuptools upgrading itself
would fail to find a function declared in the metadata.
"""
modules = filter(_needs_hiding, sys.modules)
_clear_modules(modules)
def run_setup(setup_script, args):
"""Run a distutils setup script, sandboxed in its directory"""
setup_dir = os.path.abspath(os.path.dirname(setup_script))
with setup_context(setup_dir):
try:
sys.argv[:] = [setup_script]+list(args)
sys.path.insert(0, setup_dir)
# reset to include setup dir, w/clean callback list
working_set.__init__()
working_set.callbacks.append(lambda dist:dist.activate())
def runner():
ns = dict(__file__=setup_script, __name__='__main__')
_execfile(setup_script, ns)
DirectorySandbox(setup_dir).run(runner)
except SystemExit as v:
if v.args and v.args[0]:
raise
# Normal exit, just return
class AbstractSandbox:
"""Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
_active = False
def __init__(self):
self._attrs = [
name for name in dir(_os)
if not name.startswith('_') and hasattr(self,name)
]
def _copy(self, source):
for name in self._attrs:
setattr(os, name, getattr(source,name))
def run(self, func):
"""Run 'func' under os sandboxing"""
try:
self._copy(self)
if _file:
builtins.file = self._file
builtins.open = self._open
self._active = True
return func()
finally:
self._active = False
if _file:
builtins.file = _file
builtins.open = _open
self._copy(_os)
def _mk_dual_path_wrapper(name):
original = getattr(_os,name)
def wrap(self,src,dst,*args,**kw):
if self._active:
src,dst = self._remap_pair(name,src,dst,*args,**kw)
return original(src,dst,*args,**kw)
return wrap
for name in ["rename", "link", "symlink"]:
if hasattr(_os,name): locals()[name] = _mk_dual_path_wrapper(name)
def _mk_single_path_wrapper(name, original=None):
original = original or getattr(_os,name)
def wrap(self,path,*args,**kw):
if self._active:
path = self._remap_input(name,path,*args,**kw)
return original(path,*args,**kw)
return wrap
if _file:
_file = _mk_single_path_wrapper('file', _file)
_open = _mk_single_path_wrapper('open', _open)
for name in [
"stat", "listdir", "chdir", "open", "chmod", "chown", "mkdir",
"remove", "unlink", "rmdir", "utime", "lchown", "chroot", "lstat",
"startfile", "mkfifo", "mknod", "pathconf", "access"
]:
if hasattr(_os,name): locals()[name] = _mk_single_path_wrapper(name)
def _mk_single_with_return(name):
original = getattr(_os,name)
def wrap(self,path,*args,**kw):
if self._active:
path = self._remap_input(name,path,*args,**kw)
return self._remap_output(name, original(path,*args,**kw))
return original(path,*args,**kw)
return wrap
for name in ['readlink', 'tempnam']:
if hasattr(_os,name): locals()[name] = _mk_single_with_return(name)
def _mk_query(name):
original = getattr(_os,name)
def wrap(self,*args,**kw):
retval = original(*args,**kw)
if self._active:
return self._remap_output(name, retval)
return retval
return wrap
for name in ['getcwd', 'tmpnam']:
if hasattr(_os,name): locals()[name] = _mk_query(name)
def _validate_path(self,path):
"""Called to remap or validate any path, whether input or output"""
return path
def _remap_input(self,operation,path,*args,**kw):
"""Called for path inputs"""
return self._validate_path(path)
def _remap_output(self,operation,path):
"""Called for path outputs"""
return self._validate_path(path)
def _remap_pair(self,operation,src,dst,*args,**kw):
"""Called for path pairs like rename, link, and symlink operations"""
return (
self._remap_input(operation+'-from',src,*args,**kw),
self._remap_input(operation+'-to',dst,*args,**kw)
)
if hasattr(os, 'devnull'):
_EXCEPTIONS = [os.devnull,]
else:
_EXCEPTIONS = []
try:
from win32com.client.gencache import GetGeneratePath
_EXCEPTIONS.append(GetGeneratePath())
del GetGeneratePath
except ImportError:
# it appears pywin32 is not installed, so no need to exclude.
pass
class DirectorySandbox(AbstractSandbox):
"""Restrict operations to a single subdirectory - pseudo-chroot"""
write_ops = dict.fromkeys([
"open", "chmod", "chown", "mkdir", "remove", "unlink", "rmdir",
"utime", "lchown", "chroot", "mkfifo", "mknod", "tempnam",
])
_exception_patterns = [
# Allow lib2to3 to attempt to save a pickled grammar object (#121)
'.*lib2to3.*\.pickle$',
]
"exempt writing to paths that match the pattern"
def __init__(self, sandbox, exceptions=_EXCEPTIONS):
self._sandbox = os.path.normcase(os.path.realpath(sandbox))
self._prefix = os.path.join(self._sandbox,'')
self._exceptions = [
os.path.normcase(os.path.realpath(path))
for path in exceptions
]
AbstractSandbox.__init__(self)
def _violation(self, operation, *args, **kw):
raise SandboxViolation(operation, args, kw)
if _file:
def _file(self, path, mode='r', *args, **kw):
if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
self._violation("file", path, mode, *args, **kw)
return _file(path,mode,*args,**kw)
def _open(self, path, mode='r', *args, **kw):
if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
self._violation("open", path, mode, *args, **kw)
return _open(path,mode,*args,**kw)
def tmpnam(self):
self._violation("tmpnam")
def _ok(self, path):
active = self._active
try:
self._active = False
realpath = os.path.normcase(os.path.realpath(path))
return (
self._exempted(realpath)
or realpath == self._sandbox
or realpath.startswith(self._prefix)
)
finally:
self._active = active
def _exempted(self, filepath):
start_matches = (
filepath.startswith(exception)
for exception in self._exceptions
)
pattern_matches = (
re.match(pattern, filepath)
for pattern in self._exception_patterns
)
candidates = itertools.chain(start_matches, pattern_matches)
return any(candidates)
def _remap_input(self, operation, path, *args, **kw):
"""Called for path inputs"""
if operation in self.write_ops and not self._ok(path):
self._violation(operation, os.path.realpath(path), *args, **kw)
return path
def _remap_pair(self, operation, src, dst, *args, **kw):
"""Called for path pairs like rename, link, and symlink operations"""
if not self._ok(src) or not self._ok(dst):
self._violation(operation, src, dst, *args, **kw)
return (src,dst)
def open(self, file, flags, mode=0o777, *args, **kw):
"""Called for low-level os.open()"""
if flags & WRITE_FLAGS and not self._ok(file):
self._violation("os.open", file, flags, mode, *args, **kw)
return _os.open(file,flags,mode, *args, **kw)
WRITE_FLAGS = functools.reduce(
operator.or_, [getattr(_os, a, 0) for a in
"O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()]
)
class SandboxViolation(DistutilsError):
"""A setup script attempted to modify the filesystem outside the sandbox"""
def __str__(self):
return """SandboxViolation: %s%r %s
The package setup script has attempted to modify files on your system
that are not within the EasyInstall build area, and has been aborted.
This package cannot be safely installed by EasyInstall, and may not
support alternate installation locations even if you run its setup
script by hand. Please inform the package's author and the EasyInstall
maintainers to find out if a fix or workaround is available.""" % self.args
#
|
CatherineH/adolphus | refs/heads/master | demos/laserplan/pso.py | 2 | """\
Particle Swarm Optimization
@author: Aaron Mavrinac
@organization: University of Windsor
@contact: mavrin1@uwindsor.ca
@license: GPL-3
"""
import numpy
from random import uniform
class Particle(numpy.ndarray):
_gbest = None
_gbest_fitness = None
def __init__(self, *args):
self.velocity = numpy.ndarray(self.shape[0])
self._best = None
self._best_fitness = None
self.neighborhood = set()
@property
def best(self):
return (self._best, self._best_fitness)
@property
def nbest(self):
if not self.neighborhood:
return self.gbest
candidates = [particle.best for particle in self.neighborhood]
return max(candidates, key=lambda best: best[1])
@property
def gbest(self):
return (self.__class__._gbest, self.__class__._gbest_fitness)
def initialize(self, bounds, l=1.0):
for d in range(self.shape[0]):
self[d] = uniform(bounds[d][0], bounds[d][1])
span = bounds[d][1] - bounds[d][0]
vmax = l * span
self.velocity[d] = min(max(uniform(-span, span), -vmax), vmax)
def update(self, omega, phip, phin, constraint, bounds, l=1.0):
for d in range(self.shape[0]):
vmax = l * (bounds[d][1] - bounds[d][0])
self.velocity[d] = min(max(omega * self.velocity[d] \
+ uniform(0, phip) * (self.best[0][d] - self[d]) \
+ uniform(0, phin) * (self.nbest[0][d] - self[d]), -vmax), vmax)
self += self.velocity
constraint(self, bounds)
def update_best(self, fitness):
if fitness > self._best_fitness:
self._best = tuple(self)
self._best_fitness = fitness
if fitness > self.__class__._gbest_fitness:
self.__class__._gbest = tuple(self)
self.__class__._gbest_fitness = fitness
def norm_dist_to_gbest(self, bounds):
base = numpy.array([b[0] for b in bounds])
span = numpy.array([b[1] for b in bounds]) - base
center = (numpy.array(self.gbest[0]) - base) / span
norm = (self - base) / span
return numpy.linalg.norm(norm - center)
topologies = {None: lambda particles: None}
def topology(f):
topologies[f.__name__] = f
return f
@topology
def ring(particles):
for i, particle in enumerate(particles):
particle.neighborhood.add(particle)
particle.neighborhood.add(particles[i - 1])
particle.neighborhood.add(particles[(i + 1) % len(particles)])
@topology
def star(particles):
for particle in particles[1:]:
particle.neighborhood.add(particle)
particle.neighborhood.add(particles[0])
constraints = {None: lambda particle, bounds: None}
def constraint(f):
constraints[f.__name__] = f
return f
@constraint
def nearest(particle, bounds):
for d in range(particle.shape[0]):
particle[d] = max(particle[d], bounds[d][0])
particle[d] = min(particle[d], bounds[d][1])
@constraint
def random(particle, bounds):
for d in range(particle.shape[0]):
if particle[d] < bounds[d][0] or particle[d] > bounds[d][1]:
particle[d] = uniform(bounds[d][0], bounds[d][1])
def particle_swarm_optimize(fitness, dimension, bounds, size, omega, phip, phin,
clamp=1.0, it=None, af=float('inf'), cluster=(1.0,
0.0), topology_type=None, constraint_type=None):
particles = [Particle(dimension) for i in range(size)]
topologies[topology_type](particles)
for particle in particles:
particle.initialize(bounds, l=clamp)
i = 0
while not it or i < it:
for particle in particles:
particle.update_best(fitness(particle))
yield particles[0].gbest
if particles[0].gbest[1] >= af and \
(particles[0].gbest[2] == -float('inf') \
or particles[0].gbest[2] >= af):
break
if sum([particle.norm_dist_to_gbest(bounds) < cluster[1] \
for particle in particles]) >= int(cluster[0] * size):
break
for particle in particles:
particle.update(omega, phip, phin, constraints[constraint_type],
bounds)
i += 1
|
adamdempsey90/fargo3d | refs/heads/master | utils/python/pyfargo3d/streams/setup.py | 1 | from distutils.core import setup, Extension
module1 = Extension('stream', sources = ['streammodule.c'])
setup (name = 'PackageName',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.